Browse Source

ai优化1

7 2 days ago
parent
commit
f437b49edd

BIN
app-邻助星/OIP-C.jpg


BIN
app-邻助星/生成特定图标图片.png


+ 2 - 0
myapp/src/app/ai-agent/ai-agent.page.html

@@ -16,6 +16,8 @@
            [class.user-message]="msg.role === 'user'"
            [class.assistant-message]="msg.role === 'assistant'"
            class="message-item">
+        <!-- 仅在助手消息时显示姓名 -->
+        <span *ngIf="msg.role === 'assistant'" class="ai-name">友邻助手</span>
         <div class="message-bubble">
           {{ msg.content }}
           <span class="message-time">{{ msg.time | date:'HH:mm' }}</span>

+ 22 - 2
myapp/src/app/ai-agent/ai-agent.page.scss

@@ -16,11 +16,12 @@
 /* 单条消息布局 */
 .message-item {
   display: flex;
+  flex-direction: column;
   &.user-message {
-    justify-content: flex-end;
+    align-items: flex-end;
   }
   &.assistant-message {
-    justify-content: flex-start;
+    align-items: flex-start;
   }
 }
 
@@ -83,4 +84,23 @@
   &:hover {
     transform: scale(1.08);  /* 悬停放大效果 */
   }
+}
+
+.ai-name {
+  font-weight: bold;
+  color: #333;
+  margin-bottom: 5px;
+}
+
+.avatar-name-container {
+  display: flex;
+  align-items: center;
+  margin-bottom: 5px;
+}
+
+.avatar {
+  width: 30px;
+  height: 30px;
+  border-radius: 50%;
+  margin-right: 10px;
 }

+ 39 - 17
myapp/src/app/ai-agent/ai-agent.page.ts

@@ -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 = '抱歉,当前无法为您提供服务。';
     }
   }
 

BIN
myapp/src/app/ai-agent/pic1.png