Skip to content

An AI-powered search engine with a generative UI

Improve related questions section display and functionality

Yoshiki Miuraf359e98ddaba
diff --git a/components/chat.tsx b/components/chat.tsx
index 4b87dd84..1017cef5 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -145,7 +145,8 @@ export function Chat({
const onQuerySelect = (query: string) => {
append({
role: 'user',
- parts: [{ type: 'text', text: query }]
+ parts: [{ type: 'text', text: query }],
+ id: generateUUID()
})
}
diff --git a/components/related-questions.tsx b/components/related-questions.tsx
index 6dcdf687..d3c0ed46 100644
--- a/components/related-questions.tsx
+++ b/components/related-questions.tsx
@@ -1,7 +1,8 @@
'use client'
+import { Related } from '@/lib/schema/related'
import { UseChatHelpers } from '@ai-sdk/react'
-import { JSONValue } from 'ai'
+import { ToolInvocation } from 'ai'
import { ArrowRight } from 'lucide-react'
import React from 'react'
import { CollapsibleMessage } from './collapsible-message'
@@ -10,43 +11,28 @@ import { Button } from './ui/button'
import { Skeleton } from './ui/skeleton'
export interface RelatedQuestionsProps {
- annotations: JSONValue[]
+ tool: ToolInvocation
onQuerySelect: (query: string) => void
isOpen: boolean
onOpenChange: (open: boolean) => void
status?: UseChatHelpers['status']
}
-interface RelatedQuestionsAnnotation extends Record<string, JSONValue> {
- type: 'related-questions'
- data: {
- items: Array<{ query: string }>
- }
-}
-
export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
- annotations,
+ tool,
onQuerySelect,
isOpen,
onOpenChange,
status
}) => {
- const isLoading = status === 'submitted' || status === 'streaming'
+ const isLoading =
+ status === 'submitted' || status === 'streaming' || tool.state === 'call'
- if (!annotations) {
- return null
- }
-
- const lastRelatedQuestionsAnnotation = annotations[
- annotations.length - 1
- ] as RelatedQuestionsAnnotation
-
- const relatedQuestions = lastRelatedQuestionsAnnotation?.data
- if ((!relatedQuestions || !relatedQuestions.items) && !isLoading) {
- return null
- }
+ const data: Related | undefined =
+ tool.state === 'result' ? tool.result : undefined
- if (relatedQuestions.items.length === 0 && isLoading) {
+ console.log('data', data)
+ if (!data && isLoading) {
return (
<CollapsibleMessage
role="assistant"
@@ -55,7 +41,16 @@ export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
onOpenChange={onOpenChange}
showIcon={false}
>
- <Skeleton className="w-full h-6" />
+ <Section title="Related" className="pt-0 pb-4">
+ <div className="flex flex-col gap-2">
+ {[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>
+ ))}
+ </div>
+ </Section>
</CollapsibleMessage>
)
}
@@ -71,24 +66,22 @@ export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
>
<Section title="Related" className="pt-0 pb-4">
<div className="flex flex-col">
- {Array.isArray(relatedQuestions.items) ? (
- relatedQuestions.items
- ?.filter(item => item?.query !== '')
- .map((item, index) => (
- <div className="flex items-start w-full" key={index}>
- <ArrowRight className="h-4 w-4 mr-2 mt-1 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?.query}
- onClick={() => onQuerySelect(item?.query)}
- >
- {item?.query}
- </Button>
- </div>
- ))
+ {Array.isArray(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>Not an array</div>
)}
diff --git a/components/render-message.tsx b/components/render-message.tsx
index 25214994..297c0466 100644
--- a/components/render-message.tsx
+++ b/components/render-message.tsx
@@ -43,8 +43,12 @@ export function RenderMessage({
return (
<>
{message.parts?.map((part, index) => {
- // Check if this is the last part in the array
- const isLastPart = index === (message.parts?.length ?? 0) - 1
+ // Check if this is the last text part in the array
+ const textParts =
+ message.parts?.filter(part => part.type === 'text') || []
+ const isLastTextPart =
+ part.type === 'text' &&
+ textParts.indexOf(part) === textParts.length - 1
switch (part.type) {
case 'tool-invocation':
@@ -58,6 +62,7 @@ export function RenderMessage({
}
addToolResult={addToolResult}
status={status}
+ onQuerySelect={onQuerySelect}
/>
)
case 'text':
@@ -69,7 +74,7 @@ export function RenderMessage({
isOpen={getIsOpen(messageId)}
onOpenChange={open => onOpenChange(messageId, open)}
chatId={chatId}
- showActions={isLastPart}
+ showActions={isLastTextPart}
messageId={messageId}
reload={reload}
status={status}
diff --git a/components/tool-section.tsx b/components/tool-section.tsx
index 423d3874..432c37bd 100644
--- a/components/tool-section.tsx
+++ b/components/tool-section.tsx
@@ -3,6 +3,7 @@
import { UseChatHelpers } from '@ai-sdk/react'
import { ToolInvocation } from 'ai'
import { QuestionConfirmation } from './question-confirmation'
+import { RelatedQuestions } from './related-questions'
import RetrieveSection from './retrieve-section'
import { SearchSection } from './search-section'
import { VideoSearchSection } from './video-search-section'
@@ -13,6 +14,7 @@ interface ToolSectionProps {
onOpenChange: (open: boolean) => void
status?: UseChatHelpers['status']
addToolResult?: (params: { toolCallId: string; result: any }) => void
+ onQuerySelect: (query: string) => void
}
export function ToolSection({
@@ -20,7 +22,8 @@ export function ToolSection({
isOpen,
onOpenChange,
status,
- addToolResult
+ addToolResult,
+ onQuerySelect
}: ToolSectionProps) {
// Special handling for ask_question tool
if (tool.toolName === 'ask_question') {
@@ -85,6 +88,16 @@ export function ToolSection({
status={status}
/>
)
+ case 'related_questions':
+ return (
+ <RelatedQuestions
+ tool={tool}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ status={status}
+ onQuerySelect={onQuerySelect}
+ />
+ )
default:
return null
}
diff --git a/lib/agents/generate-related-questions.ts b/lib/agents/generate-related-questions.ts
index c5085234..7301f8d9 100644
--- a/lib/agents/generate-related-questions.ts
+++ b/lib/agents/generate-related-questions.ts
@@ -1,8 +1,9 @@
-import { relatedSchema } from '@/lib/schema/related'
-import { ModelMessage, generateObject } from 'ai'
+import { generateObject, ModelMessage, streamText, tool } from 'ai'
+import { z } from 'zod'
+import { relatedSchema } from '../schema/related'
import { getModel } from '../utils/registry'
-export async function generateRelatedQuestions(
+export function generateRelatedQuestions(
messages: ModelMessage[],
model: string
) {
@@ -11,16 +12,42 @@ export async function generateRelatedQuestions(
role: 'user'
})) as ModelMessage[]
- const result = await generateObject({
- model: getModel(model),
- system: `As a professional web researcher, your task is to generate a set of three queries that explore the subject matter more deeply, building upon the initial query and the information uncovered in its search results.
+ const systemPrompt = `As a professional web researcher, generate 3 related queries that explore the topic more deeply, based on the initial query and search results.
+
+ The queries should:
+ - Progress from general to specific aspects
+ - Cover implications and connected topics
+ - Match the user's language style and level
+ - Help build comprehensive understanding
+ - Be relevant and naturally follow from the context
- For instance, if the original query was "Starship's third test flight key milestones", your output should follow this format:
+ Example format for "Starship's third test flight key milestones":
+ - "What technical improvements were made for Starship's third test flight?"
+ - "How does the third flight's performance compare to previous launches?"
+ - "What are the implications of this test flight for future Starship missions?"`
- Aim to create queries that progressively delve into more specific aspects, implications, or adjacent topics related to the initial query. The goal is to anticipate the user's potential information needs and guide them towards a more comprehensive understanding of the subject matter.
- Please match the language of the response to the user's language.`,
+ const result = streamText({
+ model: getModel(model),
+ system:
+ 'Generate related questions. Use the generateRelatedQuestions tool exactly once to provide the related questions.',
messages: lastMessages,
- schema: relatedSchema
+ tools: {
+ related_questions: tool({
+ description: 'Generate related questions',
+ parameters: z.object({}),
+ execute: async () => {
+ const questions = await generateObject({
+ model: getModel(model),
+ system: systemPrompt,
+ messages: lastMessages,
+ schema: relatedSchema
+ })
+
+ return questions.object
+ }
+ })
+ },
+ toolChoice: 'required'
})
return result
diff --git a/lib/schema/related.tsx b/lib/schema/related.tsx
index 77fc3835..6405b729 100644
--- a/lib/schema/related.tsx
+++ b/lib/schema/related.tsx
@@ -1,15 +1,11 @@
-import { DeepPartial } from 'ai'
import { z } from 'zod'
export const relatedSchema = z.object({
- items: z
- .array(
- z.object({
- query: z.string()
- })
- )
- .length(3)
+ questions: z.array(
+ z.object({
+ question: z.string()
+ })
+ )
})
-export type PartialRelated = DeepPartial<typeof relatedSchema>
export type Related = z.infer<typeof relatedSchema>
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 635dddc4..1f8cd801 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -4,13 +4,15 @@ import {
convertToModelMessages,
createUIMessageStream,
createUIMessageStreamResponse,
+ UIMessage,
UIMessageStreamWriter
} from 'ai'
import { saveChatMessage, saveSingleMessage } from '../actions/chat-db'
+import { generateRelatedQuestions } from '../agents/generate-related-questions'
import { generateChatTitle } from '../agents/title-generator'
import { getChat, getChatMessages } from '../db/chat'
import { generateUUID } from '../utils'
-import { getTextFromParts } from '../utils/message-utils'
+import { getTextFromParts, mergeUIMessages } from '../utils/message-utils'
import { BaseStreamConfig } from './types'
export async function createChatStreamResponse(
@@ -55,25 +57,46 @@ export async function createChatStreamResponse(
message
})
- const result = await researcher({
+ const result = researcher({
messages: convertToModelMessages(messagesToModel),
model: modelId,
searchMode
})
+ // Create a variable to store the messages from the first callback
+ let firstResponseMessage: UIMessage | null = null
+
writer.merge(
result.toUIMessageStream({
newMessageId: generateUUID(),
- onFinish({ messages: resultingMessages }) {
- const assistantMessage = resultingMessages.find(
- m => m.role === 'assistant'
- )
- if (assistantMessage) {
- saveSingleMessage(chatId, assistantMessage)
- }
+ experimental_sendFinish: false,
+ onFinish: ({ responseMessage }) => {
+ // Store the messages for later use
+ firstResponseMessage = responseMessage
}
})
)
+
+ const relatedQuestions = generateRelatedQuestions(
+ (await result.response).messages,
+ modelId
+ )
+ writer.merge(
+ relatedQuestions.toUIMessageStream({
+ newMessageId: generateUUID(),
+ onFinish: ({ responseMessage }) => {
+ // If there is a first response message, merge it with the new message
+ if (firstResponseMessage) {
+ const mergedMessage = mergeUIMessages(
+ firstResponseMessage,
+ responseMessage
+ )
+ saveSingleMessage(chatId, mergedMessage)
+ }
+ },
+ experimental_sendStart: false
+ })
+ )
} catch (error) {
console.error('Stream execution error:', error)
throw error // This error will be handled by the onError callback
diff --git a/lib/utils/message-utils.ts b/lib/utils/message-utils.ts
index 78793527..e7710369 100644
--- a/lib/utils/message-utils.ts
+++ b/lib/utils/message-utils.ts
@@ -85,13 +85,9 @@ export function extractTitleFromMessage(
}
/**
- * Extracts and concatenates text content from a message's 'parts' array.
- *
- * This function mimics the behavior of the expression:
- * `message?.parts?.filter(part => part.type === 'text').map(part => part.text).join(' ') ?? '';`
- *
- * @param message - An object that may contain a 'parts' array. Can be undefined.
- * @returns A string of concatenated text from text parts, or an empty string
+ * Extracts text content from UIMessage parts.
+ * @param parts Array of message parts to extract text from.
+ * @returns Concatenated text content or empty string if no text content is found,
* if 'message' or 'message.parts' is undefined, or if 'parts' is empty or contains no text parts.
*/
export function getTextFromParts(parts?: UIMessage['parts']): string {
@@ -102,3 +98,19 @@ export function getTextFromParts(parts?: UIMessage['parts']): string {
.join(' ') ?? ''
)
}
+
+/**
+ * Merges two UIMessage objects by combining their parts
+ * @param primaryMessage The main message (properties from this will be preserved)
+ * @param secondaryMessage The message whose parts will be merged into the primary message
+ * @returns A new UIMessage with combined parts
+ */
+export function mergeUIMessages(
+ primaryMessage: UIMessage,
+ secondaryMessage: UIMessage
+): UIMessage {
+ return {
+ ...primaryMessage,
+ parts: [...primaryMessage.parts, ...secondaryMessage.parts]
+ }
+}