import { Message } from '@prisma/client'; import { MessageAssistantResponse, MessageUI } from '../types'; import { ChunkBody } from './content'; /** * The Message we saved to database consists of a prompt and a response * for the UI to use, we need to break them to 2 messages, User and Assistant(if responded) */ export const convertDBMessageToUIMessage = ( messages: Message[], ): MessageUI[] => { return messages.reduce((acc, message) => { const { id, mediaUrl, prompt, response, result } = message; if (mediaUrl && prompt) { acc.push({ id: id + '-user', role: 'user', content: prompt, mediaUrl, }); } if (response) { acc.push({ id: id + '-assistant', role: 'assistant', content: response, }); } return acc; }, [] as MessageUI[]); }; export const convertAssistantUIMessageToDBMessageResponse = ( message: MessageUI, ): MessageAssistantResponse => { let result = null; const lines = message.content.split('\n'); for (let line of lines) { try { const json = JSON.parse(line) as ChunkBody; if (json.type == 'final_code') { result = json as PrismaJson.FinalChatResult; break; } } catch (e) { console.error((e as Error).message); } } return { response: message.content, result, }; };