Skip to content

An AI-powered search engine with a generative UI

feat: optimize chat message preparation by reusing initialChat

Yoshiki Miura06372318a774
diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.ts
index e8d880a8..eedcf035 100644
--- a/lib/streaming/helpers/prepare-messages.ts
+++ b/lib/streaming/helpers/prepare-messages.ts
@@ -18,9 +18,20 @@ export async function prepareMessages(
): Promise<UIMessage[]> {
const { chatId, userId, trigger, messageId, initialChat } = context
+ // Performance logging
+ if (process.env.NODE_ENV === 'development') {
+ console.log('[prepareMessages] Using initialChat:', !!initialChat)
+ }
+
if (trigger === 'regenerate-assistant-message' && messageId) {
- // Handle regeneration
- const currentChat = initialChat || (await getChatAction(chatId, userId))
+ // Handle regeneration - use initialChat if available to avoid DB call
+ let currentChat = initialChat
+ if (!currentChat) {
+ if (process.env.NODE_ENV === 'development') {
+ console.log('[prepareMessages] Fetching chat from DB (regeneration)')
+ }
+ currentChat = await getChatAction(chatId, userId)
+ }
if (!currentChat || !currentChat.messages.length) {
throw new Error('No messages found')
}
@@ -81,6 +92,19 @@ export async function prepareMessages(
}
await saveMessage(chatId, messageWithId)
+
+ // If we have initialChat, append the new message instead of fetching all messages
+ if (initialChat && initialChat.messages) {
+ if (process.env.NODE_ENV === 'development') {
+ console.log('[prepareMessages] Using cached messages, skipping DB fetch')
+ }
+ return [...initialChat.messages, messageWithId]
+ }
+
+ // Fallback to fetching if no initialChat
+ if (process.env.NODE_ENV === 'development') {
+ console.log('[prepareMessages] No initialChat, fetching from DB')
+ }
const updatedChat = await getChatAction(chatId, userId)
return updatedChat?.messages || [messageWithId]
}
diff --git a/lib/streaming/helpers/types.ts b/lib/streaming/helpers/types.ts
index e8b6d0dd..2a2cbdd3 100644
--- a/lib/streaming/helpers/types.ts
+++ b/lib/streaming/helpers/types.ts
@@ -1,10 +1,13 @@
+import type { Chat } from '@/lib/db/schema'
+import type { UIMessage } from '@/lib/types/ai'
+
export interface StreamContext {
chatId: string
userId: string
modelId: string
messageId?: string
trigger?: string
- initialChat: any
+ initialChat: (Chat & { messages: UIMessage[] }) | null
abortSignal?: AbortSignal
parentTraceId?: string
}