An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
refactor: Update submit function to handle error cases and retry messages
Yoshiki Miura6a63cce1f657
diff --git a/app/actions.tsx b/app/actions.tsxindex d6a719b5..14d2cbb1 100644--- a/app/actions.tsx+++ b/app/actions.tsx@@ -23,16 +23,23 @@ import RetrieveSection from '@/components/retrieve-section'import { VideoSearchSection } from '@/components/video-search-section'import { transformToolMessages } from '@/lib/utils'import { AnswerSection } from '@/components/answer-section'+import { ErrorCard } from '@/components/error-card'-async function submit(formData?: FormData, skip?: boolean) {+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[] = [...aiState.get().messages]+ const messages: CoreMessage[] = aiMessages.filter(message =>message.role !== 'tool' &&@@ -163,7 +170,7 @@ async function submit(formData?: FormData, skip?: boolean) {}// If useSpecificAPI is enabled, generate the answer using the specific model- if (useSpecificAPI && answer.length === 0) {+ if (useSpecificAPI && answer.length === 0 && !errorOccurred) {// modify the messages to be used by the specific modelconst modifiedMessages = transformToolMessages(messages)const latestMessages = modifiedMessages.slice(maxMessages * -1)@@ -174,8 +181,6 @@ async function submit(formData?: FormData, skip?: boolean) {)answer = responseerrorOccurred = hasError- } else {- streamText.done()}if (!errorOccurred) {@@ -226,6 +231,14 @@ async function submit(formData?: FormData, skip?: boolean) {}]})+ } else {+ aiState.done(aiState.get())+ streamText.done()+ uiStream.append(+ <ErrorCard+ errorMessage={answer || 'An error occurred. Please try again.'}+ />+ )}isGenerating.done(false)diff --git a/components/error-card.tsx b/components/error-card.tsxnew file mode 100644index 00000000..6ea40dd9--- /dev/null+++ b/components/error-card.tsx@@ -0,0 +1,58 @@+'use client'++import React from 'react'+import { Card } from './ui/card'+import { Button } from './ui/button'+import { RefreshCcw } from 'lucide-react'+import { Label } from './ui/label'+import { useUIState, useActions, useAIState } from 'ai/rsc'+import { AI } from '@/app/actions'+import { AIMessage } from '@/lib/types'++type ErrorCardProps = {+ errorMessage: string+}++export const ErrorCard: React.FC<ErrorCardProps> = ({ errorMessage }) => {+ const [messages, setMessages] = useUIState<typeof AI>()+ const [aiState, setAIState] = useAIState<typeof AI>()+ const { submit } = useActions()++ const handleRetry = async () => {+ // Remove the last message from the UIState+ setMessages(messages.slice(0, -1))++ const aiMessages = aiState.messages+ // Get the last message with role = user+ const lastUserMessage = [...aiMessages]+ .reverse()+ .find(m => m.role === 'user')++ let retryMessages: AIMessage[] = []+ // Remove messages after lastUserMessage, cannot identify by id, so process by order+ if (lastUserMessage) {+ const lastUserMessageIndex = aiMessages.findIndex(+ m => m === lastUserMessage+ )+ retryMessages = aiMessages.slice(0, lastUserMessageIndex + 1)+ }+ // Request retry from the server and add the response to the current messages+ const response = await submit(undefined, false, retryMessages)+ setMessages(currentMessages => [...currentMessages, response])+ }++ return (+ <Card className="p-4">+ <form+ className="flex flex-col items-center space-y-4"+ action={handleRetry}+ >+ <Label>{errorMessage}</Label>+ <Button size="sm" className="w-fit" type="submit">+ <RefreshCcw size={14} className="mr-1" />+ Retry+ </Button>+ </form>+ </Card>+ )+}diff --git a/lib/agents/tools/retrieve.tsx b/lib/agents/tools/retrieve.tsxindex 2d627ae3..2b03d02b 100644--- a/lib/agents/tools/retrieve.tsx+++ b/lib/agents/tools/retrieve.tsx@@ -1,6 +1,5 @@import { retrieveSchema } from '@/lib/schema/retrieve'import { ToolProps } from '.'-import { Card } from '@/components/ui/card'import { SearchSkeleton } from '@/components/search-skeleton'import { SearchResults as SearchResultsType } from '@/lib/types'import RetrieveSection from '@/components/retrieve-section'@@ -45,22 +44,11 @@ export const retrieveTool = ({ uiStream, fullResponse }: ToolProps) => ({} catch (error) {hasError = trueconsole.error('Retrieve API error:', error)-- fullResponse += `\n${error} "${url}".`-- uiStream.update(- <Card className="p-4 mt-2 text-sm">{`${error} "${url}".`}</Card>- )- return results}if (hasError || !results) {- fullResponse += `\nAn error occurred while retrieving "${url}".`- uiStream.update(- <Card className="p-4 mt-2 text-sm">- {`An error occurred while retrieving "${url}".This webiste may not be supported.`}- </Card>- )+ fullResponse = `An error occurred while retrieving "${url}".`+ uiStream.update(null)return results}diff --git a/lib/agents/tools/search.tsx b/lib/agents/tools/search.tsxindex 3ed9d82d..1998a82e 100644--- a/lib/agents/tools/search.tsx+++ b/lib/agents/tools/search.tsx@@ -38,12 +38,9 @@ export const searchTool = ({ uiStream, fullResponse }: ToolProps) => ({}if (hasError) {- fullResponse += `\nAn error occurred while searching for "${query}.`- uiStream.update(- <Card className="p-4 mt-2 text-sm">- {`An error occurred while searching for "${query}".`}- </Card>- )+ fullResponse = `An error occurred while searching for "${query}.`+ uiStream.update(null)+ streamResults.done()return searchResult}diff --git a/lib/agents/tools/video-search.tsx b/lib/agents/tools/video-search.tsxindex 0e5d0e05..d05a2593 100644--- a/lib/agents/tools/video-search.tsx+++ b/lib/agents/tools/video-search.tsx@@ -1,6 +1,5 @@import { createStreamableValue } from 'ai/rsc'import { searchSchema } from '@/lib/schema/search'-import { Card } from '@/components/ui/card'import { ToolProps } from '.'import { VideoSearchSection } from '@/components/video-search-section'@@ -34,12 +33,9 @@ export const videoSearchTool = ({ uiStream, fullResponse }: ToolProps) => ({}if (hasError) {- fullResponse += `\nAn error occurred while searching for videos with "${query}.`- uiStream.update(- <Card className="p-4 mt-2 text-sm">- {`An error occurred while searching for videos with "${query}".`}- </Card>- )+ fullResponse = `An error occurred while searching for videos with "${query}.`+ uiStream.update(null)+ streamResults.done()return searchResult}