|
| 1 | +import { useEffect, useState } from 'react' |
| 2 | +import { Button } from './Button' |
| 3 | +import { type ChatGPTMessage, ChatLine, LoadingChatLine } from './ChatLine' |
| 4 | +import { useCookies } from 'react-cookie' |
| 5 | + |
| 6 | +const COOKIE_NAME = 'nextjs-example-ai-chat-gpt3' |
| 7 | + |
| 8 | +// default first message to display in UI (not necessary to define the prompt) |
| 9 | +export const initialMessages: ChatGPTMessage[] = [ |
| 10 | + { |
| 11 | + role: 'assistant', |
| 12 | + content: 'Hi! I am a friendly AI assistant. Ask me anything!', |
| 13 | + }, |
| 14 | +] |
| 15 | + |
| 16 | +const InputMessage = ({ input, setInput, sendMessage }: any) => ( |
| 17 | + <div className="mt-6 flex clear-both"> |
| 18 | + <input |
| 19 | + type="text" |
| 20 | + aria-label="chat input" |
| 21 | + required |
| 22 | + className="min-w-0 flex-auto appearance-none rounded-md border border-zinc-900/10 bg-white px-3 py-[calc(theme(spacing.2)-1px)] shadow-md shadow-zinc-800/5 placeholder:text-zinc-400 focus:border-teal-500 focus:outline-none focus:ring-4 focus:ring-teal-500/10 sm:text-sm" |
| 23 | + value={input} |
| 24 | + onKeyDown={(e) => { |
| 25 | + if (e.key === 'Enter') { |
| 26 | + sendMessage(input) |
| 27 | + setInput('') |
| 28 | + } |
| 29 | + }} |
| 30 | + onChange={(e) => { |
| 31 | + setInput(e.target.value) |
| 32 | + }} |
| 33 | + /> |
| 34 | + <Button |
| 35 | + type="submit" |
| 36 | + className="ml-4 flex-none" |
| 37 | + onClick={() => { |
| 38 | + sendMessage(input) |
| 39 | + setInput('') |
| 40 | + }} |
| 41 | + > |
| 42 | + Say |
| 43 | + </Button> |
| 44 | + </div> |
| 45 | +) |
| 46 | + |
| 47 | +export function Chat() { |
| 48 | + const [messages, setMessages] = useState<ChatGPTMessage[]>(initialMessages) |
| 49 | + const [input, setInput] = useState('') |
| 50 | + const [loading, setLoading] = useState(false) |
| 51 | + const [cookie, setCookie] = useCookies([COOKIE_NAME]) |
| 52 | + |
| 53 | + useEffect(() => { |
| 54 | + if (!cookie[COOKIE_NAME]) { |
| 55 | + // generate a semi random short id |
| 56 | + const randomId = Math.random().toString(36).substring(7) |
| 57 | + setCookie(COOKIE_NAME, randomId) |
| 58 | + } |
| 59 | + }, [cookie, setCookie]) |
| 60 | + |
| 61 | + // send message to API /api/chat endpoint |
| 62 | + const sendMessage = async (message: string) => { |
| 63 | + setLoading(true) |
| 64 | + const newMessages = [ |
| 65 | + ...messages, |
| 66 | + { role: 'user', content: message } as ChatGPTMessage, |
| 67 | + ] |
| 68 | + setMessages(newMessages) |
| 69 | + const last10messages = newMessages.slice(-10) // remember last 10 messages |
| 70 | + |
| 71 | + const response = await fetch('/api/chat', { |
| 72 | + method: 'POST', |
| 73 | + headers: { |
| 74 | + 'Content-Type': 'application/json', |
| 75 | + }, |
| 76 | + body: JSON.stringify({ |
| 77 | + messages: last10messages, |
| 78 | + user: cookie[COOKIE_NAME], |
| 79 | + }), |
| 80 | + }) |
| 81 | + |
| 82 | + console.log('Edge function returned.') |
| 83 | + |
| 84 | + if (!response.ok) { |
| 85 | + throw new Error(response.statusText) |
| 86 | + } |
| 87 | + |
| 88 | + // This data is a ReadableStream |
| 89 | + const data = response.body |
| 90 | + if (!data) { |
| 91 | + return |
| 92 | + } |
| 93 | + |
| 94 | + const reader = data.getReader() |
| 95 | + const decoder = new TextDecoder() |
| 96 | + let done = false |
| 97 | + |
| 98 | + let lastMessage = '' |
| 99 | + |
| 100 | + while (!done) { |
| 101 | + const { value, done: doneReading } = await reader.read() |
| 102 | + done = doneReading |
| 103 | + const chunkValue = decoder.decode(value) |
| 104 | + |
| 105 | + lastMessage = lastMessage + chunkValue |
| 106 | + |
| 107 | + setMessages([ |
| 108 | + ...newMessages, |
| 109 | + { role: 'assistant', content: lastMessage } as ChatGPTMessage, |
| 110 | + ]) |
| 111 | + |
| 112 | + setLoading(false) |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + return ( |
| 117 | + <div className="rounded-2xl border-zinc-100 lg:border lg:p-6"> |
| 118 | + {messages.map(({ content, role }, index) => ( |
| 119 | + <ChatLine key={index} role={role} content={content} /> |
| 120 | + ))} |
| 121 | + |
| 122 | + {loading && <LoadingChatLine />} |
| 123 | + |
| 124 | + {messages.length < 2 && ( |
| 125 | + <span className="mx-auto flex flex-grow text-gray-600 clear-both"> |
| 126 | + Type a message to start the conversation |
| 127 | + </span> |
| 128 | + )} |
| 129 | + <InputMessage |
| 130 | + input={input} |
| 131 | + setInput={setInput} |
| 132 | + sendMessage={sendMessage} |
| 133 | + /> |
| 134 | + </div> |
| 135 | + ) |
| 136 | +} |
0 commit comments