import React, { useState, useEffect, useRef } from 'react'; const ChatInterface = () => { const [messages, setMessages] = useState([ { role: 'assistant', content: 'Hello! I am your custom LLM. How can I help you today?' } ]); const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const messagesEndRef = useRef(null); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }; useEffect(scrollToBottom, [messages]); const handleSubmit = async (e) => { e.preventDefault(); if (!input.trim()) return; const userMessage = { role: 'user', content: input }; setMessages(prev => [...prev, userMessage]); setInput(''); setIsLoading(true); try { const response = await fetch('/api/chat', { // Proxied to HF/FastAPI method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: [...messages, userMessage].map(m => ({ role: m.role, content: m.content })) }), }); const data = await response.json(); setMessages(prev => [...prev, { role: 'assistant', content: data.choices[0].message.content }]); } catch (error) { console.error('Error:', error); setMessages(prev => [...prev, { role: 'assistant', content: 'Sorry, I encountered an error. Please check your backend connection.' }]); } finally { setIsLoading(false); } }; return (
Connected to HF Spaces / FastAPI Backend
{m.content}