Skip to content

An AI-powered search engine with a generative UI

feat: save chat with related questions after completion

Yoshiki Miura69dd5f2c8507
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 70c5959f..49c397e1 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -1,16 +1,25 @@
-import { streamText, createDataStreamResponse } from 'ai'
+import {
+ streamText,
+ createDataStreamResponse,
+ Message,
+ convertToCoreMessages,
+ generateId,
+ JSONValue,
+ ToolInvocation
+} from 'ai'
import { researcher } from '@/lib/agents/researcher'
import { generateRelatedQuestions } from '@/lib/agents/generate-related-questions'
import { cookies } from 'next/headers'
+import { getChat, saveChat } from '@/lib/actions/chat'
export const maxDuration = 30
const DEFAULT_MODEL = 'openai:gpt-4o-mini'
export async function POST(req: Request) {
- const { messages } = await req.json()
+ const { messages, id: chatId } = await req.json()
- // Get the model from the cookie
+ const coreMessages = convertToCoreMessages(messages)
const cookieStore = await cookies()
const modelFromCookie = cookieStore.get('selected-model')?.value
const model = modelFromCookie || DEFAULT_MODEL
@@ -18,34 +27,72 @@ export async function POST(req: Request) {
return createDataStreamResponse({
execute: dataStream => {
const researcherConfig = researcher({
- messages,
+ messages: coreMessages,
model
})
+ let toolResults: ToolInvocation[] = []
const result = streamText({
...researcherConfig,
+ onStepFinish(event) {
+ // onFinish's event.toolResults is empty. Use onStepFinish to get the tool results.
+ if (event.stepType === 'initial') {
+ toolResults = event.toolResults
+ }
+ },
onFinish: async event => {
- // Notify the client that related questions are coming
- dataStream.writeMessageAnnotation({
+ const responseMessages = event.response.messages
+
+ let annotation: JSONValue = {
type: 'related-questions',
- relatedQuestions: {
+ data: {
items: []
},
status: 'loading'
- })
+ }
+
+ // Notify related questions loading
+ dataStream.writeMessageAnnotation(annotation)
// Generate related questions
- const responseMessages = event.response.messages
const relatedQuestions = await generateRelatedQuestions(
responseMessages,
model
)
- // Notify the client with the generated related questions
- dataStream.writeMessageAnnotation({
- type: 'related-questions',
- relatedQuestions: relatedQuestions.object,
+ // Update the annotation with the related questions
+ annotation = {
+ ...annotation,
+ data: relatedQuestions.object,
status: 'done'
+ }
+
+ // Send related questions to client
+ dataStream.writeMessageAnnotation(annotation)
+
+ // Create the message to save
+ const generatedMessage: Message = {
+ role: 'assistant',
+ content: event.text,
+ toolInvocations: toolResults,
+ annotations: [annotation],
+ id: generateId()
+ }
+
+ // Get the chat from the database if it exists, otherwise create a new one
+ const savedChat = (await getChat(chatId)) ?? {
+ messages: [],
+ createdAt: new Date(),
+ userId: 'anonymous',
+ path: `/search/${chatId}`,
+ title: messages[0].content,
+ id: chatId
+ }
+
+ // Save chat with complete response and related questions
+ await saveChat({
+ ...savedChat,
+ messages: [...savedChat.messages, generatedMessage]
})
}
})
diff --git a/app/page.tsx b/app/page.tsx
index 1ceeeb1b..f60160bd 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -1,5 +1,7 @@
import { Chat } from '@/components/chat'
+import { generateId } from 'ai'
export default function Page() {
- return <Chat />
+ const id = generateId()
+ return <Chat id={id} />
}
diff --git a/components/chat.tsx b/components/chat.tsx
index 0591fdb0..10369a1f 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -4,7 +4,7 @@ import { useChat } from 'ai/react'
import { ChatMessages } from './chat-messages'
import { ChatPanel } from './chat-panel'
-export function Chat() {
+export function Chat({ id }: { id: string }) {
const {
messages,
input,
@@ -14,7 +14,14 @@ export function Chat() {
setMessages,
stop,
append
- } = useChat()
+ } = useChat({
+ body: {
+ id
+ },
+ onFinish: () => {
+ // window.history.replaceState({}, '', `/search/${id}`)
+ }
+ })
return (
<div className="flex flex-col w-full max-w-3xl pt-10 pb-16 mx-auto stretch">
diff --git a/components/related-questions.tsx b/components/related-questions.tsx
index 2bc1aa0c..55f88e08 100644
--- a/components/related-questions.tsx
+++ b/components/related-questions.tsx
@@ -16,7 +16,7 @@ export interface RelatedQuestionsProps {
interface RelatedQuestionsAnnotation extends Record<string, JSONValue> {
type: 'related-questions'
- relatedQuestions: {
+ data: {
items: Array<{ query: string }>
}
status: 'loading' | 'done'
@@ -48,7 +48,7 @@ export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
</div>
)
- const relatedQuestions = lastRelatedQuestionsAnnotation?.relatedQuestions
+ const relatedQuestions = lastRelatedQuestionsAnnotation?.data
if (!relatedQuestions) {
return (
<CollapsibleMessage
diff --git a/lib/types/index.ts b/lib/types/index.ts
index 5d95c343..9ab2ef21 100644
--- a/lib/types/index.ts
+++ b/lib/types/index.ts
@@ -1,3 +1,5 @@
+import { Message } from 'ai'
+
export type SearchResults = {
images: SearchResultImage[]
results: SearchResultItem[]
@@ -61,7 +63,7 @@ export interface Chat extends Record<string, any> {
createdAt: Date
userId: string
path: string
- messages: AIMessage[]
+ messages: Message[] // Note: Changed from AIMessage to Message
sharePath?: string
}