import React, { useState, useRef, useEffect } from 'react'; export default function ChatInterface() { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const [image, setImage] = useState(null); const messagesEndRef = useRef(null); const fileInputRef = useRef(null); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }; useEffect(() => { scrollToBottom(); }, [messages]); const handleImageUpload = (e) => { const file = e.target.files[0]; if (file && file.type.startsWith('image/')) { const reader = new FileReader(); reader.onloadend = () => { setImage(reader.result); }; reader.readAsDataURL(file); } }; const handleSubmit = async (e) => { e.preventDefault(); if (!input.trim() && !image) return; const userMessage = { role: 'user', content: input, image: image, }; setMessages(prev => [...prev, userMessage]); setInput(''); setIsLoading(true); try { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ messages: [...messages, userMessage].map(msg => ({ role: msg.role, content: msg.content, })), image: image, }), }); const data = await response.json(); if (response.ok) { setMessages(prev => [...prev, { role: 'assistant', content: data.response, }]); } else { throw new Error(data.error || 'Failed to get response'); } } catch (error) { console.error('Error:', error); setMessages(prev => [...prev, { role: 'assistant', content: 'Sorry, I encountered an error. Please try again.', }]); } finally { setIsLoading(false); setImage(null); if (fileInputRef.current) { fileInputRef.current.value = ''; } } }; return (
{messages.length === 0 && (

Welcome to GLM-4.6V-Flash

Upload an image and ask me about it!

)} {messages.map((message, index) => (
{message.image && ( Uploaded )}

{message.content}

))} {isLoading && (
)}
{image && (
Preview
)}
setInput(e.target.value)} placeholder="Type your message..." className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" disabled={isLoading} />
); }