'use client' import React, { useState, useEffect, useRef } from 'react' import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Textarea } from "@/components/ui/textarea" import { Card, CardContent } from "@/components/ui/card" import { ChevronDown, ChevronUp, Send } from 'lucide-react' export default function AIChat() { const [messages, setMessages] = useState([]) const [input, setInput] = useState('') const [apiKey, setApiKey] = useState('') const [thinking, setThinking] = useState('') const [isThinkingVisible, setIsThinkingVisible] = useState(false) const chatEndRef = useRef(null) useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages]) const handleSubmit = async (e) => { e.preventDefault() if (!input.trim()) return const newMessage = { role: 'user', content: input } setMessages([...messages, newMessage]) setInput('') try { // Call /think endpoint const thinkResponse = await fetch('/api/think', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: [...messages, newMessage], api_key: apiKey }), }) if (!thinkResponse.ok) throw new Error('Think request failed') const reader = thinkResponse.body.getReader() let thinkingContent = '' while (true) { const { done, value } = await reader.read() if (done) break const chunk = new TextDecoder().decode(value) thinkingContent += chunk setThinking(thinkingContent) } // Call /chat endpoint with the thinking result const chatResponse = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: [...messages, newMessage, { role: 'assistant', content: thinkingContent }], api_key: apiKey }), }) if (!chatResponse.ok) throw new Error('Chat request failed') const chatReader = chatResponse.body.getReader() let chatContent = '' while (true) { const { done, value } = await chatReader.read() if (done) break const chunk = new TextDecoder().decode(value) chatContent += chunk setMessages(prev => [...prev.slice(0, -1), { role: 'assistant', content: chatContent }]) } } catch (error) { console.error('Error:', error) setMessages(prev => [...prev, { role: 'assistant', content: 'An error occurred. Please try again.' }]) } } return (
{line.replace(/<\/?thinking>|<\/?step>/g, '')}
} return null })}