import React, { useState, useEffect } from "react"; const ChatBox = ({ activeThread }) => { const [messages, setMessages] = useState([]); const [userInput, setUserInput] = useState(""); const [isStreaming, setIsStreaming] = useState(false); const FLASK_API_URL = process.env.FLASK_API_URL; // useEffect(() => { // // Fetch existing messages for the active thread // fetch(`http://127.0.0.1:5000/api/chat/${activeThread}`) // .then((response) => response.json()) // .then((data) => setMessages(data)); // }, [activeThread]); const sendMessage = async () => { if (!userInput.trim()) return; const newMessage = { sender: "user", message: userInput }; setMessages((prevMessages) => [...prevMessages, newMessage]); setUserInput(""); try { setIsStreaming(true); const response = await fetch(FLASK_API_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ thread_id: activeThread, prompt: userInput }), }); if (!response.ok) { console.error("Failed to stream response"); setIsStreaming(false); return; } const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8"); let streamingMessage = ""; while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); streamingMessage += chunk; setMessages((prevMessages) => { const updatedMessages = [...prevMessages]; const lastMessage = updatedMessages[updatedMessages.length - 1]; if (lastMessage && lastMessage.sender === "bot") { lastMessage.message = streamingMessage; } else { updatedMessages.push({ sender: "bot", message: streamingMessage }); } return updatedMessages; }); } setIsStreaming(false); } catch (error) { console.error("Error during streaming:", error); setIsStreaming(false); } }; const renderMessage = (message) => { if (message.message.includes("```")) { // Handle code block const parts = message.message.split(/```/g); return parts.map((part, index) => (
{part}
) : (
{part}
)}
{message.message}
; }; const handleKeyDown = (event) => { if (event.key === "Enter") { sendMessage(); } }; return (