modify addChatMessage

This commit is contained in:
chungyau97
2023-09-15 21:25:28 +08:00
parent bc7d95cf9d
commit 7b54f17a58
4 changed files with 35 additions and 29 deletions
+4
View File
@@ -2,6 +2,10 @@ import { ICommonObject, INode, INodeData as INodeDataFromComponent, INodeParams
export type MessageType = 'apiMessage' | 'userMessage' export type MessageType = 'apiMessage' | 'userMessage'
export enum chatType {
INTERNAL = 'INTERNAL',
EXTERNAL = 'EXTERNAL'
}
/** /**
* Databases * Databases
*/ */
+31 -7
View File
@@ -16,7 +16,8 @@ import {
IReactFlowObject, IReactFlowObject,
INodeData, INodeData,
IDatabaseExport, IDatabaseExport,
ICredentialReturnResponse ICredentialReturnResponse,
chatType
} from './Interface' } from './Interface'
import { import {
getNodeModulesPackagePath, getNodeModulesPackagePath,
@@ -404,12 +405,7 @@ export class App {
// Add chatmessages for chatflowid // Add chatmessages for chatflowid
this.app.post('/api/v1/chatmessage/:id', async (req: Request, res: Response) => { this.app.post('/api/v1/chatmessage/:id', async (req: Request, res: Response) => {
const body = req.body const body = req.body
const newChatMessage = new ChatMessage() const results = await this.addChatMessage(body)
Object.assign(newChatMessage, body)
const chatmessage = this.AppDataSource.getRepository(ChatMessage).create(newChatMessage)
const results = await this.AppDataSource.getRepository(ChatMessage).save(chatmessage)
return res.json(results) return res.json(results)
}) })
@@ -818,6 +814,18 @@ export class App {
} }
} }
/**
* Add Chat Message
* @param {any} chatMessage
*/
async addChatMessage(chatMessage: any) {
const newChatMessage = new ChatMessage()
Object.assign(newChatMessage, chatMessage)
const chatmessage = this.AppDataSource.getRepository(ChatMessage).create(newChatMessage)
return await this.AppDataSource.getRepository(ChatMessage).save(chatmessage)
}
/** /**
* Process Prediction * Process Prediction
* @param {Request} req * @param {Request} req
@@ -844,6 +852,13 @@ export class App {
await this.validateKey(req, res, chatflow) await this.validateKey(req, res, chatflow)
} }
await this.addChatMessage({
role: 'userMessage',
content: incomingInput.question,
chatflowid: chatflowid,
chatType: isInternal ? chatType.INTERNAL : chatType.EXTERNAL
})
let isStreamValid = false let isStreamValid = false
const files = (req.files as any[]) || [] const files = (req.files as any[]) || []
@@ -991,6 +1006,15 @@ export class App {
analytic: chatflow.analytic analytic: chatflow.analytic
}) })
const apiMessage: any = {
role: 'apiMessage',
content: typeof result === 'string' ? result : result.text,
chatflowid: chatflowid,
chatType: isInternal ? chatType.INTERNAL : chatType.EXTERNAL
}
if (result?.sourceDocuments) apiMessage.sourceDocuments = JSON.stringify(result.sourceDocuments)
await this.addChatMessage(apiMessage)
logger.debug(`[server]: Finished running ${nodeToExecuteData.label} (${nodeToExecuteData.id})`) logger.debug(`[server]: Finished running ${nodeToExecuteData.label} (${nodeToExecuteData.id})`)
return res.json(result) return res.json(result)
} catch (e: any) { } catch (e: any) {
-3
View File
@@ -2,12 +2,9 @@ import client from './client'
const getChatmessageFromChatflow = (id) => client.get(`/chatmessage/${id}`) const getChatmessageFromChatflow = (id) => client.get(`/chatmessage/${id}`)
const createNewChatmessage = (id, body) => client.post(`/chatmessage/${id}`, body)
const deleteChatmessage = (id) => client.delete(`/chatmessage/${id}`) const deleteChatmessage = (id) => client.delete(`/chatmessage/${id}`)
export default { export default {
getChatmessageFromChatflow, getChatmessageFromChatflow,
createNewChatmessage,
deleteChatmessage deleteChatmessage
} }
@@ -104,20 +104,6 @@ export const ChatMessage = ({ open, chatflowid, isDialog }) => {
const onChange = useCallback((e) => setUserInput(e.target.value), [setUserInput]) const onChange = useCallback((e) => setUserInput(e.target.value), [setUserInput])
const addChatMessage = async (message, type, sourceDocuments) => {
try {
const newChatMessageBody = {
role: type,
content: message,
chatflowid: chatflowid
}
if (sourceDocuments) newChatMessageBody.sourceDocuments = JSON.stringify(sourceDocuments)
await chatmessageApi.createNewChatmessage(chatflowid, newChatMessageBody)
} catch (error) {
console.error(error)
}
}
const updateLastMessage = (text) => { const updateLastMessage = (text) => {
setMessages((prevMessages) => { setMessages((prevMessages) => {
let allMessages = [...cloneDeep(prevMessages)] let allMessages = [...cloneDeep(prevMessages)]
@@ -140,7 +126,6 @@ export const ChatMessage = ({ open, chatflowid, isDialog }) => {
const handleError = (message = 'Oops! There seems to be an error. Please try again.') => { const handleError = (message = 'Oops! There seems to be an error. Please try again.') => {
message = message.replace(`Unable to parse JSON response from chat agent.\n\n`, '') message = message.replace(`Unable to parse JSON response from chat agent.\n\n`, '')
setMessages((prevMessages) => [...prevMessages, { message, type: 'apiMessage' }]) setMessages((prevMessages) => [...prevMessages, { message, type: 'apiMessage' }])
addChatMessage(message, 'apiMessage')
setLoading(false) setLoading(false)
setUserInput('') setUserInput('')
setTimeout(() => { setTimeout(() => {
@@ -158,8 +143,6 @@ export const ChatMessage = ({ open, chatflowid, isDialog }) => {
setLoading(true) setLoading(true)
setMessages((prevMessages) => [...prevMessages, { message: userInput, type: 'userMessage' }]) setMessages((prevMessages) => [...prevMessages, { message: userInput, type: 'userMessage' }])
// waiting for first chatmessage saved, the first chatmessage will be used in sendMessageAndGetPrediction
await addChatMessage(userInput, 'userMessage')
// Send user question and history to API // Send user question and history to API
try { try {
@@ -183,12 +166,10 @@ export const ChatMessage = ({ open, chatflowid, isDialog }) => {
{ message: data.text, sourceDocuments: data.sourceDocuments, type: 'apiMessage' } { message: data.text, sourceDocuments: data.sourceDocuments, type: 'apiMessage' }
]) ])
} }
addChatMessage(data.text, 'apiMessage', data.sourceDocuments)
} else { } else {
if (!isChatFlowAvailableToStream) { if (!isChatFlowAvailableToStream) {
setMessages((prevMessages) => [...prevMessages, { message: data, type: 'apiMessage' }]) setMessages((prevMessages) => [...prevMessages, { message: data, type: 'apiMessage' }])
} }
addChatMessage(data, 'apiMessage')
} }
setLoading(false) setLoading(false)
setUserInput('') setUserInput('')