'use client'; import { useState, useRef } from 'react'; import { streamChat, ChatRequest } from '../utils/api'; interface Message { role: 'user' | 'assistant'; content: string; } export default function ChatApp() { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const endRef = useRef(null); const scrollToEnd = () => { endRef.current?.scrollIntoView({ behavior: 'smooth' }); }; const sendMessage = async () => { if (!input.trim() || loading) return; const prompt = input; setInput(''); setMessages((prev) => [...prev, { role: 'user', content: prompt }, { role: 'assistant', content: '' }]); setLoading(true); try { const req: ChatRequest = { user: 'demo', session: 'default', prompt }; for await (const chunk of streamChat(req)) { setMessages((prev) => { const msgs = [...prev]; msgs[msgs.length - 1] = { role: 'assistant', content: msgs[msgs.length - 1].content + chunk, }; return msgs; }); scrollToEnd(); } } catch (err) { console.error(err); setMessages((prev) => { const msgs = [...prev]; msgs[msgs.length - 1] = { role: 'assistant', content: 'Error retrieving response', }; return msgs; }); } finally { setLoading(false); scrollToEnd(); } }; const onSubmit = (e: React.FormEvent) => { e.preventDefault(); void sendMessage(); }; return (
{messages.map((msg, idx) => (
{msg.content}
))}
setInput(e.target.value)} placeholder="Type your message..." />
); }