Spaces:
Sleeping
Sleeping
import { Message } from '@prisma/client'; | |
import { MessageUI } from '../types'; | |
/** | |
* The Message we saved to database consists of a prompt and a response | |
* for the API to use, we need to break them to 2 messages, User and Assistant(if responded) | |
*/ | |
export const convertDBMessageToAPIMessage = ( | |
messages: Message[], | |
): MessageUI[] => { | |
return messages.reduce((acc, message) => { | |
const { id, mediaUrl, prompt, result, chatId } = message; | |
// fileName could be null if it's example media url | |
const [prefix, fileName] = mediaUrl.split(`${chatId}/`); | |
if (mediaUrl && prompt) { | |
acc.push({ | |
id: id + '-user', | |
role: 'user', | |
content: prompt, | |
media: [ | |
fileName | |
? prefix + | |
`${chatId}/` + | |
encodeURIComponent(decodeURIComponent(fileName)) | |
: mediaUrl, | |
], | |
}); | |
} | |
if (result && result.type === 'final_code') { | |
acc.push({ | |
id: id + '-assistant', | |
role: 'assistant', | |
content: result?.payload.code, | |
}); | |
} | |
return acc; | |
}, [] as MessageUI[]); | |
}; | |