An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Add CopilotDisplay component
Yoshiki Miura39cb73dae33b
diff --git a/app/action.tsx b/app/action.tsxindex c5c03175..1c2571c3 100644--- a/app/action.tsx+++ b/app/action.tsx@@ -19,7 +19,7 @@ import { UserMessage } from '@/components/user-message'import { BotMessage } from '@/components/message'import { SearchSection } from '@/components/search-section'import SearchRelated from '@/components/search-related'-import { Copilot } from '@/components/copilot'+import { CopilotDisplay } from '@/components/copilot-display'async function submit(formData?: FormData, skip?: boolean) {'use server'@@ -93,7 +93,7 @@ async function submit(formData?: FormData, skip?: boolean) {uiStream.done()isGenerating.done()isCollapsed.done(false)- aiState.update({+ aiState.done({...aiState.get(),messages: [...aiState.get().messages,@@ -278,107 +278,121 @@ export const AI = createAI<AIState, UIState>({const path = `/search/${chatId}`const title =JSON.parse(messages[0].content)?.input?.substring(0, 100) || 'Untitled'- const chat: Chat = { id: chatId, createdAt, userId, path, title, messages }++ // Add an end message to the chat, to prevent excessive refreshes+ const modifiedMessages = [+ ...messages,+ {+ id: nanoid(),+ role: 'assistant',+ content: 'end'+ } as AIMessage+ ]++ const chat: Chat = {+ id: chatId,+ createdAt,+ userId,+ path,+ title,+ messages: modifiedMessages+ }await saveChat(chat)}})export const getUIStateFromAIState = (aiState: Chat) => {- return aiState.messages.map(message => {- const { role, content, id, type, name } = message-- if (!type)- return {- id,- component: null- }-- switch (role) {- case 'user':- switch (type) {- case 'input' || 'input_related':- const json = JSON.parse(content)- const value = type === 'input' ? json.input : json.related_query- return {- id,- component: (- <Section>- <UserMessage message={value} />- </Section>- )- }- case 'inquiry':- const inquiry = createStreamableValue()- inquiry.done(content)- return {- id,- component: (- <Section>- <Copilot inquiry={inquiry.value} />- </Section>- )- }- }- case 'assistant':- const answer = createStreamableValue()- answer.done(content)- switch (type) {- case 'answer':- return {- id,- component: (- <Section title="Answer">- <BotMessage content={answer.value} />- </Section>- )- }- case 'related':- const relatedQueries = createStreamableValue()- relatedQueries.done(JSON.parse(content))- return {- id,- component: (- <Section title="Related" separator={true}>- <SearchRelated relatedQueries={relatedQueries.value} />- </Section>- )+ return aiState.messages+ .map(message => {+ const { role, content, id, type, name } = message++ if (!type) return null++ switch (role) {+ case 'user':+ switch (type) {+ case 'input' || 'input_related':+ const json = JSON.parse(content)+ const value = type === 'input' ? json.input : json.related_query+ return {+ id,+ component: (+ <Section>+ <UserMessage message={value} />+ </Section>+ )+ }+ case 'inquiry':+ return {+ id,+ component: (+ <Section>+ <CopilotDisplay content={content} />+ </Section>+ )+ }+ }+ case 'assistant':+ const answer = createStreamableValue()+ answer.done(content)+ switch (type) {+ case 'answer':+ return {+ id,+ component: (+ <Section title="Answer">+ <BotMessage content={answer.value} />+ </Section>+ )+ }+ case 'related':+ const relatedQueries = createStreamableValue()+ relatedQueries.done(JSON.parse(content))+ return {+ id,+ component: (+ <Section title="Related" separator={true}>+ <SearchRelated relatedQueries={relatedQueries.value} />+ </Section>+ )+ }+ 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 'followup':+ } catch (error) {return {id,- component: (- <Section title="Follow-up" className="pb-8">- <FollowupPanel />- </Section>- )+ component: null}- }- 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- }}- } catch (error) {+ default:return {id,component: null}- }- default:- return {- id,- component: null- }- }- })+ }+ })+ .filter(message => message !== null) as UIState}diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsxindex 45fc016c..40a38173 100644--- a/app/search/[id]/page.tsx+++ b/app/search/[id]/page.tsx@@ -22,8 +22,6 @@ export default async function SearchPage({ params }: SearchPageProps) {const userId = 'anonymous'const chat = await getChat(params.id, userId)- console.log(chat)-if (!chat) {redirect('/')}diff --git a/app/temp-action.tsx b/app/temp-action.tsxdeleted file mode 100644index 613983a8..00000000--- a/app/temp-action.tsx+++ /dev/null@@ -1,414 +0,0 @@-import {- createAI,- createStreamableUI,- createStreamableValue,- getMutableAIState-} from 'ai/rsc'--import { ExperimentalMessage, nanoid, ToolResultPart } from 'ai'--import { Spinner } from '@/components/ui/spinner'--import { Section } from '@/components/section'--import { FollowupPanel } from '@/components/followup-panel'--import { inquire, researcher, taskManager, querySuggestor } from '@/lib/agents'--import { writer } from '@/lib/agents/writer'--import { saveChat } from '@/lib/actions/chat'--import { Chat } from '@/lib/types'--import { AIMessage } from '@/lib/types'--async function submit(formData?: FormData, skip?: boolean) {- 'use server'-- const aiState = getMutableAIState<typeof AI>()-- const uiStream = createStreamableUI()-- const isGenerating = createStreamableValue(true)-- const isCollapsed = createStreamableValue(false)-- const messages: ExperimentalMessage[] = aiState.get() as any[]-- const chatId = aiState.get().length > 0 ? aiState.get()[0].chatId : nanoid()-- console.log('submit', aiState.get())-- const useSpecificAPI = process.env.USE_SPECIFIC_API_FOR_WRITER === 'true'-- const maxMessages = useSpecificAPI ? 5 : 10-- // Limit the number of messages to the maximum-- messages.splice(0, Math.max(messages.length - maxMessages, 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 ? 'skip' : userInput ? 'input' : 'selection'-- // Add the user message to the state-- if (content) {- aiState.update([- ...aiState.get(),-- {- chatId,-- id: nanoid(),-- role: 'user',-- content,-- type- }- ])-- messages.push({- role: 'user',-- content- })- }-- async function processEvents() {- let action: any = { object: { next: 'proceed' } }-- // If the user skips the task, we proceed to the search-- if (!skip) action = (await taskManager(messages)) ?? action-- if (action.object.next === 'inquire') {- // Generate inquiry-- await inquire(uiStream, messages)-- uiStream.done()-- isGenerating.done()-- isCollapsed.done(false)-- return- }-- // Set the collapsed state to true-- isCollapsed.done(true)-- // Generate the answer-- let answer = ''-- let toolOutputs: ToolResultPart[] = []-- let errorOccurred = false-- const streamText = createStreamableValue<string>()-- uiStream.update(<Spinner />)-- // If useSpecificAPI is enabled, only function calls will be made-- // If not using a tool, this model generates the answer-- while (- useSpecificAPI- ? toolOutputs.length === 0 && answer.length === 0- : answer.length === 0- ) {- // Search the web and generate the answer-- const { fullResponse, hasError, toolResponses } = await researcher(- uiStream,-- streamText,-- messages,-- useSpecificAPI- )-- answer = fullResponse-- toolOutputs = toolResponses-- errorOccurred = hasError-- // if (toolOutputs.length > 0) {-- // toolOutputs.map(output => {-- // aiState.update({-- // ...aiState.get(),-- // messages: []-- // })-- // })-- // }- }-- // If useSpecificAPI is enabled, generate the answer using the specific model-- if (useSpecificAPI && answer.length === 0) {- // modify the messages to be used by the specific model-- const modifiedMessages = aiState.get().map(msg =>- msg.role === 'function'- ? {- ...msg,-- role: 'assistant',-- content: JSON.stringify(msg.content),-- type: 'tool'- }- : msg- ) as ExperimentalMessage[]-- answer = await writer(uiStream, streamText, modifiedMessages)- } else {- streamText.done()- }-- // aiState.update({-- // ...aiState.get(),-- // messages: []-- // })-- if (!errorOccurred) {- // Generate related queries-- const relatedQueries = await querySuggestor(uiStream, messages)-- // aiState.update({-- // ...aiState.get(),-- // messages: [-- // {-- // id: nanoid(),-- // role: 'assistant',-- // content: JSON.stringify(relatedQueries),-- // type: 'related'-- // }-- // ]-- // })-- // Add follow-up panel-- uiStream.append(- <Section title="Follow-up">- <FollowupPanel />- </Section>- )- }-- isGenerating.done(false)-- uiStream.done()-- aiState.done(aiState.get())-- console.log('aiState', aiState.get())- }-- processEvents()-- return {- id: nanoid(),-- isGenerating: isGenerating.value,-- component: uiStream.value,-- isCollapsed: isCollapsed.value- }-}--// Note: In the case of { chatid, messages }, nested object values cause errors--// so we need to flatten the object--export type AIState = {- chatId: string-- id: string-- role: 'user' | 'assistant' | 'system' | 'function' | 'tool'-- content: string-- name?: string-- type?: 'answer' | 'related' | 'skip' | 'selection' | 'input' | 'tool'-}[]--export type UIState = {- id: string-- component: React.ReactNode-- isGenerating?: boolean-- isCollapsed?: boolean-}[]--const initialAIState: AIState = []--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-- // unstable_onGetUIState: async () => {-- // 'use server'-- // const aiState = getAIState()-- // if (aiState) {-- // const uiState = getUIStateFromAIState(aiState)-- // return uiState-- // } else {-- // return-- // }-- // return []-- // },-- // unstable_onSetAIState: async ({ state, done }) => {-- // 'use server'-- // const { chatId, messages } = state-- // const createdAt = new Date()-- // const userId = 'anonymous'-- // const path = `/search/${chatId}`-- // const title =-- // JSON.parse(messages[0].content)?.input?.substring(0, 100) || 'Untitled'-- // const chat: Chat = { id: chatId, createdAt, userId, path, title, messages }-- // await saveChat(chat)-- // }-})--export const getUIStateFromAIState = (aiState: Chat) => {- return {- id: aiState.chatId,-- component: <div></div>- }-- // return aiState.messages-- // .filter(message => message.role !== 'system')-- // .map((message, index) => ({-- // id: `${aiState.chatId}-${index}`,-- // display:-- // message.role === 'function' ? (-- // message.name === 'listStocks' ? (-- // <BotCard>-- // <Stocks props={JSON.parse(message.content)} />-- // </BotCard>-- // ) : message.name === 'showStockPrice' ? (-- // <BotCard>-- // <Stock props={JSON.parse(message.content)} />-- // </BotCard>-- // ) : message.name === 'showStockPurchase' ? (-- // <BotCard>-- // <Purchase props={JSON.parse(message.content)} />-- // </BotCard>-- // ) : message.name === 'getEvents' ? (-- // <BotCard>-- // <Events props={JSON.parse(message.content)} />-- // </BotCard>-- // ) : null-- // ) : message.role === 'user' ? (-- // <UserMessage>{message.content}</UserMessage>-- // ) : (-- // <BotMessage content={message.content} />-- // )-- // }))-}diff --git a/components/chat-panel.tsx b/components/chat-panel.tsxindex 493ec125..4bd46872 100644--- a/components/chat-panel.tsx+++ b/components/chat-panel.tsx@@ -1,12 +1,12 @@import { useEffect, useState, useRef } from 'react'import { useRouter } from 'next/navigation'import type { AI, UIState } from '@/app/action'-import { useUIState, useActions, useAIState } from 'ai/rsc'+import { useUIState, useActions } from 'ai/rsc'import { cn } from '@/lib/utils'import { UserMessage } from './user-message'import { Input } from './ui/input'import { Button } from './ui/button'-import { ArrowRight, Plus, Square } from 'lucide-react'+import { ArrowRight, Plus } from 'lucide-react'import { EmptyScreen } from './empty-screen'import { nanoid } from 'ai'@@ -17,7 +17,6 @@ interface ChatPanelProps {export function ChatPanel({ messages }: ChatPanelProps) {const [input, setInput] = useState('')const [, setMessages] = useUIState<typeof AI>()- const [aiMessages, setAiMessages] = useAIState<typeof AI>()const { submit } = useActions()const [isButtonPressed, setIsButtonPressed] = useState(false)const inputRef = useRef<HTMLInputElement>(null)@@ -49,13 +48,10 @@ export function ChatPanel({ messages }: ChatPanelProps) {}])- console.log('ai: ', aiMessages)-// Submit and get response messageconst formData = new FormData(e.currentTarget)const responseMessage = await submit(formData)setMessages(currentMessages => [...currentMessages, responseMessage as any])- console.log('responseMessage', responseMessage)}// Clear messagesdiff --git a/components/chat.tsx b/components/chat.tsxindex fe55d7c3..5c56f2b4 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -23,8 +23,7 @@ export function Chat({ id }: ChatProps) {}, [id, path, messages])useEffect(() => {- if (aiState.messages.length > 2) {- console.log('refresh')+ if (aiState.messages[aiState.messages.length - 1]?.type === 'followup') {router.refresh()}}, [aiState, messages, router])diff --git a/components/copilot-display.tsx b/components/copilot-display.tsxnew file mode 100644index 00000000..91a817d6--- /dev/null+++ b/components/copilot-display.tsx@@ -0,0 +1,33 @@+'use client'++import React from 'react'+import { Check } from 'lucide-react'+import { Card } from './ui/card'+import { IconLogo } from './ui/icons'++interface CopilotDisplayProps {+ content: string+}++export function CopilotDisplay({ content }: CopilotDisplayProps) {+ try {+ const json = JSON.parse(content)+ const formDataEntries = Object.entries(json)+ const query = formDataEntries+ .filter(([key, value]) => value === 'on' || key === 'additional_query')+ .map(([key, value]) => (key === 'additional_query' ? value : key))+ .join(', ')++ return (+ <Card className="p-3 md:p-4 w-full flex justify-between items-center">+ <div className="flex items-center space-x-2 flex-1 min-w-0">+ <IconLogo className="w-4 h-4 flex-shrink-0" />+ <h5 className="text-muted-foreground text-xs truncate">{query}</h5>+ </div>+ <Check size={16} className="text-green-500 w-4 h-4" />+ </Card>+ )+ } catch (error) {+ return null+ }+}diff --git a/components/history-item.tsx b/components/history-item.tsxindex 81296b92..1b923d1c 100644--- a/components/history-item.tsx+++ b/components/history-item.tsx@@ -53,8 +53,8 @@ const HistoryItem: React.FC<HistoryItemProps> = ({ chat }) => {<Linkhref={chat.path}className={cn(- 'flex flex-col hover:bg-muted cursor-pointer p-2 rounded',- isActive ? 'bg-muted/50' : ''+ 'flex flex-col hover:bg-muted cursor-pointer p-2 rounded border',+ isActive ? 'bg-muted/70 border-border' : 'border-transparent')}><div className="text-xs font-medium truncate select-none">diff --git a/components/history.tsx b/components/history.tsxindex 62cdf1e8..4b213e05 100644--- a/components/history.tsx+++ b/components/history.tsx@@ -33,8 +33,8 @@ export function History({ location, chats }: HistoryProps) {</SheetTrigger><SheetContent className="w-64 rounded-tl-xl rounded-bl-xl"><SheetHeader>- <SheetTitle className="flex items-center gap-1 text-base mb-2">- <HistoryIcon size={16} />+ <SheetTitle className="flex items-center gap-1 text-sm font-normal mb-2">+ <HistoryIcon size={14} />History</SheetTitle></SheetHeader>diff --git a/lib/actions/chat.ts b/lib/actions/chat.tsindex 14be8148..911d0fe8 100644--- a/lib/actions/chat.ts+++ b/lib/actions/chat.ts@@ -1,6 +1,5 @@'use server'-import { redirect } from 'next/navigation'import { type Chat } from '@/lib/types'import { Redis } from '@upstash/redis'