Skip to content

An AI-powered search engine with a generative UI

refactor: finalize related questions data parts implementation

Yoshiki Miura17b5942fd8a1
diff --git a/components/related-questions.tsx b/components/related-questions.tsx
index 73b1cb52..4e8606c1 100644
--- a/components/related-questions.tsx
+++ b/components/related-questions.tsx
@@ -5,16 +5,22 @@ import React from 'react'
import { ArrowRight } from 'lucide-react'
import { Button } from './ui/button'
+import { Skeleton } from './ui/skeleton'
import { CollapsibleMessage } from './collapsible-message'
import { Section } from './section'
+interface RelatedQuestionsData {
+ status: 'loading' | 'success' | 'error'
+ questions?: Array<{ question: string }>
+}
+
interface RelatedQuestionsProps {
- questions: Array<{ question: string }>
+ data: RelatedQuestionsData
onQuerySelect: (query: string) => void
}
export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
- questions,
+ data,
onQuerySelect
}) => {
return (
@@ -27,22 +33,43 @@ export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
showBorder={false}
>
<Section title="Related" className="pt-0 pb-4">
- <div className="flex flex-col">
- {questions.map((item, index) => (
- <div className="flex items-start w-full" key={index}>
- <ArrowRight className="h-4 w-4 mr-2 mt-1.5 flex-shrink-0 text-accent-foreground/50" />
- <Button
- variant="link"
- className="flex-1 justify-start px-0 py-1 h-fit font-semibold text-accent-foreground/50 whitespace-normal text-left"
- type="submit"
- name={'related_query'}
- value={item.question}
- onClick={() => onQuerySelect(item.question)}
- >
- {item.question}
- </Button>
+ <div className="flex flex-col gap-2">
+ {data.status === 'loading' && (
+ <>
+ {[1, 2, 3].map((_, index) => (
+ <div className="flex items-start w-full" key={index}>
+ <ArrowRight className="h-4 w-4 mr-2 mt-1.5 flex-shrink-0 text-accent-foreground/50" />
+ <Skeleton className="h-6 w-full" />
+ </div>
+ ))}
+ </>
+ )}
+
+ {data.status === 'error' && (
+ <div className="text-sm text-muted-foreground">
+ Failed to generate related questions
</div>
- ))}
+ )}
+
+ {data.status === 'success' && data.questions && (
+ <>
+ {data.questions.map((item, index) => (
+ <div className="flex items-start w-full" key={index}>
+ <ArrowRight className="h-4 w-4 mr-2 mt-1.5 flex-shrink-0 text-accent-foreground/50" />
+ <Button
+ variant="link"
+ className="flex-1 justify-start px-0 py-1 h-fit font-semibold text-accent-foreground/50 whitespace-normal text-left"
+ type="submit"
+ name={'related_query'}
+ value={item.question}
+ onClick={() => onQuerySelect(item.question)}
+ >
+ {item.question}
+ </Button>
+ </div>
+ ))}
+ </>
+ )}
</div>
</Section>
</CollapsibleMessage>
diff --git a/components/render-message.tsx b/components/render-message.tsx
index 37c34017..82ced01c 100644
--- a/components/render-message.tsx
+++ b/components/render-message.tsx
@@ -137,7 +137,7 @@ export function RenderMessage({
return (
<RelatedQuestions
key={`${messageId}-related-${index}`}
- questions={part.data.questions}
+ data={part.data}
onQuerySelect={onQuerySelect}
/>
)
diff --git a/drizzle/meta/0000_snapshot.json b/drizzle/meta/0000_snapshot.json
index 97295329..8ff8ec3a 100644
--- a/drizzle/meta/0000_snapshot.json
+++ b/drizzle/meta/0000_snapshot.json
@@ -122,12 +122,8 @@
"name": "messages_chat_id_chats_id_fk",
"tableFrom": "messages",
"tableTo": "chats",
- "columnsFrom": [
- "chat_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -403,12 +399,8 @@
"name": "parts_message_id_messages_id_fk",
"tableFrom": "parts",
"tableTo": "messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -452,4 +444,4 @@
"schemas": {},
"tables": {}
}
-}
\ No newline at end of file
+}
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 63d0122e..cb468fe0 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -10,4 +10,4 @@
"breakpoints": true
}
]
-}
\ No newline at end of file
+}
diff --git a/lib/agents/generate-related-questions.ts b/lib/agents/generate-related-questions.ts
index 07231529..a743c766 100644
--- a/lib/agents/generate-related-questions.ts
+++ b/lib/agents/generate-related-questions.ts
@@ -1,4 +1,4 @@
-import { generateObject } from 'ai'
+import { convertToModelMessages, generateObject, type UIMessage } from 'ai'
import { z } from 'zod'
import { getModel } from '../utils/registry'
@@ -15,9 +15,11 @@ const relatedQuestionsSchema = z.object({
export async function generateRelatedQuestions(
model: string,
- messages: any[],
+ messages: UIMessage[],
abortSignal?: AbortSignal
) {
+ // Convert UIMessages to ModelMessages
+ const modelMessages = convertToModelMessages(messages)
const systemPrompt = `You are a professional web researcher tasked with generating follow-up questions. Based on the conversation history and search results, create 3 DIFFERENT related questions that:
1. Explore NEW aspects not covered in the original query
@@ -51,7 +53,7 @@ Bad follow-ups (avoid these):
'Generate 3 unique follow-up questions that explore different aspects of the topic',
system: systemPrompt,
messages: [
- ...messages,
+ ...modelMessages,
{
role: 'user',
content:
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 473faa6b..7d29b1ad 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -17,6 +17,7 @@ import {
} from '../actions/chat'
import { generateRelatedQuestions } from '../agents/generate-related-questions'
import { generateChatTitle } from '../agents/title-generator'
+import { updateChatTitle } from '../db/actions'
import { generateId } from '../db/schema'
import {
getMaxAllowedTokens,
@@ -65,12 +66,8 @@ export async function createChatStreamResponse(
})
}
- // Track variables for abort handling
- let researchMessage: UIMessage | null = null
- let wasAborted = false
-
// Create the stream
- const stream = createUIMessageStream({
+ const stream = createUIMessageStream<UIMessage>({
execute: async ({ writer }: { writer: UIMessageStreamWriter }) => {
try {
let messagesToModel: UIMessage[]
@@ -185,119 +182,99 @@ export async function createChatStreamResponse(
}
}
- // Stream with the research agent
- const researchResult = researchAgent.stream({
- messages: modelMessages
- })
+ // Start title generation in parallel if it's a new chat
+ let titlePromise: Promise<string> | undefined
+ if (!initialChat && message) {
+ const userContent = getTextFromParts(message.parts)
+ titlePromise = generateChatTitle({
+ userMessageContent: userContent,
+ modelId,
+ abortSignal
+ }).catch(error => {
+ console.error('Error generating title:', error)
+ return DEFAULT_CHAT_TITLE
+ })
+ }
- // Messages are tracked at the top level now
-
- // Create a promise to track when research finishes
- const researchPromise = new Promise<void>(resolve => {
- writer.merge(
- researchResult.toUIMessageStream({
- onFinish: async ({ responseMessage, isAborted }) => {
- if (isAborted) {
- wasAborted = true
- resolve()
- return
- }
- researchMessage = responseMessage
-
- // Generate related questions only if there are tool calls
- if (responseMessage && hasToolCalls(responseMessage)) {
- try {
- // Get research data
- const researchData = await researchResult.response
-
- const allMessages = [
- ...convertToModelMessages(messagesToModel),
- ...researchData.messages
- ]
-
- const relatedQuestions = await generateRelatedQuestions(
- modelId,
- allMessages,
- abortSignal
- )
-
- // Send as data part
- writer.write({
- type: 'data-relatedQuestions',
- id: generateId(),
- data: relatedQuestions
- })
- } catch (error) {
- console.error('Error generating related questions:', error)
- }
+ // Stream with the research agent
+ writer.merge(
+ researchAgent.stream({ messages: modelMessages }).toUIMessageStream({
+ onFinish: async ({ responseMessage, isAborted }) => {
+ if (isAborted || !responseMessage) return
+
+ // Generate related questions if there are tool calls
+ if (hasToolCalls(responseMessage)) {
+ const questionPartId = generateId()
+
+ try {
+ // Send initial loading state
+ writer.write({
+ type: 'data-relatedQuestions',
+ id: questionPartId,
+ data: { status: 'loading' }
+ })
+
+ const relatedQuestions = await generateRelatedQuestions(
+ modelId,
+ [...messagesToModel, responseMessage],
+ abortSignal
+ )
+
+ // Add to message parts for saving (with actual data)
+ responseMessage.parts.push({
+ type: 'data-relatedQuestions',
+ id: questionPartId,
+ data: {
+ status: 'success',
+ questions: relatedQuestions.questions
+ }
+ })
+
+ // Update stream with actual data (same ID)
+ writer.write({
+ type: 'data-relatedQuestions',
+ id: questionPartId,
+ data: {
+ status: 'success',
+ questions: relatedQuestions.questions
+ }
+ })
+ } catch (error) {
+ console.error('Error generating related questions:', error)
+ // Send error state with same ID
+ writer.write({
+ type: 'data-relatedQuestions',
+ id: questionPartId,
+ data: { status: 'error' }
+ })
}
-
- resolve()
}
- })
- )
- })
-
- // Wait for research to complete
- await researchPromise
- // Check if we have a valid research message
- if (!researchMessage) {
- writer.write({ type: 'finish' })
- return
- }
-
- // Check if aborted during research
- if (wasAborted) {
- writer.write({ type: 'finish' })
- return
- }
-
- // At this point, TypeScript should know researchMessage is not null
- const validResearchMessage: UIMessage = researchMessage
-
- // Save message after research completes
- if (validResearchMessage) {
- // Save research message and generate title in parallel
- const saveOperations: (() => Promise<any>)[] = [
- () => saveMessage(chatId, validResearchMessage)
- ]
-
- // Generate proper title after conversation starts
- if (!initialChat && message) {
- const userContent = getTextFromParts(message.parts)
- saveOperations.push(() =>
- generateChatTitle({
- userMessageContent: userContent,
- modelId,
- abortSignal
- }).then(async title => {
- const { updateChatTitle } = await import('../db/actions')
- return updateChatTitle(chatId, title)
+ // Wait for title generation if it was started
+ const chatTitle = titlePromise ? await titlePromise : undefined
+
+ // Save message with retry logic
+ saveMessage(chatId, responseMessage).catch(async error => {
+ console.error('Error saving message:', error)
+ try {
+ await retryDatabaseOperation(
+ () => saveMessage(chatId, responseMessage),
+ 'save message'
+ )
+ } catch (retryError) {
+ console.error('Failed to save after retries:', retryError)
+ }
})
- )
- }
-
- // Execute saves in background with exponential backoff retry
- // Note: This is intentionally not awaited to avoid blocking the stream
- Promise.all(saveOperations.map(op => op())).catch(async error => {
- console.error('Error saving message or title:', error)
- // Retry critical save operations with backoff
- try {
- for (const operation of saveOperations) {
- await retryDatabaseOperation(operation, 'save message/title')
+ // Update title after message is saved
+ if (chatTitle && chatTitle !== DEFAULT_CHAT_TITLE) {
+ updateChatTitle(chatId, chatTitle).catch(error =>
+ console.error('Error updating title:', error)
+ )
}
- } catch (retryError) {
- console.error(
- 'Failed to save after retries with backoff:',
- retryError
- )
- // Consider implementing alerting mechanism here
- // For now, we ensure the error is logged for monitoring
}
})
- }
+ )
} catch (error) {
console.error('Stream execution error:', error)
throw error // This error will be handled by the onError callback
diff --git a/lib/types/ai.ts b/lib/types/ai.ts
index 29fa2df6..14af4ac5 100644
--- a/lib/types/ai.ts
+++ b/lib/types/ai.ts
@@ -12,6 +12,10 @@ export type UIMessage<
export type UIDataTypes = {
sources?: any[]
+ relatedQuestions?: {
+ status: 'loading' | 'success' | 'error'
+ questions?: Array<{ question: string }>
+ }
}
export type UITools = {
diff --git a/lib/utils/message-mapping.ts b/lib/utils/message-mapping.ts
index 7f1baab5..d636964e 100644
--- a/lib/utils/message-mapping.ts
+++ b/lib/utils/message-mapping.ts
@@ -413,7 +413,7 @@ export function mapDBPartToUIMessagePart(
if (part.data_prefix) {
return {
type: `data-${part.data_prefix}`,
- ...(part.data_content as any),
+ data: part.data_content,
...(part.data_id ? { id: part.data_id } : {})
}
}