Skip to content

An AI-powered search engine with a generative UI

feat: Add generate related questions

Yoshiki Miuraca5ef1489555
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 8b8d6fb3..bbc19820 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -17,25 +17,27 @@ export async function POST(req: Request) {
const result = streamText({
...researcherConfig,
onFinish: async event => {
- // Notify the client that related queries are coming
+ // Notify the client that related questions are coming
dataStream.writeMessageAnnotation({
- type: 'related-queries',
- relatedQueries: {
+ type: 'related-questions',
+ relatedQuestions: {
items: []
- }
+ },
+ status: 'loading'
})
- // Generate related queries
+ // Generate related questions
const responseMessages = event.response.messages
- const relatedQueries = await generateRelatedQuestions(
+ const relatedQuestions = await generateRelatedQuestions(
responseMessages,
model
)
- // Notify the client with the generated related queries
+ // Notify the client with the generated related questions
dataStream.writeMessageAnnotation({
- type: 'related-queries',
- relatedQueries: relatedQueries.object
+ type: 'related-questions',
+ relatedQuestions: relatedQuestions.object,
+ status: 'done'
})
}
})
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index f3ab5d17..8b4c420d 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -1,16 +1,33 @@
import { Message } from 'ai'
+import { UserMessage } from './user-message'
+import { BotMessage } from './message'
+import RelatedQuestions from './related-questions'
interface ChatMessagesProps {
messages: Message[]
+ onQuerySelect: (query: string) => void
}
-export function ChatMessages({ messages }: ChatMessagesProps) {
+export function ChatMessages({ messages, onQuerySelect }: ChatMessagesProps) {
+ if (!messages.length) {
+ return null
+ }
+
return (
- <div className="flex flex-col items-center justify-center w-full max-w-2xl mx-auto">
+ <div className="relative mx-auto px-4 w-full">
{messages.map(message => (
- <div key={message.id} className="w-full py-2">
- {message.role === 'user' ? 'User: ' : 'AI: '}
- {message.content}
+ <div key={message.id} className="mb-4">
+ {message.role === 'user' ? (
+ <UserMessage message={message.content} />
+ ) : (
+ <BotMessage message={message.content} />
+ )}
+ {!message.toolInvocations && message.annotations && (
+ <RelatedQuestions
+ annotations={message.annotations}
+ onQuerySelect={onQuerySelect}
+ />
+ )}
</div>
))}
</div>
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index f612e95b..1016a462 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -84,7 +84,7 @@ export function ChatPanel({
<form
onSubmit={handleSubmit}
className={cn(
- 'max-w-2xl w-full mx-auto',
+ 'max-w-3xl w-full mx-auto',
messages.length > 0 ? 'p-4' : 'px-6'
)}
>
diff --git a/components/chat.tsx b/components/chat.tsx
index e05cf36a..54543c97 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -20,7 +20,8 @@ export function Chat() {
handleSubmit,
isLoading,
setMessages,
- stop
+ stop,
+ append
} = useChat({
body: {
model: selectedModelId
@@ -28,8 +29,16 @@ export function Chat() {
})
return (
- <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">
- <ChatMessages messages={messages} />
+ <div className="flex flex-col w-full max-w-3xl py-24 mx-auto stretch">
+ <ChatMessages
+ messages={messages}
+ onQuerySelect={query => {
+ append({
+ role: 'user',
+ content: query
+ })
+ }}
+ />
<ChatPanel
input={input}
handleInputChange={handleInputChange}
diff --git a/components/message.tsx b/components/message.tsx
index cee4d892..5c3d2b1e 100644
--- a/components/message.tsx
+++ b/components/message.tsx
@@ -8,14 +8,14 @@ import rehypeKatex from 'rehype-katex'
import 'katex/dist/katex.min.css'
import { CodeBlock } from './ui/codeblock'
-export function BotMessage({ content }: { content: string }) {
+export function BotMessage({ message }: { message: string }) {
// Check if the content contains LaTeX patterns
const containsLaTeX = /\\\[([\s\S]*?)\\\]|\\\(([\s\S]*?)\\\)/.test(
- content || ''
+ message || ''
)
// Modify the content to render LaTeX equations if LaTeX patterns are found
- const processedData = preprocessLaTeX(content || '')
+ const processedData = preprocessLaTeX(message || '')
if (containsLaTeX) {
return (
@@ -70,7 +70,7 @@ export function BotMessage({ content }: { content: string }) {
}
}}
>
- {content}
+ {message}
</MemoizedReactMarkdown>
)
}
diff --git a/components/related-questions.tsx b/components/related-questions.tsx
new file mode 100644
index 00000000..dd09e850
--- /dev/null
+++ b/components/related-questions.tsx
@@ -0,0 +1,77 @@
+'use client'
+
+import React from 'react'
+import { Button } from './ui/button'
+import { ArrowRight } from 'lucide-react'
+import { Section } from './section'
+import { Skeleton } from './ui/skeleton'
+import { JSONValue } from 'ai'
+
+export interface RelatedQuestionsProps {
+ annotations: JSONValue[]
+ onQuerySelect: (query: string) => void
+}
+
+interface RelatedQuestionsAnnotation extends Record<string, JSONValue> {
+ type: 'related-questions'
+ relatedQuestions: {
+ items: Array<{ query: string }>
+ }
+ status: 'loading' | 'done'
+}
+
+export const RelatedQuestions: React.FC<RelatedQuestionsProps> = ({
+ annotations,
+ onQuerySelect
+}) => {
+ if (!annotations) {
+ return null
+ }
+
+ const lastRelatedQuestionsAnnotation = annotations.find(
+ (a): a is RelatedQuestionsAnnotation =>
+ a !== null &&
+ typeof a === 'object' &&
+ 'type' in a &&
+ a.type === 'related-questions' &&
+ a.status === 'done'
+ )
+
+ const relatedQuestions = lastRelatedQuestionsAnnotation?.relatedQuestions
+ if (!relatedQuestions) {
+ return (
+ <Section title="Related" separator={true}>
+ <Skeleton className="w-full h-6" />
+ </Section>
+ )
+ }
+
+ return (
+ <Section title="Related" separator={true}>
+ <div className="flex flex-wrap">
+ {Array.isArray(relatedQuestions.items) ? (
+ relatedQuestions.items
+ ?.filter(item => item?.query !== '')
+ .map((item, index) => (
+ <div className="flex items-start w-full" key={index}>
+ <ArrowRight className="h-4 w-4 mr-2 mt-1 flex-shrink-0 text-accent-foreground/50" />
+ <Button
+ variant="link"
+ className="flex-1 justify-start px-0 py-1 h-fit font-semibold text-accent-foreground/50 whitespace-normal text-left"
+ type="submit"
+ name={'related_query'}
+ value={item?.query}
+ onClick={() => onQuerySelect(item?.query)}
+ >
+ {item?.query}
+ </Button>
+ </div>
+ ))
+ ) : (
+ <div>Not an array</div>
+ )}
+ </div>
+ </Section>
+ )
+}
+export default RelatedQuestions
diff --git a/components/search-related.tsx b/components/search-related.tsx
deleted file mode 100644
index 8d371d5d..00000000
--- a/components/search-related.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-'use client'
-
-import React, { useEffect, useState } from 'react'
-import { Button } from './ui/button'
-import { ArrowRight } from 'lucide-react'
-import {
- StreamableValue,
- useActions,
- useStreamableValue,
- useUIState
-} from 'ai/rsc'
-import { AI } from '@/app/actions'
-import { UserMessage } from './user-message'
-import { PartialRelated } from '@/lib/schema/related'
-import { Section } from './section'
-import { Skeleton } from './ui/skeleton'
-import { useLocalStorage } from '@/lib/hooks/use-local-storage'
-import { models } from '@/lib/types/models'
-import { getDefaultModelId } from '@/lib/utils'
-
-export interface SearchRelatedProps {
- relatedQueries: StreamableValue<PartialRelated>
-}
-
-export const SearchRelated: React.FC<SearchRelatedProps> = ({
- relatedQueries
-}) => {
- const { submit } = useActions()
- const [, setMessages] = useUIState<typeof AI>()
- const [data, error, pending] = useStreamableValue(relatedQueries)
- const [related, setRelated] = useState<PartialRelated>()
-
- const [selectedModelId] = useLocalStorage<string>(
- 'selectedModel',
- getDefaultModelId(models)
- )
-
- useEffect(() => {
- if (!data) return
- setRelated(data)
- }, [data])
-
- const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
- event.preventDefault()
- const formData = new FormData(event.currentTarget as HTMLFormElement)
-
- // Get the submitter of the form
- const submitter = (event.nativeEvent as SubmitEvent)
- .submitter as HTMLInputElement
- let query = ''
- if (submitter) {
- formData.append(submitter.name, submitter.value)
- query = submitter.value
- }
-
- // Add model information to formData
- formData.set('model', selectedModelId)
-
- const userMessage = {
- id: Date.now(),
- component: <UserMessage message={query} />
- }
-
- const responseMessage = await submit(formData)
- setMessages(currentMessages => [
- ...currentMessages,
- userMessage,
- responseMessage
- ])
- }
-
- return related ? (
- <Section title="Related" separator={true}>
- <form onSubmit={handleSubmit} className="flex flex-wrap">
- {Array.isArray(related.items) ? (
- related.items
- ?.filter(item => item?.query !== '')
- .map((item, index) => (
- <div className="flex items-start w-full" key={index}>
- <ArrowRight className="h-4 w-4 mr-2 mt-1 flex-shrink-0 text-accent-foreground/50" />
- <Button
- variant="link"
- className="flex-1 justify-start px-0 py-1 h-fit font-semibold text-accent-foreground/50 whitespace-normal text-left"
- type="submit"
- name={'related_query'}
- value={item?.query}
- >
- {item?.query}
- </Button>
- </div>
- ))
- ) : (
- <div>Not an array</div>
- )}
- </form>
- </Section>
- ) : error ? null : (
- <Section title="Related" separator={true}>
- <Skeleton className="w-full h-6" />
- </Section>
- )
-}
-
-export default SearchRelated