-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathchatbot-page.tsx
executable file
·67 lines (60 loc) · 1.83 KB
/
chatbot-page.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use client'
import { ChatList } from '@/components/chat-list'
import { useChat, type Message } from 'ai/react'
import cn from 'mxcn'
import { useState } from 'react'
import { toast } from 'sonner'
import { ChatInput } from './chat-input'
import { Opening } from './opening'
import { Suggestions } from './suggestions'
export interface ChatProps extends React.ComponentProps<'div'> {
id?: string // Optional: Thread ID if you want to persist the chat in a DB
initialMessages?: Message[] // Optional: Messages to pre-populate the chat from DB
}
export function Chatbot({ id, initialMessages, className }: ChatProps) {
const [threadId, setThreadId] = useState<null | string>(null)
const { messages, append, reload, stop, isLoading, input, setInput } =
useChat({
api: '/api/chat',
initialMessages,
body: { threadId },
onResponse(response) {
if (response.status !== 200) {
console.log('✨ ~ response:', response)
toast.error(response.statusText)
}
// Get Thread ID from response header
const lbThreadId = response.headers.get('lb-thread-id')
setThreadId(lbThreadId)
}
})
const sendSuggestedPrompt = (prompt: string) => {
setInput(prompt)
}
return (
<div className="min-h-screen">
<div className={cn('pb-36 pt-4 md:pt-10', className)}>
{messages.length ? (
<>
<ChatList messages={messages} />
</>
) : (
<>
<Opening />
<Suggestions sendSuggestedPrompt={sendSuggestedPrompt} />
</>
)}
</div>
<ChatInput
id={id}
isLoading={isLoading}
stop={stop}
append={append}
reload={reload}
messages={messages}
input={input}
setInput={setInput}
/>
</div>
)
}