Skip to content

An AI-powered search engine with a generative UI

Add new page and related types

Yoshiki Miuraec0c3ea32a80
diff --git a/app/action.tsx b/app/action.tsx
index 08fa9603..50fbd592 100644
--- a/app/action.tsx
+++ b/app/action.tsx
@@ -1,7 +1,9 @@
import {
+ StreamableValue,
createAI,
createStreamableUI,
createStreamableValue,
+ getAIState,
getMutableAIState
} from 'ai/rsc'
import { ExperimentalMessage, nanoid, ToolResultPart } from 'ai'
@@ -13,6 +15,11 @@ import { writer } from '@/lib/agents/writer'
import { saveChat } from '@/lib/actions/chat'
import { Chat } from '@/lib/types'
import { AIMessage } from '@/lib/types'
+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'
async function submit(formData?: FormData, skip?: boolean) {
'use server'
@@ -21,7 +28,10 @@ async function submit(formData?: FormData, skip?: boolean) {
const uiStream = createStreamableUI()
const isGenerating = createStreamableValue(true)
const isCollapsed = createStreamableValue(false)
- const messages: ExperimentalMessage[] = aiState.get().messages as any[]
+ // Get the messages from the state, filter out the tool messages
+ const messages: ExperimentalMessage[] = [
+ ...(aiState.get().messages as any[])
+ ].filter(message => message.role !== 'tool')
console.log('submit', aiState.get())
@@ -33,12 +43,22 @@ async function submit(formData?: FormData, skip?: boolean) {
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'
+ const type = skip
+ ? undefined
+ : formData?.has('input')
+ ? 'input'
+ : formData?.has('related_query')
+ ? 'input_related'
+ : 'inquiry'
+
+ console.log('content', content)
+
// Add the user message to the state
if (content) {
aiState.update({
@@ -46,7 +66,7 @@ async function submit(formData?: FormData, skip?: boolean) {
messages: [
...aiState.get().messages,
{
- id: 'hello',
+ id: nanoid(),
role: 'user',
content,
type
@@ -66,11 +86,21 @@ async function submit(formData?: FormData, skip?: boolean) {
if (action.object.next === 'inquire') {
// Generate inquiry
- await inquire(uiStream, messages)
-
+ const inquiry = await inquire(uiStream, messages)
uiStream.done()
isGenerating.done()
isCollapsed.done(false)
+ aiState.update({
+ ...aiState.get(),
+ messages: [
+ ...aiState.get().messages,
+ {
+ id: nanoid(),
+ role: 'assistant',
+ content: `inquiry: ${inquiry?.question}`
+ }
+ ]
+ })
return
}
@@ -102,21 +132,30 @@ async function submit(formData?: FormData, skip?: boolean) {
toolOutputs = toolResponses
errorOccurred = hasError
- // if (toolOutputs.length > 0) {
- // toolOutputs.map(output => {
- // aiState.update({
- // ...aiState.get(),
- // messages: []
- // })
- // })
- // }
+ if (toolOutputs.length > 0) {
+ toolOutputs.map(output => {
+ aiState.update({
+ ...aiState.get(),
+ messages: [
+ ...aiState.get().messages,
+ {
+ id: nanoid(),
+ role: 'tool',
+ content: JSON.stringify(output.result),
+ name: output.toolName,
+ type: 'tool'
+ }
+ ]
+ })
+ })
+ }
}
// 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().messages.map(msg =>
- msg.role === 'function'
+ msg.role === 'tool'
? {
...msg,
role: 'assistant',
@@ -130,25 +169,34 @@ async function submit(formData?: FormData, skip?: boolean) {
streamText.done()
}
- // aiState.update({
- // ...aiState.get(),
- // messages: []
- // })
+ aiState.update({
+ ...aiState.get(),
+ messages: [
+ ...aiState.get().messages,
+ {
+ id: nanoid(),
+ role: 'assistant',
+ content: answer,
+ type: 'answer'
+ }
+ ]
+ })
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'
- // }
- // ]
- // })
+ aiState.update({
+ ...aiState.get(),
+ messages: [
+ ...aiState.get().messages,
+ {
+ id: nanoid(),
+ role: 'assistant',
+ content: JSON.stringify(relatedQueries),
+ type: 'related'
+ }
+ ]
+ })
// Add follow-up panel
uiStream.append(
@@ -162,7 +210,7 @@ async function submit(formData?: FormData, skip?: boolean) {
uiStream.done()
aiState.done(aiState.get())
- console.log('aiState', aiState.get())
+ console.log('aiState', aiState.get().chatId)
}
processEvents()
@@ -183,8 +231,8 @@ export type AIState = {
export type UIState = {
id: string
component: React.ReactNode
- isGenerating?: boolean
- isCollapsed?: boolean
+ isGenerating?: StreamableValue<boolean>
+ isCollapsed?: StreamableValue<boolean>
}[]
const initialAIState: AIState = {
@@ -200,65 +248,113 @@ export const AI = createAI<AIState, UIState>({
submit
},
initialUIState,
- initialAIState
- // unstable_onGetUIState: async () => {
- // 'use server'
+ 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 aiState = getAIState()
+ if (aiState) {
+ const uiState = getUIStateFromAIState(aiState)
+ return uiState
+ } else {
+ 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)
- // }
+ 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} />
- // )
- // }))
+ const groupedId = nanoid()
+ 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} initialCompleted={true} />
+ </Section>
+ )
+ }
+ }
+ case 'assistant':
+ const answer = createStreamableValue()
+ answer.done(content)
+ switch (type) {
+ case 'answer':
+ return {
+ id: groupedId,
+ component: (
+ <Section title="Answer">
+ <BotMessage content={answer.value} />
+ </Section>
+ )
+ }
+ case 'related':
+ const relatedQueries = createStreamableValue()
+ relatedQueries.done(JSON.parse(content))
+ return {
+ id: groupedId,
+ component: (
+ <Section title="Related" separator={true}>
+ <SearchRelated relatedQueries={relatedQueries.value} />
+ </Section>
+ )
+ }
+ }
+ case 'tool':
+ 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: groupedId,
+ component: <SearchSection result={searchResults.value} />,
+ isCollapsed: isCollapsed.value
+ }
+ }
+ default:
+ return {
+ id,
+ component: null
+ }
+ }
+ })
}
diff --git a/app/layout.tsx b/app/layout.tsx
index 2b1c9175..856f5ce4 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -1,6 +1,5 @@
import type { Metadata, Viewport } from 'next'
import { Inter as FontSans } from 'next/font/google'
-import { AI } from './action'
import './globals.css'
import { cn } from '@/lib/utils'
import { ThemeProvider } from '@/components/theme-provider'
@@ -55,7 +54,7 @@ export default function RootLayout({
disableTransitionOnChange
>
<Header />
- <AI>{children}</AI>
+ {children}
<Sidebar />
<Footer />
</ThemeProvider>
diff --git a/app/new/page.tsx b/app/new/page.tsx
new file mode 100644
index 00000000..d2358948
--- /dev/null
+++ b/app/new/page.tsx
@@ -0,0 +1,5 @@
+import { redirect } from 'next/navigation'
+
+export default async function NewPage() {
+ redirect('/')
+}
diff --git a/app/page.tsx b/app/page.tsx
index 10a4d6ea..f6e3975d 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -1,7 +1,14 @@
import { Chat } from '@/components/chat'
+import { nanoid } from 'ai'
+import { AI } from './action'
export const runtime = 'edge'
export default function Page() {
- return <Chat />
+ const id = nanoid()
+ return (
+ <AI initialAIState={{ chatId: id, messages: [] }}>
+ <Chat id={id} />
+ </AI>
+ )
}
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsx
new file mode 100644
index 00000000..45fc016c
--- /dev/null
+++ b/app/search/[id]/page.tsx
@@ -0,0 +1,40 @@
+import { notFound, redirect } from 'next/navigation'
+import { Chat } from '@/components/chat'
+import { getChat } from '@/lib/actions/chat'
+import { AI } from '@/app/action'
+
+export const runtime = 'edge'
+
+export interface SearchPageProps {
+ params: {
+ id: string
+ }
+}
+
+export async function generateMetadata({ params }: SearchPageProps) {
+ const chat = await getChat(params.id, 'anonymous')
+ return {
+ title: chat?.title.toString().slice(0, 50) || 'Search'
+ }
+}
+
+export default async function SearchPage({ params }: SearchPageProps) {
+ const userId = 'anonymous'
+ const chat = await getChat(params.id, userId)
+
+ console.log(chat)
+
+ if (!chat) {
+ redirect('/')
+ }
+
+ if (chat?.userId !== userId) {
+ notFound()
+ }
+
+ return (
+ <AI initialAIState={{ chatId: chat.id, messages: chat.messages }}>
+ <Chat id={params.id} />
+ </AI>
+ )
+}
diff --git a/app/temp-action.tsx b/app/temp-action.tsx
new file mode 100644
index 00000000..613983a8
--- /dev/null
+++ b/app/temp-action.tsx
@@ -0,0 +1,414 @@
+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-messages.tsx b/components/chat-messages.tsx
index 8b99266d..18a6526e 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -1,23 +1,60 @@
import { StreamableValue, useUIState } from 'ai/rsc'
-import type { AI } from '@/app/action'
+import type { AI, UIState } from '@/app/action'
import { CollapsibleMessage } from './collapsible-message'
-export function ChatMessages() {
- const [messages] = useUIState<typeof AI>()
+interface ChatMessagesProps {
+ messages: UIState
+}
+
+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]: any }, 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 (
<>
- {messages.map(
- (message: {
+ {groupedMessagesArray.map(
+ (groupedMessage: {
id: string
- component: React.ReactNode
+ components: React.ReactNode[]
isCollapsed?: StreamableValue<boolean>
- isGenerating?: StreamableValue<boolean>
}) => (
<CollapsibleMessage
- key={message.id}
- message={message}
- isLastMessage={message.id === messages[messages.length - 1].id}
+ key={groupedMessage.id}
+ message={{
+ id: groupedMessage.id,
+ component: <>{groupedMessage.components}</>,
+ isCollapsed: groupedMessage.isCollapsed
+ }}
+ isLastMessage={
+ groupedMessage.id === messages[messages.length - 1].id
+ }
/>
)
)}
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index 9ee9ee44..493ec125 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -1,5 +1,6 @@
import { useEffect, useState, useRef } from 'react'
-import type { AI } from '@/app/action'
+import { useRouter } from 'next/navigation'
+import type { AI, UIState } from '@/app/action'
import { useUIState, useActions, useAIState } from 'ai/rsc'
import { cn } from '@/lib/utils'
import { UserMessage } from './user-message'
@@ -9,14 +10,19 @@ import { ArrowRight, Plus, Square } from 'lucide-react'
import { EmptyScreen } from './empty-screen'
import { nanoid } from 'ai'
-export function ChatPanel() {
+interface ChatPanelProps {
+ messages: UIState
+}
+
+export function ChatPanel({ messages }: ChatPanelProps) {
const [input, setInput] = useState('')
- const [messages, setMessages] = useUIState<typeof AI>()
+ const [, setMessages] = useUIState<typeof AI>()
const [aiMessages, setAiMessages] = useAIState<typeof AI>()
const { submit } = useActions()
const [isButtonPressed, setIsButtonPressed] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
const [showEmptyScreen, setShowEmptyScreen] = useState(false)
+ const router = useRouter()
// Focus on input when button is pressed
useEffect(() => {
if (isButtonPressed) {
@@ -54,9 +60,7 @@ export function ChatPanel() {
// Clear messages
const handleClear = () => {
- setIsButtonPressed(true)
- // setMessages([])
- // setAiMessages(null)
+ router.push('/new')
}
useEffect(() => {
diff --git a/components/chat.tsx b/components/chat.tsx
index bb1b0d31..bbb23ee9 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -1,13 +1,38 @@
'use client'
+import { useEffect } from 'react'
+import { usePathname, useRouter } from 'next/navigation'
import { ChatPanel } from './chat-panel'
import { ChatMessages } from './chat-messages'
+import { useUIState, useAIState } from 'ai/rsc'
+
+type ChatProps = {
+ id?: string
+}
+
+export function Chat({ id }: ChatProps) {
+ const router = useRouter()
+ const path = usePathname()
+ const [messages] = useUIState()
+ const [aiState] = useAIState()
+
+ useEffect(() => {
+ if (!path.includes('search') && messages.length === 1) {
+ window.history.replaceState({}, '', `/search/${id}`)
+ }
+ }, [id, path, messages])
+
+ useEffect(() => {
+ const messagesLength = aiState.messages?.length
+ if (messagesLength === 2) {
+ router.refresh()
+ }
+ }, [aiState.messages, router])
-export function Chat() {
return (
- <div className="px-8 md:px-12 pt-6 md:pt-8 pb-14 md:pb-24 max-w-3xl mx-auto flex flex-col space-y-3 md:space-y-4">
- <ChatMessages />
- <ChatPanel />
+ <div className="px-8 sm:px-12 pt-6 md:pt-8 pb-14 md:pb-24 max-w-3xl mx-auto flex flex-col space-y-3 md:space-y-4">
+ <ChatMessages messages={messages} />
+ <ChatPanel messages={messages} />
</div>
)
}
diff --git a/components/header.tsx b/components/header.tsx
index 39ab1df6..144665ad 100644
--- a/components/header.tsx
+++ b/components/header.tsx
@@ -8,7 +8,7 @@ import { History } from './history'
export const Header: React.FC = () => {
return (
- <header className="fixed w-full p-2 md:p-2 flex justify-between items-center z-10 backdrop-blur md:backdrop-blur-none bg-background/80 md:bg-transparent">
+ <header className="fixed w-full p-1 md:p-2 flex justify-between items-center z-10 backdrop-blur md:backdrop-blur-none bg-background/80 md:bg-transparent">
<div>
<a href="/">
<IconLogo className={cn('w-5 h-5')} />
diff --git a/components/history.tsx b/components/history.tsx
index cc53e8b1..f96d7a60 100644
--- a/components/history.tsx
+++ b/components/history.tsx
@@ -22,7 +22,9 @@ export function History({ location }: HistoryProps) {
<Button
variant="ghost"
size="icon"
- className={cn({ 'rounded-full': location === 'sidebar' })}
+ className={cn({
+ 'rounded-full text-foreground/30': location === 'sidebar'
+ })}
>
{location === 'header' ? <Menu /> : <ChevronLeft size={16} />}
</Button>
diff --git a/components/message.tsx b/components/message.tsx
index 0c106484..5be78e0c 100644
--- a/components/message.tsx
+++ b/components/message.tsx
@@ -5,11 +5,7 @@ import { MemoizedReactMarkdown } from './ui/markdown'
import rehypeExternalLinks from 'rehype-external-links'
import remarkGfm from 'remark-gfm'
-export function BotMessage({
- content
-}: {
- content: string | StreamableValue<string>
-}) {
+export function BotMessage({ content }: { content: StreamableValue<string> }) {
const [data, error, pending] = useStreamableValue(content)
// Currently, sometimes error occurs after finishing the stream.
diff --git a/components/search-section.tsx b/components/search-section.tsx
index db961c44..cac81dcc 100644
--- a/components/search-section.tsx
+++ b/components/search-section.tsx
@@ -14,24 +14,24 @@ export type SearchSectionProps = {
export function SearchSection({ result }: SearchSectionProps) {
const [data, error, pending] = useStreamableValue(result)
- const results: TypeSearchResults = data ? JSON.parse(data) : undefined
+ const searchResults: TypeSearchResults = data ? JSON.parse(data) : undefined
return (
<div>
{!pending && data ? (
<>
<Section size="sm" className="pt-2 pb-0">
- <ToolBadge tool="search">{`${results.query}`}</ToolBadge>
+ <ToolBadge tool="search">{`${searchResults.query}`}</ToolBadge>
</Section>
- {results.images && results.images.length > 0 && (
+ {searchResults.images && searchResults.images.length > 0 && (
<Section title="Images">
<SearchResultsImageSection
- images={results.images}
- query={results.query}
+ images={searchResults.images}
+ query={searchResults.query}
/>
</Section>
)}
<Section title="Results">
- <SearchResults results={results.results} />
+ <SearchResults results={searchResults.results} />
</Section>
</>
) : (
diff --git a/lib/schema/related.tsx b/lib/schema/related.tsx
index bf9b9f88..77fc3835 100644
--- a/lib/schema/related.tsx
+++ b/lib/schema/related.tsx
@@ -11,3 +11,5 @@ export const relatedSchema = z.object({
.length(3)
})
export type PartialRelated = DeepPartial<typeof relatedSchema>
+
+export type Related = z.infer<typeof relatedSchema>
diff --git a/lib/types/index.ts b/lib/types/index.ts
index 463e91eb..969b3f87 100644
--- a/lib/types/index.ts
+++ b/lib/types/index.ts
@@ -25,5 +25,12 @@ export type AIMessage = {
content: string
id: string
name?: string
- type?: 'answer' | 'related' | 'skip' | 'selection' | 'input' | 'tool'
+ type?:
+ | 'answer'
+ | 'related'
+ | 'skip'
+ | 'inquiry'
+ | 'input'
+ | 'input_related'
+ | 'tool'
}
diff --git a/lib/utils/index.ts b/lib/utils/index.ts
index 7db7716e..d32b0fe6 100644
--- a/lib/utils/index.ts
+++ b/lib/utils/index.ts
@@ -1,26 +1,6 @@
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
-import { AIMessage } from '../types'
-import { ExperimentalMessage } from 'ai'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
-
-export function convertToExperimentalMessages(
- messages: AIMessage[]
-): ExperimentalMessage[] {
- return messages
- .filter(
- message =>
- message.role === 'tool' ||
- message.role === 'assistant' ||
- message.role === 'user'
- )
- .map(message => {
- return {
- content: message.content,
- role: message.role
- } as ExperimentalMessage
- })
-}