Skip to content

An AI-powered search engine with a generative UI

refactor: complete AI SDK v5 beta migration

Yoshiki Miura10b8cdef2ec0
diff --git a/components/answer-section.tsx b/components/answer-section.tsx
index 340be89a..d077649f 100644
--- a/components/answer-section.tsx
+++ b/components/answer-section.tsx
@@ -1,6 +1,7 @@
'use client'
import { UseChatHelpers } from '@ai-sdk/react'
+import type { UIMessage, UIDataTypes, UITools } from '@/lib/types/ai'
import { ChatRequestOptions } from 'ai'
import { CollapsibleMessage } from './collapsible-message'
@@ -15,7 +16,7 @@ export type AnswerSectionProps = {
chatId?: string
showActions?: boolean
messageId: string
- status?: UseChatHelpers['status']
+ status?: UseChatHelpers<UIMessage<unknown, UIDataTypes, UITools>>['status']
reload?: (
messageId: string,
options?: ChatRequestOptions
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index 3dac5cf5..2380f1a1 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -3,6 +3,7 @@
import { useState } from 'react'
import { UseChatHelpers } from '@ai-sdk/react'
+import type { UIMessage, UIDataTypes, UITools } from '@/lib/types/ai'
import { UIMessage } from 'ai'
import { cn } from '@/lib/utils'
@@ -20,7 +21,7 @@ interface ChatSection {
interface ChatMessagesProps {
sections: ChatSection[] // Changed from messages to sections
onQuerySelect: (query: string) => void
- status: UseChatHelpers['status']
+ status: UseChatHelpers<UIMessage<unknown, UIDataTypes, UITools>>['status']
chatId?: string
addToolResult?: (params: { toolCallId: string; result: any }) => void
/** Ref for the scroll container */
diff --git a/components/chat.tsx b/components/chat.tsx
index 08fd255a..d34ceb35 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -48,9 +48,9 @@ export function Chat({
stop,
sendMessage,
regenerate,
- addToolInvocation
+ addToolResult
} = useChat<UIMessage<unknown, UIDataTypes, UITools>>({
- api: '/api/chat',
+ url: '/api/chat',
body: {
chatId: id
},
@@ -146,10 +146,9 @@ export function Chat({
}, [sections, messages])
const onQuerySelect = (query: string) => {
- append({
+ sendMessage({
role: 'user',
- parts: [{ type: 'text', text: query }],
- id: generateUUID()
+ parts: [{ type: 'text', text: query }]
})
}
@@ -198,7 +197,7 @@ export function Chat({
})
await deleteTrailingMessages(id, pivotTimestamp)
- await reload()
+ await regenerate()
} catch (error) {
console.error('Error during message edit and reload process:', error)
toast.error(
@@ -247,8 +246,8 @@ export function Chat({
const contentToResend =
targetUserMessage.parts
- ?.filter(p => p.type === 'text')
- .map(p => p.text)
+ ?.filter((p: any) => p.type === 'text')
+ .map((p: any) => p.text)
.join('') || ''
try {
@@ -328,9 +327,7 @@ export function Chat({
onQuerySelect={onQuerySelect}
status={status}
chatId={id}
- addToolResult={({ toolCallId, result }) => {
- addToolInvocation({ toolCallId, result })
- }}
+ addToolResult={addToolResult}
scrollContainerRef={scrollContainerRef}
onUpdateMessage={handleUpdateAndReloadMessage}
reload={handleReloadFrom}
diff --git a/components/inspector/inspector-drawer.tsx b/components/inspector/inspector-drawer.tsx
index 5ae15099..551b96d1 100644
--- a/components/inspector/inspector-drawer.tsx
+++ b/components/inspector/inspector-drawer.tsx
@@ -19,8 +19,14 @@ export function InspectorDrawer() {
const getTitle = () => {
if (!part) return 'Artifact' // Default title
switch (part.type) {
- case 'tool-invocation':
- return part.toolInvocation.toolName
+ case 'tool-search':
+ return 'search'
+ case 'tool-retrieve':
+ return 'retrieve'
+ case 'tool-videoSearch':
+ return 'videoSearch'
+ case 'tool-askQuestion':
+ return 'askQuestion'
case 'reasoning':
return 'Reasoning'
case 'text':
diff --git a/components/inspector/inspector-panel.tsx b/components/inspector/inspector-panel.tsx
index 9dd860d8..375541eb 100644
--- a/components/inspector/inspector-panel.tsx
+++ b/components/inspector/inspector-panel.tsx
@@ -23,10 +23,14 @@ export function InspectorPanel() {
// Get the icon and title based on part type
const getIconAndTitle = () => {
switch (part.type) {
- case 'tool-invocation':
+ case 'tool-search':
+ case 'tool-retrieve':
+ case 'tool-videoSearch':
+ case 'tool-askQuestion':
+ const toolName = part.type.replace('tool-', '')
return {
icon: <Wrench size={18} />,
- title: part.toolInvocation.toolName
+ title: toolName
}
case 'reasoning':
return {
diff --git a/components/message-actions.tsx b/components/message-actions.tsx
index 9d463e4b..50e7f301 100644
--- a/components/message-actions.tsx
+++ b/components/message-actions.tsx
@@ -1,6 +1,7 @@
'use client'
import { UseChatHelpers } from '@ai-sdk/react'
+import type { UIMessage, UIDataTypes, UITools } from '@/lib/types/ai'
import { Copy } from 'lucide-react'
import { toast } from 'sonner'
@@ -17,7 +18,7 @@ interface MessageActionsProps {
chatId?: string
enableShare?: boolean
className?: string
- status?: UseChatHelpers['status']
+ status?: UseChatHelpers<UIMessage<unknown, UIDataTypes, UITools>>['status']
}
export function MessageActions({
diff --git a/components/render-message.tsx b/components/render-message.tsx
index 7701f97a..df739601 100644
--- a/components/render-message.tsx
+++ b/components/render-message.tsx
@@ -1,4 +1,5 @@
-import { UIMessage, UseChatHelpers } from '@ai-sdk/react'
+import { UseChatHelpers } from '@ai-sdk/react'
+import type { UIMessage, UIDataTypes, UITools } from '@/lib/types/ai'
import { AnswerSection } from './answer-section'
import { ReasoningSection } from './reasoning-section'
@@ -13,7 +14,7 @@ interface RenderMessageProps {
onOpenChange: (id: string, open: boolean) => void
onQuerySelect: (query: string) => void
chatId?: string
- status?: UseChatHelpers['status']
+ status?: UseChatHelpers<UIMessage<unknown, UIDataTypes, UITools>>['status']
addToolResult?: (params: { toolCallId: string; result: any }) => void
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
reload?: (messageId: string) => Promise<void | string | null | undefined>
@@ -78,18 +79,22 @@ export function RenderMessage({
const hasNextPart = message.parts && index < message.parts.length - 1
switch (part.type) {
- case 'tool-invocation':
+ case 'tool-search':
+ case 'tool-retrieve':
+ case 'tool-videoSearch':
+ case 'tool-askQuestion':
+ case 'tool-relatedQuestions':
return (
<ToolSection
key={`${messageId}-tool-${index}`}
- tool={part.toolInvocation}
+ tool={part as any}
isOpen={getIsOpen(
- part.toolInvocation.toolCallId,
+ part.toolCallId,
part.type,
hasNextPart
)}
onOpenChange={open =>
- onOpenChange(part.toolInvocation.toolCallId, open)
+ onOpenChange(part.toolCallId, open)
}
addToolResult={addToolResult}
status={status}
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 875084d4..f9e27fab 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -1,5 +1,4 @@
import {
- appendClientMessage,
convertToModelMessages,
createUIMessageStream,
createUIMessageStreamResponse,
@@ -37,7 +36,7 @@ export async function createChatStreamResponse(
// If authorized or it's a new chat, proceed to create the stream
const stream = createUIMessageStream({
- execute: async (writer: UIMessageStreamWriter) => {
+ execute: async ({ writer }: { writer: UIMessageStreamWriter }) => {
try {
// Use chatForAuth (from outer scope) to decide new/existing path
if (!chatForAuth) {
@@ -54,11 +53,7 @@ export async function createChatStreamResponse(
}
const previousMessages = await getChatMessages(chatId)
- const messagesToModel = appendClientMessage({
- // @ts-ignore
- messages: previousMessages,
- message
- })
+ const messagesToModel = [...previousMessages, message]
const result = researcher({
messages: convertToModelMessages(messagesToModel),
@@ -71,7 +66,7 @@ export async function createChatStreamResponse(
writer.merge(
result.toUIMessageStream({
- newMessageId: generateUUID(),
+ id: generateUUID(),
experimental_sendFinish: false,
onFinish: ({ responseMessage }) => {
// Store the messages for later use
@@ -86,7 +81,7 @@ export async function createChatStreamResponse(
)
writer.merge(
relatedQuestions.toUIMessageStream({
- newMessageId: generateUUID(),
+ id: generateUUID(),
onFinish: ({ responseMessage }) => {
// If there is a first response message, merge it with the new message
if (firstResponseMessage) {
diff --git a/lib/types/ai.ts b/lib/types/ai.ts
index caa87cd3..de4f79d1 100644
--- a/lib/types/ai.ts
+++ b/lib/types/ai.ts
@@ -1,42 +1,20 @@
-import type { Message } from 'ai'
+import type { Message, InferUITool } from 'ai'
+import { searchTool } from '@/lib/tools/search'
+import { retrieveTool } from '@/lib/tools/retrieve'
+import { videoSearchTool } from '@/lib/tools/video-search'
+import { askQuestionTool } from '@/lib/tools/question'
-export type UIMessage = Message
+export type UIMessage<TMetadata = unknown, TDataTypes = UIDataTypes, TTools = UITools> = Message
export type UIDataTypes = {
sources?: any[]
}
export type UITools = {
- search: {
- input: {
- query: string
- max_results?: number
- search_depth?: 'basic' | 'advanced'
- include_domains?: string[]
- exclude_domains?: string[]
- }
- output: any
- }
- retrieve: {
- input: {
- url: string
- }
- output: any
- }
- videoSearch: {
- input: {
- query: string
- }
- output: any
- }
- askQuestion: {
- input: {
- question: string
- options: string[]
- allowMultiple?: boolean
- }
- output: any
- }
+ search: InferUITool<typeof searchTool>
+ retrieve: InferUITool<typeof retrieveTool>
+ videoSearch: InferUITool<typeof videoSearchTool>
+ askQuestion: InferUITool<typeof askQuestionTool>
}
export type TextPart = {