|
@@ -14,6 +14,7 @@ export class AiAgentPage {
|
|
|
userInput: string = '';
|
|
|
conversation: { role: 'user' | 'assistant'; content: string; time: Date }[] = []; /* 新增time字段 */
|
|
|
@ViewChild('conversationContainer') conversationContainer!: ElementRef; /* 获取消息容器引用 */
|
|
|
+ currentAssistantResponse: string = ''; // 用于存储当前助手的流式响应
|
|
|
|
|
|
async sendMessage() {
|
|
|
if (!this.userInput.trim()) return;
|
|
@@ -28,7 +29,14 @@ export class AiAgentPage {
|
|
|
this.userInput = '';
|
|
|
this.scrollToBottom(); /* 滚动到最新消息 */
|
|
|
|
|
|
- // 调用大模型API(示例,需替换为实际接口)
|
|
|
+ // 初始化助手消息,明确指定 role 类型
|
|
|
+ const assistantMessage: { role: 'user' | 'assistant'; content: string; time: Date } = {
|
|
|
+ role: 'assistant',
|
|
|
+ content: '',
|
|
|
+ time: new Date()
|
|
|
+ };
|
|
|
+ this.conversation.push(assistantMessage);
|
|
|
+
|
|
|
try {
|
|
|
// 请替换为正确的 DeepSeek API 地址和模型名称
|
|
|
const response = await fetch('https://api.deepseek.com/chat/completions', {
|
|
@@ -44,33 +52,47 @@ export class AiAgentPage {
|
|
|
messages: this.conversation.map(msg => ({
|
|
|
role: msg.role,
|
|
|
content: msg.content
|
|
|
- }))
|
|
|
+ })),
|
|
|
+ stream: true // 开启流式输出
|
|
|
})
|
|
|
});
|
|
|
|
|
|
- // 检查响应状态
|
|
|
if (!response.ok) {
|
|
|
const errorText = await response.text();
|
|
|
throw new Error(`API 请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);
|
|
|
}
|
|
|
|
|
|
- const data = await response.json();
|
|
|
- if (data.choices?.[0]?.message) {
|
|
|
- // 添加当前时间戳
|
|
|
- this.conversation.push({
|
|
|
- role: 'assistant',
|
|
|
- content: data.choices[0].message.content,
|
|
|
- time: new Date()
|
|
|
- });
|
|
|
+ const reader = response.body?.getReader();
|
|
|
+ const decoder = new TextDecoder('utf-8');
|
|
|
+
|
|
|
+ if (reader) {
|
|
|
+ while (true) {
|
|
|
+ const { done, value } = await reader.read();
|
|
|
+ if (done) break;
|
|
|
+
|
|
|
+ const chunk = decoder.decode(value);
|
|
|
+ const lines = chunk.split('\n').filter(line => line.trim() !== '');
|
|
|
+
|
|
|
+ for (const line of lines) {
|
|
|
+ const data = line.replace(/^data: /, '');
|
|
|
+ if (data === '[DONE]') break;
|
|
|
+
|
|
|
+ try {
|
|
|
+ const jsonData = JSON.parse(data);
|
|
|
+ if (jsonData.choices?.[0]?.delta?.content) {
|
|
|
+ this.currentAssistantResponse += jsonData.choices[0].delta.content;
|
|
|
+ assistantMessage.content = this.currentAssistantResponse;
|
|
|
+ this.scrollToBottom();
|
|
|
+ }
|
|
|
+ } catch (parseError) {
|
|
|
+ console.error('解析流式数据时出错:', parseError);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
} catch (error) {
|
|
|
console.error('大模型请求失败:', error);
|
|
|
- // 添加当前时间戳
|
|
|
- this.conversation.push({
|
|
|
- role: 'assistant',
|
|
|
- content: '抱歉,当前无法为您提供服务。',
|
|
|
- time: new Date()
|
|
|
- });
|
|
|
+ assistantMessage.content = '抱歉,当前无法为您提供服务。';
|
|
|
}
|
|
|
}
|
|
|
|