index.tsx 4.42 KB
import React, {useState, useEffect, useRef} from "react";
import '../../components/deepSeekIndex/base.less'
import './style.less'
import { Button, Input } from 'antd';
import Markdown from '@/components/deepSeekIndex/Markdown'
import laBanner from "./laBanner.png";

const LaTest: React.FC = () => {
    const [searchValue, setSearchValue] = useState<any>();

    const [chatHistory, setChatHistory] = useState<any[]>([]);
    const [currentResponse, setCurrentResponse] = useState<string>('');

    const chatRef = useRef(null);

    const send = async () => {
        console.log('searchValue', searchValue)
        const data = {
            "query": searchValue,
            "inputs": {},
            "response_mode": "streaming",
            "user": "11",
            "conversation_id": ""
        }
        const customHeaders = {
            'Authorization': 'Bearer app-nvw8Y9taTRWuKg9ZfaoMXwNC'
        }

        const newHistory = [...chatHistory, { role: 'user', answer: searchValue }];
        setChatHistory(newHistory);
        setSearchValue('');
        let _currentResponse = '';

        try {
            const response = await fetch('http://10.9.5.168/v1/chat-messages', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // 这里可以添加自定义请求头
                    ...customHeaders
                },
                body: JSON.stringify({...data })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;
                buffer += decoder?.decode(value, { stream: true });
                const lines = buffer?.split('\n');
                buffer = lines.pop();
                lines.forEach(line => {
                    if (line.startsWith('data:')) {
                        const data = JSON.parse(line?.slice(5)?.trim());
                        setCurrentResponse(prev => prev + (data?.answer || ''));
                        _currentResponse = _currentResponse + (data?.answer || '');
                    }
                });
            }

            const updatedHistory = [...newHistory, { role: 'assistant', answer: _currentResponse }];
            setChatHistory(updatedHistory);
            setCurrentResponse('');


        } catch (error) {
            console.error('Stream error:', error);
        }

    }

    // 让会话一直展示最新
    useEffect(() => {
        if (chatRef.current) {
            chatRef.current.scrollTop = chatRef.current.scrollHeight;
        }
    }, [currentResponse]);


    useEffect(() => {
        console.log('chatHistory', chatHistory)
    }, [chatHistory])

    return (
       <div className={'la-test'}>
           <div className={'la-test_header'}>
               <img src={laBanner} alt=""/>
           </div>
           <div
               ref={chatRef}
               className={'la-test_content'}
           >
               {chatHistory?.map((msg, index) => (
                   <p key={index} className={`mb-2 ${msg.role === 'user' ? 'text-right' : 'text-left'}`}>
                       {
                           msg?.role ? <div className={'role'}>
                               {msg?.role === 'user' ? '问' : msg?.role === 'assistant' ? '答' : ''}
                           </div> : ''
                       }
                       <Markdown content={msg?.answer}/>
                   </p>
               ))}
               {currentResponse && (
                   <p className="mb-2 text-left current">
                       <div className={'role'}>答</div>
                       <Markdown content={currentResponse} />
                   </p>
               )}
           </div>
           <div className={'la-test_footer'}>
               <Input
                   type="text"
                   value={searchValue}
                   className="company-list-search-input"
                   placeholder="输入..."
                   onChange={(e) => setSearchValue(e.target.value)}
                   onPressEnter={send}
               />
               <Button type={'primary'} onClick={send}>发送</Button>
           </div>

       </div>
    );
};

export default LaTest;