message-utils.ts25 lines · main
1import type { UIMessage } from 'ai'
2
3/**
4 * Prepares messages for API transmission by cleaning and limiting history
5 */
6export function prepareMessagesForAPI(messages: UIMessage[]): UIMessage[] {
7 // [Joshen] Specifically limiting the chat history that get's sent to reduce the
8 // size of the context that goes into the model. This should always be an odd number
9 // as much as possible so that the first message is always the user's
10 const MAX_CHAT_HISTORY = 7
11
12 const slicedMessages = messages.slice(-MAX_CHAT_HISTORY)
13
14 // Filter out results from messages before sending to the model
15 const cleanedMessages = slicedMessages.map((_message) => {
16 const message = _message as UIMessage & { results?: unknown }
17 const cleanedMessage = { ...message } as UIMessage & { results?: unknown }
18 if (message.role === 'assistant' && message.results) {
19 delete cleanedMessage.results
20 }
21 return cleanedMessage as UIMessage
22 })
23
24 return cleanedMessages
25}