mirror of
https://github.com/farcasclaudiu/Flowise.git
synced 2026-06-28 09:00:52 +03:00
Feature/Custom Assistant Builder (#3631)
* add custom assistant builder * add tools to custom assistant * add save assistant button
This commit is contained in:
@@ -2,7 +2,9 @@ import { IAction, ICommonObject, IFileUpload, INode, INodeData as INodeDataFromC
|
||||
|
||||
export type MessageType = 'apiMessage' | 'userMessage'
|
||||
|
||||
export type ChatflowType = 'CHATFLOW' | 'MULTIAGENT'
|
||||
export type ChatflowType = 'CHATFLOW' | 'MULTIAGENT' | 'ASSISTANT'
|
||||
|
||||
export type AssistantType = 'CUSTOM' | 'OPENAI' | 'AZURE'
|
||||
|
||||
export enum ChatType {
|
||||
INTERNAL = 'INTERNAL',
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Request, Response, NextFunction } from 'express'
|
||||
import assistantsService from '../../services/assistants'
|
||||
import { InternalFlowiseError } from '../../errors/internalFlowiseError'
|
||||
import { StatusCodes } from 'http-status-codes'
|
||||
import { AssistantType } from '../../Interface'
|
||||
|
||||
const createAssistant = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
@@ -35,7 +36,8 @@ const deleteAssistant = async (req: Request, res: Response, next: NextFunction)
|
||||
|
||||
const getAllAssistants = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const apiResponse = await assistantsService.getAllAssistants()
|
||||
const type = req.query.type as AssistantType
|
||||
const apiResponse = await assistantsService.getAllAssistants(type)
|
||||
return res.json(apiResponse)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
@@ -78,10 +80,56 @@ const updateAssistant = async (req: Request, res: Response, next: NextFunction)
|
||||
}
|
||||
}
|
||||
|
||||
const getChatModels = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const apiResponse = await assistantsService.getChatModels()
|
||||
return res.json(apiResponse)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
const getDocumentStores = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const apiResponse = await assistantsService.getDocumentStores()
|
||||
return res.json(apiResponse)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
const getTools = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const apiResponse = await assistantsService.getTools()
|
||||
return res.json(apiResponse)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
const generateAssistantInstruction = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
if (!req.body) {
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.PRECONDITION_FAILED,
|
||||
`Error: assistantsController.generateAssistantInstruction - body not provided!`
|
||||
)
|
||||
}
|
||||
const apiResponse = await assistantsService.generateAssistantInstruction(req.body.task, req.body.selectedChatModel)
|
||||
return res.json(apiResponse)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
createAssistant,
|
||||
deleteAssistant,
|
||||
getAllAssistants,
|
||||
getAssistantById,
|
||||
updateAssistant
|
||||
updateAssistant,
|
||||
getChatModels,
|
||||
getDocumentStores,
|
||||
getTools,
|
||||
generateAssistantInstruction
|
||||
}
|
||||
|
||||
@@ -410,6 +410,24 @@ const refreshDocStoreMiddleware = async (req: Request, res: Response, next: Next
|
||||
}
|
||||
}
|
||||
|
||||
const generateDocStoreToolDesc = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
if (typeof req.params.id === 'undefined' || req.params.id === '') {
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.PRECONDITION_FAILED,
|
||||
`Error: documentStoreController.generateDocStoreToolDesc - storeId not provided!`
|
||||
)
|
||||
}
|
||||
if (typeof req.body === 'undefined') {
|
||||
throw new Error('Error: documentStoreController.generateDocStoreToolDesc - body not provided!')
|
||||
}
|
||||
const apiResponse = await documentStoreService.generateDocStoreToolDesc(req.params.id, req.body.selectedChatModel)
|
||||
return res.json(apiResponse)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
deleteDocumentStore,
|
||||
createDocumentStore,
|
||||
@@ -434,5 +452,6 @@ export default {
|
||||
getRateLimiterMiddleware,
|
||||
upsertDocStoreMiddleware,
|
||||
refreshDocStoreMiddleware,
|
||||
saveProcessingLoader
|
||||
saveProcessingLoader,
|
||||
generateDocStoreToolDesc
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable */
|
||||
import { Entity, Column, CreateDateColumn, UpdateDateColumn, PrimaryGeneratedColumn } from 'typeorm'
|
||||
import { IAssistant } from '../../Interface'
|
||||
import { AssistantType, IAssistant } from '../../Interface'
|
||||
|
||||
@Entity()
|
||||
export class Assistant implements IAssistant {
|
||||
@@ -16,6 +16,9 @@ export class Assistant implements IAssistant {
|
||||
@Column({ nullable: true })
|
||||
iconSrc?: string
|
||||
|
||||
@Column({ nullable: true, type: 'text' })
|
||||
type?: AssistantType
|
||||
|
||||
@Column({ type: 'timestamp' })
|
||||
@CreateDateColumn()
|
||||
createdDate: Date
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm'
|
||||
|
||||
export class AddTypeToAssistant1733011290987 implements MigrationInterface {
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
const columnExists = await queryRunner.hasColumn('assistant', 'type')
|
||||
if (!columnExists) {
|
||||
await queryRunner.query(`ALTER TABLE \`assistant\` ADD COLUMN \`type\` TEXT;`)
|
||||
await queryRunner.query(`UPDATE \`assistant\` SET \`type\` = 'OPENAI';`)
|
||||
}
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE \`assistant\` DROP COLUMN \`type\`;`)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { LongTextColumn1722301395521 } from './1722301395521-LongTextColumn'
|
||||
import { AddCustomTemplate1725629836652 } from './1725629836652-AddCustomTemplate'
|
||||
import { AddArtifactsToChatMessage1726156258465 } from './1726156258465-AddArtifactsToChatMessage'
|
||||
import { AddFollowUpPrompts1726666318346 } from './1726666318346-AddFollowUpPrompts'
|
||||
import { AddTypeToAssistant1733011290987 } from './1733011290987-AddTypeToAssistant'
|
||||
|
||||
export const mariadbMigrations = [
|
||||
Init1693840429259,
|
||||
@@ -57,5 +58,6 @@ export const mariadbMigrations = [
|
||||
LongTextColumn1722301395521,
|
||||
AddCustomTemplate1725629836652,
|
||||
AddArtifactsToChatMessage1726156258465,
|
||||
AddFollowUpPrompts1726666318346
|
||||
AddFollowUpPrompts1726666318346,
|
||||
AddTypeToAssistant1733011290987
|
||||
]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm'
|
||||
|
||||
export class AddTypeToAssistant1733011290987 implements MigrationInterface {
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
const columnExists = await queryRunner.hasColumn('assistant', 'type')
|
||||
if (!columnExists) {
|
||||
await queryRunner.query(`ALTER TABLE \`assistant\` ADD COLUMN \`type\` TEXT;`)
|
||||
await queryRunner.query(`UPDATE \`assistant\` SET \`type\` = 'OPENAI';`)
|
||||
}
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE \`assistant\` DROP COLUMN \`type\`;`)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { LongTextColumn1722301395521 } from './1722301395521-LongTextColumn'
|
||||
import { AddCustomTemplate1725629836652 } from './1725629836652-AddCustomTemplate'
|
||||
import { AddArtifactsToChatMessage1726156258465 } from './1726156258465-AddArtifactsToChatMessage'
|
||||
import { AddFollowUpPrompts1726666302024 } from './1726666302024-AddFollowUpPrompts'
|
||||
import { AddTypeToAssistant1733011290987 } from './1733011290987-AddTypeToAssistant'
|
||||
|
||||
export const mysqlMigrations = [
|
||||
Init1693840429259,
|
||||
@@ -57,5 +58,6 @@ export const mysqlMigrations = [
|
||||
LongTextColumn1722301395521,
|
||||
AddCustomTemplate1725629836652,
|
||||
AddArtifactsToChatMessage1726156258465,
|
||||
AddFollowUpPrompts1726666302024
|
||||
AddFollowUpPrompts1726666302024,
|
||||
AddTypeToAssistant1733011290987
|
||||
]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm'
|
||||
|
||||
export class AddTypeToAssistant1733011290987 implements MigrationInterface {
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
const columnExists = await queryRunner.hasColumn('assistant', 'type')
|
||||
if (!columnExists) {
|
||||
await queryRunner.query(`ALTER TABLE "assistant" ADD COLUMN "type" TEXT;`)
|
||||
await queryRunner.query(`UPDATE "assistant" SET "type" = 'OPENAI';`)
|
||||
}
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE "assistant" DROP COLUMN "type";`)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { AddActionToChatMessage1721078251523 } from './1721078251523-AddActionTo
|
||||
import { AddCustomTemplate1725629836652 } from './1725629836652-AddCustomTemplate'
|
||||
import { AddArtifactsToChatMessage1726156258465 } from './1726156258465-AddArtifactsToChatMessage'
|
||||
import { AddFollowUpPrompts1726666309552 } from './1726666309552-AddFollowUpPrompts'
|
||||
import { AddTypeToAssistant1733011290987 } from './1733011290987-AddTypeToAssistant'
|
||||
|
||||
export const postgresMigrations = [
|
||||
Init1693891895163,
|
||||
@@ -57,5 +58,6 @@ export const postgresMigrations = [
|
||||
AddActionToChatMessage1721078251523,
|
||||
AddCustomTemplate1725629836652,
|
||||
AddArtifactsToChatMessage1726156258465,
|
||||
AddFollowUpPrompts1726666309552
|
||||
AddFollowUpPrompts1726666309552,
|
||||
AddTypeToAssistant1733011290987
|
||||
]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm'
|
||||
|
||||
export class AddTypeToAssistant1733011290987 implements MigrationInterface {
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
const columnExists = await queryRunner.hasColumn('assistant', 'type')
|
||||
if (!columnExists) {
|
||||
await queryRunner.query(`ALTER TABLE "assistant" ADD COLUMN "type" TEXT;`)
|
||||
await queryRunner.query(`UPDATE "assistant" SET "type" = 'OPENAI';`)
|
||||
}
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE "assistant" DROP COLUMN "type";`)
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import { AddActionToChatMessage1721078251523 } from './1721078251523-AddActionTo
|
||||
import { AddArtifactsToChatMessage1726156258465 } from './1726156258465-AddArtifactsToChatMessage'
|
||||
import { AddCustomTemplate1725629836652 } from './1725629836652-AddCustomTemplate'
|
||||
import { AddFollowUpPrompts1726666294213 } from './1726666294213-AddFollowUpPrompts'
|
||||
import { AddTypeToAssistant1733011290987 } from './1733011290987-AddTypeToAssistant'
|
||||
|
||||
export const sqliteMigrations = [
|
||||
Init1693835579790,
|
||||
@@ -55,5 +56,6 @@ export const sqliteMigrations = [
|
||||
AddActionToChatMessage1721078251523,
|
||||
AddArtifactsToChatMessage1726156258465,
|
||||
AddCustomTemplate1725629836652,
|
||||
AddFollowUpPrompts1726666294213
|
||||
AddFollowUpPrompts1726666294213,
|
||||
AddTypeToAssistant1733011290987
|
||||
]
|
||||
|
||||
@@ -16,4 +16,11 @@ router.put(['/', '/:id'], assistantsController.updateAssistant)
|
||||
// DELETE
|
||||
router.delete(['/', '/:id'], assistantsController.deleteAssistant)
|
||||
|
||||
router.get('/components/chatmodels', assistantsController.getChatModels)
|
||||
router.get('/components/docstores', assistantsController.getDocumentStores)
|
||||
router.get('/components/tools', assistantsController.getTools)
|
||||
|
||||
// Generate Assistant Instruction
|
||||
router.post('/generate/instruction', assistantsController.generateAssistantInstruction)
|
||||
|
||||
export default router
|
||||
|
||||
@@ -61,4 +61,7 @@ router.get('/components/recordmanager', documentStoreController.getRecordManager
|
||||
// update the selected vector store from the playground
|
||||
router.post('/vectorstore/update', documentStoreController.updateVectorStoreConfigOnly)
|
||||
|
||||
// generate docstore tool description
|
||||
router.post('/generate-tool-desc/:id', documentStoreController.generateDocStoreToolDesc)
|
||||
|
||||
export default router
|
||||
|
||||
@@ -4,11 +4,17 @@ import { uniqWith, isEqual, cloneDeep } from 'lodash'
|
||||
import { getRunningExpressApp } from '../../utils/getRunningExpressApp'
|
||||
import { Assistant } from '../../database/entities/Assistant'
|
||||
import { Credential } from '../../database/entities/Credential'
|
||||
import { decryptCredentialData, getAppVersion } from '../../utils'
|
||||
import { databaseEntities, decryptCredentialData, getAppVersion } from '../../utils'
|
||||
import { InternalFlowiseError } from '../../errors/internalFlowiseError'
|
||||
import { getErrorMessage } from '../../errors/utils'
|
||||
import { DeleteResult, QueryRunner } from 'typeorm'
|
||||
import { FLOWISE_METRIC_COUNTERS, FLOWISE_COUNTER_STATUS } from '../../Interface.Metrics'
|
||||
import { AssistantType } from '../../Interface'
|
||||
import nodesService from '../nodes'
|
||||
import { DocumentStore } from '../../database/entities/DocumentStore'
|
||||
import { ICommonObject } from 'flowise-components'
|
||||
import logger from '../../utils/logger'
|
||||
import { ASSISTANT_PROMPT_GENERATOR } from '../../utils/prompt'
|
||||
|
||||
const createAssistant = async (requestBody: any): Promise<Assistant> => {
|
||||
try {
|
||||
@@ -17,6 +23,24 @@ const createAssistant = async (requestBody: any): Promise<Assistant> => {
|
||||
throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Invalid request body`)
|
||||
}
|
||||
const assistantDetails = JSON.parse(requestBody.details)
|
||||
|
||||
if (requestBody.type === 'CUSTOM') {
|
||||
const newAssistant = new Assistant()
|
||||
Object.assign(newAssistant, requestBody)
|
||||
|
||||
const assistant = appServer.AppDataSource.getRepository(Assistant).create(newAssistant)
|
||||
const dbResponse = await appServer.AppDataSource.getRepository(Assistant).save(assistant)
|
||||
|
||||
await appServer.telemetry.sendTelemetry('assistant_created', {
|
||||
version: await getAppVersion(),
|
||||
assistantId: dbResponse.id
|
||||
})
|
||||
appServer.metricsProvider?.incrementCounter(FLOWISE_METRIC_COUNTERS.ASSISTANT_CREATED, {
|
||||
status: FLOWISE_COUNTER_STATUS.SUCCESS
|
||||
})
|
||||
return dbResponse
|
||||
}
|
||||
|
||||
try {
|
||||
const credential = await appServer.AppDataSource.getRepository(Credential).findOneBy({
|
||||
id: requestBody.credential
|
||||
@@ -131,6 +155,10 @@ const deleteAssistant = async (assistantId: string, isDeleteBoth: any): Promise<
|
||||
if (!assistant) {
|
||||
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Assistant ${assistantId} not found`)
|
||||
}
|
||||
if (assistant.type === 'CUSTOM') {
|
||||
const dbResponse = await appServer.AppDataSource.getRepository(Assistant).delete({ id: assistantId })
|
||||
return dbResponse
|
||||
}
|
||||
try {
|
||||
const assistantDetails = JSON.parse(assistant.details)
|
||||
const credential = await appServer.AppDataSource.getRepository(Credential).findOneBy({
|
||||
@@ -163,9 +191,15 @@ const deleteAssistant = async (assistantId: string, isDeleteBoth: any): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
const getAllAssistants = async (): Promise<Assistant[]> => {
|
||||
const getAllAssistants = async (type?: AssistantType): Promise<Assistant[]> => {
|
||||
try {
|
||||
const appServer = getRunningExpressApp()
|
||||
if (type) {
|
||||
const dbResponse = await appServer.AppDataSource.getRepository(Assistant).findBy({
|
||||
type
|
||||
})
|
||||
return dbResponse
|
||||
}
|
||||
const dbResponse = await appServer.AppDataSource.getRepository(Assistant).find()
|
||||
return dbResponse
|
||||
} catch (error) {
|
||||
@@ -204,6 +238,17 @@ const updateAssistant = async (assistantId: string, requestBody: any): Promise<A
|
||||
if (!assistant) {
|
||||
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Assistant ${assistantId} not found`)
|
||||
}
|
||||
|
||||
if (assistant.type === 'CUSTOM') {
|
||||
const body = requestBody
|
||||
const updateAssistant = new Assistant()
|
||||
Object.assign(updateAssistant, body)
|
||||
|
||||
appServer.AppDataSource.getRepository(Assistant).merge(assistant, updateAssistant)
|
||||
const dbResponse = await appServer.AppDataSource.getRepository(Assistant).save(assistant)
|
||||
return dbResponse
|
||||
}
|
||||
|
||||
try {
|
||||
const openAIAssistantId = JSON.parse(assistant.details)?.id
|
||||
const body = requestBody
|
||||
@@ -336,7 +381,115 @@ const importAssistants = async (newAssistants: Partial<Assistant>[], queryRunner
|
||||
} catch (error) {
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.INTERNAL_SERVER_ERROR,
|
||||
`Error: variableService.importVariables - ${getErrorMessage(error)}`
|
||||
`Error: assistantsService.importAssistants - ${getErrorMessage(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const getChatModels = async (): Promise<any> => {
|
||||
try {
|
||||
const dbResponse = await nodesService.getAllNodesForCategory('Chat Models')
|
||||
return dbResponse.filter((node) => !node.tags?.includes('LlamaIndex'))
|
||||
} catch (error) {
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.INTERNAL_SERVER_ERROR,
|
||||
`Error: assistantsService.getChatModels - ${getErrorMessage(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const getDocumentStores = async (): Promise<any> => {
|
||||
try {
|
||||
const appServer = getRunningExpressApp()
|
||||
const stores = await appServer.AppDataSource.getRepository(DocumentStore).find()
|
||||
const returnData = []
|
||||
for (const store of stores) {
|
||||
if (store.status === 'UPSERTED') {
|
||||
const obj = {
|
||||
name: store.id,
|
||||
label: store.name,
|
||||
description: store.description
|
||||
}
|
||||
returnData.push(obj)
|
||||
}
|
||||
}
|
||||
return returnData
|
||||
} catch (error) {
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.INTERNAL_SERVER_ERROR,
|
||||
`Error: assistantsService.getDocumentStores - ${getErrorMessage(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const getTools = async (): Promise<any> => {
|
||||
try {
|
||||
const tools = await nodesService.getAllNodesForCategory('Tools')
|
||||
const whitelistTypes = [
|
||||
'asyncOptions',
|
||||
'options',
|
||||
'multiOptions',
|
||||
'datagrid',
|
||||
'string',
|
||||
'number',
|
||||
'boolean',
|
||||
'password',
|
||||
'json',
|
||||
'code',
|
||||
'date',
|
||||
'file',
|
||||
'folder',
|
||||
'tabs'
|
||||
]
|
||||
// filter out those tools that input params type are not in the list
|
||||
const filteredTools = tools.filter((tool) => {
|
||||
const inputs = tool.inputs || []
|
||||
return inputs.every((input) => whitelistTypes.includes(input.type))
|
||||
})
|
||||
return filteredTools
|
||||
} catch (error) {
|
||||
throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: assistantsService.getTools - ${getErrorMessage(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const generateAssistantInstruction = async (task: string, selectedChatModel: ICommonObject): Promise<ICommonObject> => {
|
||||
try {
|
||||
const appServer = getRunningExpressApp()
|
||||
|
||||
if (selectedChatModel && Object.keys(selectedChatModel).length > 0) {
|
||||
const nodeInstanceFilePath = appServer.nodesPool.componentNodes[selectedChatModel.name].filePath as string
|
||||
const nodeModule = await import(nodeInstanceFilePath)
|
||||
const newNodeInstance = new nodeModule.nodeClass()
|
||||
const nodeData = {
|
||||
credential: selectedChatModel.credential || selectedChatModel.inputs['FLOWISE_CREDENTIAL_ID'] || undefined,
|
||||
inputs: selectedChatModel.inputs,
|
||||
id: `${selectedChatModel.name}_0`
|
||||
}
|
||||
const options: ICommonObject = {
|
||||
appDataSource: appServer.AppDataSource,
|
||||
databaseEntities,
|
||||
logger
|
||||
}
|
||||
const llmNodeInstance = await newNodeInstance.init(nodeData, '', options)
|
||||
const response = await llmNodeInstance.invoke([
|
||||
{
|
||||
role: 'user',
|
||||
content: ASSISTANT_PROMPT_GENERATOR.replace('{{task}}', task)
|
||||
}
|
||||
])
|
||||
const content = response?.content || response.kwargs?.content
|
||||
|
||||
return { content }
|
||||
}
|
||||
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.INTERNAL_SERVER_ERROR,
|
||||
`Error: assistantsService.generateAssistantInstruction - Error generating tool description`
|
||||
)
|
||||
} catch (error) {
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.INTERNAL_SERVER_ERROR,
|
||||
`Error: assistantsService.generateAssistantInstruction - ${getErrorMessage(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -347,5 +500,9 @@ export default {
|
||||
getAllAssistants,
|
||||
getAssistantById,
|
||||
updateAssistant,
|
||||
importAssistants
|
||||
importAssistants,
|
||||
getChatModels,
|
||||
getDocumentStores,
|
||||
getTools,
|
||||
generateAssistantInstruction
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ import { App } from '../../index'
|
||||
import { UpsertHistory } from '../../database/entities/UpsertHistory'
|
||||
import { cloneDeep, omit } from 'lodash'
|
||||
import { FLOWISE_COUNTER_STATUS, FLOWISE_METRIC_COUNTERS } from '../../Interface.Metrics'
|
||||
import { DOCUMENTSTORE_TOOL_DESCRIPTION_PROMPT_GENERATOR } from '../../utils/prompt'
|
||||
|
||||
const DOCUMENT_STORE_BASE_FOLDER = 'docustore'
|
||||
|
||||
@@ -1568,6 +1569,63 @@ const refreshDocStoreMiddleware = async (storeId: string, data?: IDocumentStoreR
|
||||
}
|
||||
}
|
||||
|
||||
const generateDocStoreToolDesc = async (docStoreId: string, selectedChatModel: ICommonObject): Promise<string> => {
|
||||
try {
|
||||
const appServer = getRunningExpressApp()
|
||||
|
||||
// get matching DocumentStoreFileChunk storeId with docStoreId, and only the first 4 chunks sorted by chunkNo
|
||||
const chunks = await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).findBy({
|
||||
storeId: docStoreId
|
||||
})
|
||||
|
||||
if (!chunks?.length) {
|
||||
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `DocumentStore ${docStoreId} chunks not found`)
|
||||
}
|
||||
|
||||
// sort the chunks by chunkNo
|
||||
chunks.sort((a, b) => a.chunkNo - b.chunkNo)
|
||||
|
||||
// get the first 4 chunks
|
||||
const chunksPageContent = chunks
|
||||
.slice(0, 4)
|
||||
.map((chunk) => {
|
||||
return chunk.pageContent
|
||||
})
|
||||
.join('\n')
|
||||
|
||||
if (selectedChatModel && Object.keys(selectedChatModel).length > 0) {
|
||||
const nodeInstanceFilePath = appServer.nodesPool.componentNodes[selectedChatModel.name].filePath as string
|
||||
const nodeModule = await import(nodeInstanceFilePath)
|
||||
const newNodeInstance = new nodeModule.nodeClass()
|
||||
const nodeData = {
|
||||
credential: selectedChatModel.credential || selectedChatModel.inputs['FLOWISE_CREDENTIAL_ID'] || undefined,
|
||||
inputs: selectedChatModel.inputs,
|
||||
id: `${selectedChatModel.name}_0`
|
||||
}
|
||||
const options: ICommonObject = {
|
||||
appDataSource: appServer.AppDataSource,
|
||||
databaseEntities,
|
||||
logger
|
||||
}
|
||||
const llmNodeInstance = await newNodeInstance.init(nodeData, '', options)
|
||||
const response = await llmNodeInstance.invoke(
|
||||
DOCUMENTSTORE_TOOL_DESCRIPTION_PROMPT_GENERATOR.replace('{context}', chunksPageContent)
|
||||
)
|
||||
return response
|
||||
}
|
||||
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.INTERNAL_SERVER_ERROR,
|
||||
`Error: documentStoreServices.generateDocStoreToolDesc - Error generating tool description`
|
||||
)
|
||||
} catch (error) {
|
||||
throw new InternalFlowiseError(
|
||||
StatusCodes.INTERNAL_SERVER_ERROR,
|
||||
`Error: documentStoreServices.generateDocStoreToolDesc - ${getErrorMessage(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
updateDocumentStoreUsage,
|
||||
deleteDocumentStore,
|
||||
@@ -1594,5 +1652,6 @@ export default {
|
||||
deleteVectorStoreFromStore,
|
||||
updateVectorStoreConfigOnly,
|
||||
upsertDocStoreMiddleware,
|
||||
refreshDocStoreMiddleware
|
||||
refreshDocStoreMiddleware,
|
||||
generateDocStoreToolDesc
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
export const ASSISTANT_PROMPT_GENERATOR = `Given a task description, produce a detailed system prompt to guide a language model in completing the task effectively.
|
||||
|
||||
<task_description>
|
||||
{{task}}
|
||||
</task_description>
|
||||
|
||||
# Guidelines
|
||||
|
||||
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
|
||||
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
|
||||
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
|
||||
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
|
||||
- Conclusion, classifications, or results should ALWAYS appear last.
|
||||
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
|
||||
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
|
||||
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
|
||||
- Formatting: Use markdown features for readability. DO NOT USE \`\`\` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
|
||||
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
|
||||
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
|
||||
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
|
||||
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
|
||||
- JSON should never be wrapped in code blocks (\`\`\`) unless explicitly requested.
|
||||
|
||||
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
|
||||
|
||||
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
|
||||
|
||||
[Additional details as needed.]
|
||||
|
||||
[Optional sections with headings or bullet points for detailed steps.]
|
||||
|
||||
# Steps [optional]
|
||||
|
||||
[optional: a detailed breakdown of the steps necessary to accomplish the task]
|
||||
|
||||
# Output Format
|
||||
|
||||
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
|
||||
|
||||
# Examples [optional]
|
||||
|
||||
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
|
||||
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
|
||||
|
||||
# Notes [optional]
|
||||
|
||||
[optional: edge cases, details, and an area to call or repeat out specific important considerations]`
|
||||
|
||||
export const DOCUMENTSTORE_TOOL_DESCRIPTION_PROMPT_GENERATOR = `Here's the document context for which I would like you to create a short sentence of, under what condition this information is useful. Sentence must not more than 1024 characters.
|
||||
|
||||
<context>
|
||||
{context}
|
||||
</context>
|
||||
|
||||
Based on context, please create a short sentence that another AI could use as tool description. The short sentence should:
|
||||
- Use the same language as context.
|
||||
Please generate the short sentence and output only the short sentence.`
|
||||
Reference in New Issue
Block a user