An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
chore: Replace useAction with useChat
Yoshiki Miura72de7f267832
diff --git a/app/actions.tsx b/app/actions.tsxdeleted file mode 100644index d110e773..00000000--- a/app/actions.tsx+++ /dev/null@@ -1,315 +0,0 @@-import {- StreamableValue,- createAI,- createStreamableUI,- createStreamableValue,- getAIState,- getMutableAIState-} from 'ai/rsc'-import { CoreMessage, generateId } from 'ai'-import { Section } from '@/components/section'-import { FollowupPanel } from '@/components/followup-panel'-import { saveChat } from '@/lib/actions/chat'-import { Chat } from '@/lib/types'-import { AIMessage } from '@/lib/types'-import { UserMessage } from '@/components/user-message'-import { SearchSection } from '@/components/search-section'-import SearchRelated from '@/components/search-related'-import { CopilotDisplay } from '@/components/copilot-display'-import RetrieveSection from '@/components/retrieve-section'-import { VideoSearchSection } from '@/components/video-search-section'-import { AnswerSection } from '@/components/answer-section'-import { workflow } from '@/lib/actions/workflow'-import { isProviderEnabled } from '@/lib/utils/registry'--const MAX_MESSAGES = 6--async function submit(- formData?: FormData,- skip?: boolean,- retryMessages?: AIMessage[]-) {- 'use server'-- const aiState = getMutableAIState<typeof AI>()- const uiStream = createStreamableUI()- const isGenerating = createStreamableValue(true)- const isCollapsed = createStreamableValue(false)-- const aiMessages = [...(retryMessages ?? aiState.get().messages)]- // Get the messages from the state, filter out the tool messages- const messages: CoreMessage[] = aiMessages- .filter(- message =>- message.role !== 'tool' &&- message.type !== 'followup' &&- message.type !== 'related' &&- message.type !== 'end'- )- .map(message => {- const { role, content } = message- return { role, content } as CoreMessage- })-- // Limit the number of messages to the maximum- messages.splice(0, Math.max(messages.length - MAX_MESSAGES, 0))- // Get the user input from the form data- const userInput = skip- ? `{"action": "skip"}`- : (formData?.get('input') as string)-- const content = skip- ? userInput- : formData- ? JSON.stringify(Object.fromEntries(formData))- : null- const type = skip- ? undefined- : formData?.has('input')- ? 'input'- : formData?.has('related_query')- ? 'input_related'- : 'inquiry'-- // Get the model from the form data (e.g., openai:gpt-4o-mini)- const model = (formData?.get('model') as string) || 'openai:gpt-4o-mini'- const providerId = model.split(':')[0]- console.log(`Using model: ${model}`)- // Check if provider is enabled- if (!isProviderEnabled(providerId)) {- throw new Error(- `Provider ${providerId} is not available (API key not configured or base URL not set)`- )- }-- // Add the user message to the state- if (content) {- aiState.update({- ...aiState.get(),- messages: [- ...aiState.get().messages,- {- id: generateId(),- role: 'user',- content,- type- }- ]- })- messages.push({- role: 'user',- content- })- }-- // Run the agent workflow- workflow(- { uiStream, isCollapsed, isGenerating },- aiState,- messages,- skip ?? false,- model- )-- return {- id: generateId(),- isGenerating: isGenerating.value,- component: uiStream.value,- isCollapsed: isCollapsed.value- }-}--export type AIState = {- messages: AIMessage[]- chatId: string- isSharePage?: boolean-}--export type UIState = {- id: string- component: React.ReactNode- isGenerating?: StreamableValue<boolean>- isCollapsed?: StreamableValue<boolean>-}[]--const initialAIState: AIState = {- chatId: generateId(),- messages: []-}--const initialUIState: UIState = []--// AI is a provider you wrap your application with so you can access AI and UI state in your components.-export const AI = createAI<AIState, UIState>({- actions: {- submit- },- initialUIState,- initialAIState,- onGetUIState: async () => {- 'use server'-- const aiState = getAIState()- if (aiState) {- const uiState = getUIStateFromAIState(aiState as Chat)- return uiState- } else {- return- }- },- onSetAIState: async ({ state, done }) => {- 'use server'-- // Check if there is any message of type 'answer' in the state messages- if (!state.messages.some(e => e.type === 'answer')) {- return- }-- const { chatId, messages } = state- const createdAt = new Date()- const userId = 'anonymous'- const path = `/search/${chatId}`- const title =- messages.length > 0- ? JSON.parse(messages[0].content)?.input?.substring(0, 100) ||- 'Untitled'- : 'Untitled'- // Add an 'end' message at the end to determine if the history needs to be reloaded- const updatedMessages: AIMessage[] = [- ...messages,- {- id: generateId(),- role: 'assistant',- content: `end`,- type: 'end'- }- ]-- const chat: Chat = {- id: chatId,- createdAt,- userId,- path,- title,- messages: updatedMessages- }- await saveChat(chat)- }-})--export const getUIStateFromAIState = (aiState: Chat) => {- const chatId = aiState.chatId- const isSharePage = aiState.isSharePage-- // Ensure messages is an array of plain objects- const messages = Array.isArray(aiState.messages)- ? aiState.messages.map(msg => ({ ...msg }))- : []-- return messages- .map((message, index) => {- const { role, content, id, type, name } = message-- if (- !type ||- type === 'end' ||- (isSharePage && type === 'related') ||- (isSharePage && type === 'followup')- )- return null-- switch (role) {- case 'user':- switch (type) {- case 'input':- case 'input_related':- const json = JSON.parse(content)- const value = type === 'input' ? json.input : json.related_query- return {- id,- component: (- <UserMessage- message={value}- chatId={chatId}- showShare={index === 0 && !isSharePage}- />- )- }- case 'inquiry':- return {- id,- component: <CopilotDisplay content={content} />- }- }- case 'assistant':- const answer = createStreamableValue()- answer.done(content)- switch (type) {- case 'answer':- return {- id,- component: <AnswerSection result={answer.value} />- }- case 'related':- const relatedQueries = createStreamableValue()- relatedQueries.done(JSON.parse(content))- return {- id,- component: (- <SearchRelated relatedQueries={relatedQueries.value} />- )- }- case 'followup':- return {- id,- component: (- <Section title="Follow-up" className="pb-8">- <FollowupPanel />- </Section>- )- }- }- case 'tool':- try {- const toolOutput = JSON.parse(content)- const isCollapsed = createStreamableValue()- isCollapsed.done(true)- const searchResults = createStreamableValue()- searchResults.done(JSON.stringify(toolOutput))- switch (name) {- case 'search':- return {- id,- component: <SearchSection result={searchResults.value} />,- isCollapsed: isCollapsed.value- }- case 'retrieve':- return {- id,- component: <RetrieveSection data={toolOutput} />,- isCollapsed: isCollapsed.value- }- case 'videoSearch':- return {- id,- component: (- <VideoSearchSection result={searchResults.value} />- ),- isCollapsed: isCollapsed.value- }- }- } catch (error) {- return {- id,- component: null- }- }- default:- return {- id,- component: null- }- }- })- .filter(message => message !== null) as UIState-}diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsnew file mode 100644index 00000000..5e77fe51--- /dev/null+++ b/app/api/chat/route.ts@@ -0,0 +1,17 @@+import { openai } from '@ai-sdk/openai'+import { streamText } from 'ai'++// Allow streaming responses up to 30 seconds+export const maxDuration = 30++export async function POST(req: Request) {+ const { messages } = await req.json()++ const result = streamText({+ model: openai('gpt-4-turbo'),+ system: 'You are a helpful assistant.',+ messages+ })++ return result.toDataStreamResponse()+}diff --git a/app/layout.tsx b/app/layout.tsxindex 29438228..0209562c 100644--- a/app/layout.tsx+++ b/app/layout.tsx@@ -58,7 +58,7 @@ export default function RootLayout({<AppStateProvider><Header />{children}- <Sidebar />+ {/* <Sidebar /> */}<Footer /><Toaster /></AppStateProvider>diff --git a/app/page.tsx b/app/page.tsxindex 82e04890..1ceeeb1b 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -1,14 +1,5 @@import { Chat } from '@/components/chat'-import { generateId } from 'ai'-import { AI } from './actions'--export const maxDuration = 60export default function Page() {- const id = generateId()- return (- <AI initialAIState={{ chatId: id, messages: [] }}>- <Chat id={id} />- </AI>- )+ return <Chat />}diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsxindex d32179ad..a8177c57 100644--- a/app/search/[id]/page.tsx+++ b/app/search/[id]/page.tsx@@ -1,7 +1,6 @@import { notFound, redirect } from 'next/navigation'import { Chat } from '@/components/chat'import { getChat } from '@/lib/actions/chat'-import { AI } from '@/app/actions'export const maxDuration = 60@@ -30,14 +29,5 @@ export default async function SearchPage({ params }: SearchPageProps) {notFound()}- return (- <AI- initialAIState={{- chatId: chat.id,- messages: chat.messages- }}- >- <Chat id={params.id} />- </AI>- )+ return <Chat />}diff --git a/app/search/page.tsx b/app/search/page.tsxindex 22893fc4..6b4e6a05 100644--- a/app/search/page.tsx+++ b/app/search/page.tsx@@ -1,6 +1,4 @@import { Chat } from '@/components/chat'-import { generateId } from 'ai'-import { AI } from '@/app/actions'import { redirect } from 'next/navigation'export const maxDuration = 60@@ -13,11 +11,7 @@ export default function Page({if (!searchParams.q) {redirect('/')}- const id = generateId()- return (- <AI initialAIState={{ chatId: id, messages: [] }}>- <Chat id={id} query={searchParams.q} />- </AI>- )+ return <Chat />+ // return <Chat initialInput={searchParams.q} />}diff --git a/components/chat-messages.tsx b/components/chat-messages.tsxindex 9c803ce7..f3ab5d17 100644--- a/components/chat-messages.tsx+++ b/components/chat-messages.tsx@@ -1,65 +1,18 @@-'use client'--import { StreamableValue } from 'ai/rsc'-import type { UIState } from '@/app/actions'-import { CollapsibleMessage } from './collapsible-message'+import { Message } from 'ai'interface ChatMessagesProps {- messages: UIState-}--type GroupedMessage = {- id: string- components: React.ReactNode[]- isCollapsed?: StreamableValue<boolean> | undefined+ messages: Message[]}export function ChatMessages({ messages }: ChatMessagesProps) {- if (!messages.length) {- return null- }-- // Group messages based on ID, and if there are multiple messages with the same ID, combine them into one message- const groupedMessages = messages.reduce(- (acc: { [key: string]: GroupedMessage }, message) => {- if (!acc[message.id]) {- acc[message.id] = {- id: message.id,- components: [],- isCollapsed: message.isCollapsed- }- }- acc[message.id].components.push(message.component)- return acc- },- {}- )-- // Convert grouped messages into an array with explicit type- const groupedMessagesArray = Object.values(groupedMessages).map(group => ({- ...group,- components: group.components as React.ReactNode[]- })) as {- id: string- components: React.ReactNode[]- isCollapsed?: StreamableValue<boolean>- }[]-return (- <>- {groupedMessagesArray.map((groupedMessage: GroupedMessage) => (- <CollapsibleMessage- key={`${groupedMessage.id}`}- message={{- id: groupedMessage.id,- component: groupedMessage.components.map((component, i) => (- <div key={`${groupedMessage.id}-${i}`}>{component}</div>- )),- isCollapsed: groupedMessage.isCollapsed- }}- isLastMessage={groupedMessage.id === messages[messages.length - 1].id}- />+ <div className="flex flex-col items-center justify-center w-full max-w-2xl mx-auto">+ {messages.map(message => (+ <div key={message.id} className="w-full py-2">+ {message.role === 'user' ? 'User: ' : 'AI: '}+ {message.content}+ </div>))}- </>+ </div>)}diff --git a/components/chat-panel.tsx b/components/chat-panel.tsxindex 830e2182..f612e95b 100644--- a/components/chat-panel.tsx+++ b/components/chat-panel.tsx@@ -2,15 +2,13 @@import { useEffect, useState, useRef } from 'react'import { useRouter } from 'next/navigation'-import type { AI, UIState } from '@/app/actions'-import { useUIState, useActions, useAIState } from 'ai/rsc'import { cn } from '@/lib/utils'import { UserMessage } from './user-message'import { Button } from './ui/button'-import { ArrowRight, Plus } from 'lucide-react'+import { ArrowRight, Plus, Square } from 'lucide-react'import { EmptyScreen } from './empty-screen'import Textarea from 'react-textarea-autosize'-import { generateId } from 'ai'+import { generateId, Message } from 'ai'import { useAppState } from '@/lib/utils/app-state'import { ModelSelector } from './model-selector'import { models } from '@/lib/types/models'@@ -19,18 +17,30 @@ import { getDefaultModelId } from '@/lib/utils'import { toast } from 'sonner'interface ChatPanelProps {- messages: UIState+ input: string+ handleInputChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void+ handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void+ isLoading: boolean+ messages: Message[]+ setMessages: (messages: Message[]) => voidquery?: stringonModelChange?: (id: string) => void+ stop: () => void}-export function ChatPanel({ messages, query, onModelChange }: ChatPanelProps) {- const [input, setInput] = useState('')+export function ChatPanel({+ input,+ handleInputChange,+ handleSubmit,+ isLoading,+ messages,+ setMessages,+ query,+ onModelChange,+ stop+}: ChatPanelProps) {const [showEmptyScreen, setShowEmptyScreen] = useState(false)- const [, setMessages] = useUIState<typeof AI>()- const [aiMessage, setAIMessage] = useAIState<typeof AI>()const { isGenerating, setIsGenerating } = useAppState()- const { submit } = useActions()const router = useRouter()const inputRef = useRef<HTMLTextAreaElement>(null)const isFirstRender = useRef(true) // For development environment@@ -53,117 +63,52 @@ export function ChatPanel({ messages, query, onModelChange }: ChatPanelProps) {}, 300)}- async function handleQuerySubmit(query: string, formData?: FormData) {- setInput(query)- setIsGenerating(true)-- // Add user message to UI state- setMessages(currentMessages => [- ...currentMessages,- {- id: generateId(),- component: <UserMessage message={query} />- }- ])-- // Use existing formData or create new one- const data = formData || new FormData()-- // Add or update the model information- const modelString = selectedModelId- data.set('model', modelString)-- // Add or update the input query if not already present- if (!formData) {- data.set('input', query)- }-- const responseMessage = await submit(data)- setMessages(currentMessages => [...currentMessages, responseMessage])- }-- const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {- e.preventDefault()- const formData = new FormData(e.currentTarget)- try {- await handleQuerySubmit(input, formData)- } catch (error) {- console.error('Error submitting form:', error)- toast.error(`${error}`)-- handleClear()- }- }-- // if query is not empty, submit the query- useEffect(() => {- if (isFirstRender.current && query && query.trim().length > 0) {- handleQuerySubmit(query)- isFirstRender.current = false- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [query])-- useEffect(() => {- const lastMessage = aiMessage.messages.slice(-1)[0]- if (lastMessage?.type === 'followup' || lastMessage?.type === 'inquiry') {- setIsGenerating(false)- }- }, [aiMessage, setIsGenerating])-- // Clear messages- const handleClear = () => {- setIsGenerating(false)+ const handleNewChat = () => {setMessages([])- setAIMessage({ messages: [], chatId: '' })- setInput('')router.push('/')}- useEffect(() => {- // focus on input when the page loads- inputRef.current?.focus()- }, [])-- // If there are messages and the new button has not been pressed, display the new Button- if (messages.length > 0) {- return (- <div className="fixed bottom-2 md:bottom-8 left-0 right-0 flex justify-center items-center mx-auto pointer-events-none">- <Button- type="button"- variant={'secondary'}- className="rounded-full bg-secondary/80 group transition-all hover:scale-105 pointer-events-auto"- onClick={() => handleClear()}- disabled={isGenerating}- >- <span className="text-sm mr-2 group-hover:block hidden animate-in fade-in duration-300">- New- </span>- <Plus size={18} className="group-hover:rotate-90 transition-all" />- </Button>- </div>- )- }-if (query && query.trim().length > 0) {return null}return (<div- className={- 'fixed bottom-8 left-0 right-0 top-10 mx-auto h-screen flex flex-col items-center justify-center'- }+ className={cn(+ 'mx-auto w-full',+ messages.length > 0+ ? 'fixed bottom-0 left-0 right-0 bg-background/80 backdrop-blur-sm'+ : 'fixed bottom-8 left-0 right-0 top-10 flex flex-col items-center justify-center'+ )}>- <form onSubmit={handleSubmit} className="max-w-2xl w-full px-6">- <div className="relative flex items-center w-full">- <ModelSelector- selectedModelId={selectedModelId}- onModelChange={id => {- setSelectedModelId(id)- onModelChange?.(id)- }}- />+ <form+ onSubmit={handleSubmit}+ className={cn(+ 'max-w-2xl w-full mx-auto',+ messages.length > 0 ? 'p-4' : 'px-6'+ )}+ >+ <div className="relative flex items-center w-full gap-2">+ {messages.length > 0 && (+ <Button+ variant="ghost"+ size="icon"+ onClick={handleNewChat}+ className="shrink-0 rounded-full"+ type="button"+ >+ <Plus className="h-4 w-4" />+ </Button>+ )}+ {messages.length === 0 && (+ <ModelSelector+ selectedModelId={selectedModelId}+ onModelChange={id => {+ setSelectedModelId(id)+ onModelChange?.(id)+ }}+ />+ )}<Textarearef={inputRef}name="input"@@ -177,7 +122,7 @@ export function ChatPanel({ messages, query, onModelChange }: ChatPanelProps) {value={input}className="resize-none w-full min-h-12 rounded-fill bg-muted border border-input pl-4 pr-10 pt-3 pb-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"onChange={e => {- setInput(e.target.value)+ handleInputChange(e)setShowEmptyScreen(e.target.value.length === 0)}}onKeyDown={e => {@@ -219,21 +164,29 @@ export function ChatPanel({ messages, query, onModelChange }: ChatPanelProps) {onBlur={() => setShowEmptyScreen(false)}/><Button- type="submit"+ type={isLoading ? 'button' : 'submit'}size={'icon'}variant={'ghost'}- className="absolute right-2 top-1/2 transform -translate-y-1/2"- disabled={input.length === 0}+ className={cn(+ 'absolute right-2 top-1/2 transform -translate-y-1/2',+ isLoading && 'animate-pulse'+ )}+ disabled={input.length === 0 && !isLoading}+ onClick={isLoading ? stop : undefined}>- <ArrowRight size={20} />+ {isLoading ? <Square size={20} /> : <ArrowRight size={20} />}</Button></div>- <EmptyScreen- submitMessage={message => {- setInput(message)- }}- className={cn(showEmptyScreen ? 'visible' : 'invisible')}- />+ {messages.length === 0 && (+ <EmptyScreen+ submitMessage={message => {+ handleInputChange({+ target: { value: message }+ } as React.ChangeEvent<HTMLTextAreaElement>)+ }}+ className={cn(showEmptyScreen ? 'visible' : 'invisible')}+ />+ )}</form></div>)diff --git a/components/chat.tsx b/components/chat.tsxindex 54a07512..f5e96f14 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -1,30 +1,32 @@'use client'-import { useEffect } from 'react'-import { usePathname } from 'next/navigation'-import { ChatPanel } from './chat-panel'+import { useChat } from 'ai/react'import { ChatMessages } from './chat-messages'-import { useUIState } from 'ai/rsc'--type ChatProps = {- id?: string- query?: string-}--export function Chat({ id, query }: ChatProps) {- const path = usePathname()- const [messages] = useUIState()+import { ChatPanel } from './chat-panel'- useEffect(() => {- if (!path.includes('search') && messages.length === 1) {- window.history.replaceState({}, '', `/search/${id}`)- }- }, [id, path, messages, query])+export function Chat() {+ const {+ messages,+ input,+ handleInputChange,+ handleSubmit,+ isLoading,+ setMessages,+ stop+ } = useChat()return (- <div className="px-8 sm:px-12 pt-12 md:pt-14 pb-14 md:pb-24 max-w-3xl mx-auto flex flex-col space-y-3 md:space-y-4">+ <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch"><ChatMessages messages={messages} />- <ChatPanel messages={messages} query={query} />+ <ChatPanel+ input={input}+ handleInputChange={handleInputChange}+ handleSubmit={handleSubmit}+ isLoading={isLoading}+ messages={messages}+ setMessages={setMessages}+ stop={stop}+ /></div>)}diff --git a/components/header.tsx b/components/header.tsxindex 39caff9e..8452c75f 100644--- a/components/header.tsx+++ b/components/header.tsx@@ -15,7 +15,7 @@ export const Header: React.FC = async () => {</div><div className="flex gap-0.5"><ModeToggle />- <HistoryContainer location="header" />+ {/* <HistoryContainer location="header" /> */}</div></header>)