index.tsx
8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import React, {useState, useEffect, useRef} from "react";
import './style.less'
import { Input, Button } from '@chatui/core';
import Markdown from '@/components/deepSeekIndex/Markdown'
import banner from "./banner_base.png";
import bg from "./bg_base.jpg";
import refresh from "./refresh.png";
import _ from 'lodash';
export const getTime = () => {
// 创建 Date 对象
const now = new Date();
// 获取月份(0-11,需 +1 转为实际月份)
const month = String(now.getMonth() + 1).padStart(2, '0'); // 补零成两位数
// 获取日期
const day = String(now.getDate()).padStart(2, '0');
// 获取小时
const hours = String(now.getHours()).padStart(2, '0');
// 获取分钟
const minutes = String(now.getMinutes()).padStart(2, '0');
// 组合成目标格式
const result = `${month}月${day}日 ${hours}:${minutes}`;
console.log(result); // 示例输出:07月15日 08:30
return result;
}
const example_1 = [
{
name: '联通提供哪些服务?',
id: '1'
},
{
name: '怎么办理国际漫游服务?',
id: '2'
},
{
name: '如何办理宽带?',
id: '3'
}
]
const example_2 = [
{
name: '5G套餐推荐',
id: '4'
},
{
name: '如何办理语音通话和短信的基础套餐?',
id: '5'
},
{
name: '上不了网怎么办?',
id: '6'
}
]
const DeepSeekIndex: React.FC = () => {
const [searchValue, setSearchValue] = useState<any>();
const [loading, setLoading] = useState<boolean>(false);
const [disabled, setDisabled] = useState<boolean>(false);
const [exampleFlag, setExampleFlag] = useState<string>('1')
const [chatHistory, setChatHistory] = useState<{role: string, answer: string, info?: any[]}[]>([]);
const [currentResponse, setCurrentResponse] = useState<string>('');
const chatRef = useRef(null);
useEffect(() => {
const _time = getTime();
const newHistory = [...chatHistory,
{role: 'time', answer: _time},
{
role: 'example',
answer: '',
info: example_1
}
];
console.log('newHistory', newHistory)
setChatHistory(newHistory);
}, [])
const refreshFun = () => {
const _exampleFlag = _.cloneDeep(exampleFlag);
const _example = _exampleFlag === '1' ? example_2 : example_1;
const _chatHistory = _.cloneDeep(chatHistory);
_chatHistory?.forEach((item: any) => {
if (item?.role === 'example') {
item.info = _example
}
})
setChatHistory(_chatHistory);
const _newExampleFlag = _exampleFlag === '1' ? '2' : '1'
setExampleFlag(_newExampleFlag);
}
const send = async (_searchValue?: string) => {
if (disabled) return;
setLoading(true)
setDisabled(true);
console.log('searchValue', searchValue)
const _value = _searchValue ? _searchValue : searchValue;
const data = {
"query": _value,
"inputs": {},
"response_mode": "streaming",
"user": "11",
"conversation_id": ""
}
const customHeaders = {
'Authorization': 'Bearer app-XxOBqpQr6u4c43tIl6by4vpK'
}
const _time = getTime();
const newHistory = [...chatHistory,
{role: 'time', answer: _time},
{role: 'user', answer: _value}
];
setChatHistory(newHistory);
setSearchValue('');
let _currentResponse = '';
try {
const response = await fetch('http://36.34.99.80:8088/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: any = response?.body?.getReader();
const decoder = new TextDecoder();
let buffer: string = '';
while (true) {
const {done, value} = await reader?.read();
if (done) break;
buffer += decoder?.decode(value, {stream: true});
const lines: any[] = buffer?.split('\n');
buffer = lines?.pop();
setLoading(false)
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('');
setDisabled(false);
} catch (error) {
console.error('Stream error:', error);
setLoading(false)
}
}
// 让会话一直展示最新
useEffect(() => {
if (chatRef.current) {
// @ts-ignore
chatRef.current.scrollTop = chatRef.current.scrollHeight;
}
}, [currentResponse]);
useEffect(() => {
console.log('chatHistory', chatHistory)
}, [chatHistory])
const handleKeyDown = (e: any) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault(); // 阻止默认换行
send();
}
};
return (
<div className={'deep-seek'}>
<img className={'deep-seek_bg'} src={bg} alt=""/>
<div
ref={chatRef}
className={'deep-seek_content'}
>
<div className={'deep-seek_header'}>
<img src={banner} alt=""/>
</div>
{chatHistory?.map((msg, index) => (
<div key={index} className={`${msg.role === 'user' ? 'content-right' : msg.role === 'assistant' ? 'content-left' : 'content-center' }`}>
{
msg.role === 'time' ?
<div className={'current-time'}>{msg?.answer}</div>:
msg.role === 'example'? <div className={'current-example'}>
<div className={'current-example_head'}>
<p className={'current-example_head-name'}>你想了解什么呢</p>
<img src={refresh} className={'refresh'} alt="" onClick={refreshFun}/>
</div>
{
msg?.info?.map((item:any) => {
return <div
className={'omit1 current-example_title'}
key={item?.id}
onClick={() => send(item?.name || '')}
>{item?.name}</div>
})
}
</div> :
msg.role === 'user' ? <p className={'current-ask'}>{msg?.answer}</p> :
<Markdown content={msg?.answer || ''}/>
}
</div>
))}
{
loading ? <div className="content-left">
<div className={'current-think'}>
思考中...
</div>
</div> : ''
}
{currentResponse ? (
<div className="content-left">
<Markdown content={currentResponse || ''}/>
</div>
) : ''}
</div>
<div className={'deep-seek_footer'}>
<Input
type="text"
value={searchValue}
className="deep-seek_footer-search"
placeholder="输入..."
onChange={(val: string) => setSearchValue(val)}
onKeyDown={handleKeyDown}
/>
<Button className={`deep-seek_footer-send ${disabled ? 'disabled' : ''}`} color={'primary'} onClick={() =>send()}>发送</Button>
</div>
</div>
);
};
export default DeepSeekIndex;