Skip to content

An AI-powered search engine with a generative UI

refactor: reorganize helper functions for better modularity

Yoshiki Miura93e1f8e9aae8
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index 782ac50f..1bb08461 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -2,6 +2,7 @@
import { revalidateTag } from 'next/cache'
+import { generateChatTitle } from '@/lib/agents/title-generator'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
import * as dbActions from '@/lib/db/actions'
import type { Chat, Message } from '@/lib/db/schema'
@@ -243,3 +244,27 @@ export async function deleteMessagesFromIndex(
return { success: true, count: result.count }
}
+
+/**
+ * Save or update chat title if it's the first conversation
+ * @param chat Existing chat object (null if new chat)
+ * @param chatId The chat ID
+ * @param message The user message to generate title from
+ * @param modelId The model ID to use for title generation
+ */
+export async function saveChatTitle(
+ chat: Chat | null,
+ chatId: string,
+ message: UIMessage | null,
+ modelId: string
+) {
+ if (!chat && message) {
+ const userContent = getTextFromParts(message.parts)
+ const title = await generateChatTitle({
+ userMessageContent: userContent,
+ modelId
+ })
+ await dbActions.updateChatTitle(chatId, title)
+ revalidateTag(`chat-${chatId}`)
+ }
+}
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 0fc327f3..daf13d32 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -9,124 +9,18 @@ import {
import { researcher } from '@/lib/agents/researcher'
import {
- createChat,
- deleteMessagesFromIndex,
getChat as getChatAction,
- saveMessage
-} from '../actions/chat'
+ saveChatTitle,
+ saveMessage} from '../actions/chat'
import { generateRelatedQuestions } from '../agents/generate-related-questions'
-import { generateChatTitle } from '../agents/title-generator'
-import { generateId } from '../db/schema'
-import { getTextFromParts, mergeUIMessages } from '../utils/message-utils'
+import { hasToolCalls, mergeUIMessages } from '../utils/message-utils'
+import {
+ prepareMessagesForRegeneration,
+ prepareMessagesForSubmission
+} from './message-preparation'
import { BaseStreamConfig } from './types'
-// Constants
-const DEFAULT_CHAT_TITLE = 'New Chat'
-
-// Helper function to check if a message contains tool calls
-function hasToolCalls(message: UIMessage | null): boolean {
- if (!message || !message.parts) return false
-
- return message.parts.some(
- (part: any) =>
- part.type &&
- (part.type.startsWith('tool-') || part.type === 'tool-call')
- )
-}
-
-// Helper function to save chat title
-async function saveChatTitle(
- chat: any,
- chatId: string,
- message: UIMessage | null,
- modelId: string
-) {
- if (!chat && message) {
- const userContent = getTextFromParts(message.parts)
- const title = await generateChatTitle({
- userMessageContent: userContent,
- modelId
- })
- const { updateChatTitle } = await import('../db/actions')
- await updateChatTitle(chatId, title)
- }
-}
-
-// Helper function to prepare messages for regeneration
-async function prepareMessagesForRegeneration(
- chatId: string,
- userId: string,
- messageId: string,
- message: UIMessage | null
-): Promise<UIMessage[]> {
- const currentChat = await getChatAction(chatId, userId)
- if (!currentChat || !currentChat.messages.length) {
- throw new Error('No messages found')
- }
-
- const messageIndex = currentChat.messages.findIndex(m => m.id === messageId)
- if (messageIndex === -1) {
- throw new Error(`Message ${messageId} not found`)
- }
-
- const targetMessage = currentChat.messages[messageIndex]
-
- if (targetMessage.role === 'assistant') {
- // Delete from this assistant message onwards
- await deleteMessagesFromIndex(chatId, messageId)
- // Use messages up to (but not including) this assistant message
- return currentChat.messages.slice(0, messageIndex)
- } else {
- // If it's a user message that was edited, save the updated message first
- if (message && message.id === messageId) {
- await saveMessage(chatId, message)
- }
- // Delete everything after this user message
- const messagesToDelete = currentChat.messages.slice(messageIndex + 1)
- if (messagesToDelete.length > 0) {
- await deleteMessagesFromIndex(chatId, messagesToDelete[0].id)
- }
- // Get updated messages including the edited one
- const updatedChat = await getChatAction(chatId, userId)
- if (updatedChat?.messages) {
- return updatedChat.messages
- } else {
- // Fallback: use current messages up to and including the edited message
- return currentChat.messages.slice(0, messageIndex + 1)
- }
- }
-}
-
-// Helper function to prepare messages for normal submission
-async function prepareMessagesForSubmission(
- chatId: string,
- userId: string,
- message: UIMessage,
- chat: any
-): Promise<UIMessage[]> {
- if (!message) {
- throw new Error('No message provided')
- }
-
- // Save the message
- const messageWithId = {
- ...message,
- id: message.id || generateId()
- }
-
- // If chat doesn't exist, create it with a temporary title
- if (!chat) {
- await createChat(chatId, DEFAULT_CHAT_TITLE)
- }
-
- await saveMessage(chatId, messageWithId)
-
- // Get all messages including the one just saved
- const updatedChat = await getChatAction(chatId, userId)
- return updatedChat?.messages || [messageWithId]
-}
-
// Helper function to handle direct response (no tool calls)
async function handleDirectResponse(
writer: UIMessageStreamWriter,
diff --git a/lib/streaming/message-preparation.ts b/lib/streaming/message-preparation.ts
new file mode 100644
index 00000000..57dcc2cf
--- /dev/null
+++ b/lib/streaming/message-preparation.ts
@@ -0,0 +1,100 @@
+import type { UIMessage } from 'ai'
+
+import {
+ createChat,
+ deleteMessagesFromIndex,
+ getChat as getChatAction,
+ saveMessage
+} from '@/lib/actions/chat'
+import { generateId } from '@/lib/db/schema'
+
+// Constants
+const DEFAULT_CHAT_TITLE = 'New Chat'
+
+/**
+ * Prepares messages for regeneration by handling message deletion and retrieval
+ * @param chatId The chat ID
+ * @param userId The user ID for authorization
+ * @param messageId The message ID to regenerate from
+ * @param message The new message (if any)
+ * @returns Array of UIMessages to send to the model
+ */
+export async function prepareMessagesForRegeneration(
+ chatId: string,
+ userId: string,
+ messageId: string,
+ message: UIMessage | null
+): Promise<UIMessage[]> {
+ const currentChat = await getChatAction(chatId, userId)
+ if (!currentChat || !currentChat.messages.length) {
+ throw new Error('No messages found')
+ }
+
+ const messageIndex = currentChat.messages.findIndex(m => m.id === messageId)
+ if (messageIndex === -1) {
+ throw new Error(`Message ${messageId} not found`)
+ }
+
+ const targetMessage = currentChat.messages[messageIndex]
+
+ if (targetMessage.role === 'assistant') {
+ // Delete from this assistant message onwards
+ await deleteMessagesFromIndex(chatId, messageId)
+ // Use messages up to (but not including) this assistant message
+ return currentChat.messages.slice(0, messageIndex)
+ } else {
+ // If it's a user message that was edited, save the updated message first
+ if (message && message.id === messageId) {
+ await saveMessage(chatId, message)
+ }
+ // Delete everything after this user message
+ const messagesToDelete = currentChat.messages.slice(messageIndex + 1)
+ if (messagesToDelete.length > 0) {
+ await deleteMessagesFromIndex(chatId, messagesToDelete[0].id)
+ }
+ // Get updated messages including the edited one
+ const updatedChat = await getChatAction(chatId, userId)
+ if (updatedChat?.messages) {
+ return updatedChat.messages
+ } else {
+ // Fallback: use current messages up to and including the edited message
+ return currentChat.messages.slice(0, messageIndex + 1)
+ }
+ }
+}
+
+/**
+ * Prepares messages for normal submission by saving the new message
+ * @param chatId The chat ID
+ * @param userId The user ID for authorization
+ * @param message The message to submit
+ * @param chat The existing chat (if any)
+ * @returns Array of UIMessages to send to the model
+ */
+export async function prepareMessagesForSubmission(
+ chatId: string,
+ userId: string,
+ message: UIMessage,
+ chat: any
+): Promise<UIMessage[]> {
+ if (!message) {
+ throw new Error('No message provided')
+ }
+
+ // Save the message
+ const messageWithId = {
+ ...message,
+ id: message.id || generateId()
+ }
+
+ // If chat doesn't exist, create it with a temporary title
+ if (!chat) {
+ await createChat(chatId, DEFAULT_CHAT_TITLE)
+ }
+
+ await saveMessage(chatId, messageWithId)
+
+ // Get all messages including the one just saved
+ const updatedChat = await getChatAction(chatId, userId)
+ return updatedChat?.messages || [messageWithId]
+}
\ No newline at end of file
diff --git a/lib/utils/message-utils.ts b/lib/utils/message-utils.ts
index 137c40d3..3cf8aa72 100644
--- a/lib/utils/message-utils.ts
+++ b/lib/utils/message-utils.ts
@@ -115,3 +115,18 @@ export function mergeUIMessages(
parts: [...primaryMessage.parts, ...secondaryMessage.parts]
}
}
+
+/**
+ * Checks if a UIMessage contains tool calls
+ * @param message The message to check for tool calls
+ * @returns true if the message contains tool calls, false otherwise
+ */
+export function hasToolCalls(message: UIMessage | null): boolean {
+ if (!message || !message.parts) return false
+
+ return message.parts.some(
+ (part: any) =>
+ part.type &&
+ (part.type.startsWith('tool-') || part.type === 'tool-call')
+ )
+}