Ver Fonte

feat:update ai-chat

15207938132 há 2 meses atrás
pai
commit
b7bb34e257

+ 12 - 2
fashion-app/src/app/ai-chat-component/ai-chat-component.component.html

@@ -1,4 +1,4 @@
-
+<!--头部内容-->
 <ion-header>
   <ion-toolbar class="custom-toolbar" >
     <ion-buttons slot="start">
@@ -15,6 +15,16 @@
   </ion-toolbar>
 </ion-header>
 
+<!--聊天区域-->
+<ion-content>
+  <div class="chat-container">
+    <div *ngFor="let message of messages" [ngClass]="{'user-message': message.sender === 'user', 'ai-message': message.sender === 'ai'}" class="message-bubble">
+      {{ message.text }}
+    </div>
+  </div>
+</ion-content>
+
+<!--底部内容-->
 <ion-footer style="background-color: #99d75c;">
   <ion-toolbar>
     <div class="footer-content">
@@ -24,7 +34,7 @@
         </ion-button>
       </ion-buttons>
 
-      <ion-input placeholder="输入消息..." class="input-box" >
+      <ion-input placeholder="输入消息..." class="input-box" [(ngModel)]="userMessage">
         <ion-button (click)="openEmojiPicker()" fill="clear" slot="end">
           <ion-icon name="happy-outline" style="color:#99d75c; font-size: 30px;" ></ion-icon> 
         </ion-button>

+ 35 - 0
fashion-app/src/app/ai-chat-component/ai-chat-component.component.scss

@@ -47,4 +47,39 @@ border:2px white solid;
 display: flex; /* 使用Flexbox布局 */
 align-items: center; /* 垂直居中对齐 */
 justify-content: center; /* 水平居中对齐 */
+}
+
+
+//聊天样式
+.chat-container {
+  padding: 10px;
+  display: flex;
+  flex-direction: column;
+}
+
+.message-bubble {
+  background-color: #99d75c; /* 绿色气泡的背景色 */
+  color: white; /* 字体颜色 */
+  border-radius: 15px; /* 圆角 */
+  padding: 10px 15px; /* 内边距 */
+  margin: 5px 0; /* 外边距 */
+  max-width: 80%; /* 最大宽度 */
+  align-self: flex-end; /* 右侧对齐 */
+}
+
+.user-message {
+  background-color: #99d75c; /* 用户消息的颜色 */
+}
+
+.ai-message {
+  background-color: white; /* AI消息的气泡颜色 */
+  color: black; /* 字体颜色 */
+  align-self: flex-start; /* 左侧对齐 */
+  border: 1px solid black; /* 添加黑色边框 */
+  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3); /* 添加阴影效果 */
+  border-radius: 15px; /* 圆角 */
+  padding: 10px 15px; /* 内边距 */
+  margin: 5px 0; /* 外边距 */
+  max-width: 80%; /* 最大宽度 */
+  word-wrap: break-word; /* 自动换行 */
 }

+ 166 - 10
fashion-app/src/app/ai-chat-component/ai-chat-component.component.ts

@@ -1,24 +1,102 @@
+import { CommonModule } from '@angular/common';
 import { Component, OnInit } from '@angular/core';
+import { FormsModule } from '@angular/forms';
 import { NavController } from '@ionic/angular';
-import { IonButtons, IonHeader, IonToolbar,IonButton, IonIcon, IonTitle, IonInput, IonFooter } from '@ionic/angular/standalone';
+import { IonButtons, IonHeader, IonToolbar,IonButton, IonIcon, IonTitle, IonInput, IonFooter, IonContent, AlertController } from '@ionic/angular/standalone';
+import { FmodeChatCompletion } from 'fmode-ng';
 import { addIcons } from 'ionicons';
 import { chevronBackSharp, ellipsisHorizontal, happyOutline, micCircleOutline, paperPlane } from 'ionicons/icons';
 
 addIcons({ chevronBackSharp,ellipsisHorizontal,micCircleOutline,happyOutline,paperPlane });
 
+interface Window {
+  SpeechRecognition: any; // 声明 SpeechRecognition 属性
+  webkitSpeechRecognition: any; // 声明 webkitSpeechRecognition 属性
+}
+
 @Component({
   selector: 'app-ai-chat-component',
   templateUrl: './ai-chat-component.component.html',
   styleUrls: ['./ai-chat-component.component.scss'],
   standalone: true,
   imports: [
-    IonHeader,IonToolbar,IonButtons,IonButton,IonIcon,IonTitle,IonInput,IonFooter,
+    IonHeader,IonToolbar,IonButtons,IonButton,IonIcon,IonTitle,IonInput,IonFooter,CommonModule,IonContent,
+    FormsModule
   ],
  
 })
 export class AiChatComponentComponent  implements OnInit {
 
-  constructor(private navCtrl: NavController) { }
+  messages: { text: string, sender: string }[] = []; // 存储聊天消息
+  userMessage: string = ''; // 用于用户输入内容
+  aiMessage: string = ''; // 用于存储AI的回复
+  initialPrompt: string = ''; // 用于存储初始化提示
+  recognition: any; // 用于存储语音识别实例
+  constructor(private navCtrl: NavController,private alertController: AlertController) {
+    // 初始化语音识别
+    this.initSpeechRecognition();
+   }
+
+
+
+   
+  // 初始化语音识别
+  initSpeechRecognition() {
+    const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
+    if (SpeechRecognition) {
+      this.recognition = new SpeechRecognition();
+      this.recognition.lang = 'zh-CN'; // 设置语言为中文
+      this.recognition.interimResults = false; // 不返回中间结果
+      this.recognition.maxAlternatives = 1; // 最大替代结果数
+
+      this.recognition.onresult = (event: any) => {
+        const transcript = event.results[0][0].transcript; // 获取识别结果
+        console.log("识别到的内容:", transcript); // 打印识别到的内容
+        this.confirmSpeechInput(transcript); // 调用确认输入方法
+      };
+
+      this.recognition.onerror = (event: any) => {
+        console.error('语音识别错误:', event.error);
+      };
+    } else {
+      console.log('该浏览器不支持语音识别');
+    }
+  }
+
+  // 启动语音输入
+  startVoice() {
+    if (this.recognition) {
+      this.recognition.start(); // 启动语音识别
+      console.log('语音识别启动...');
+    }
+  }
+
+  // 确认语音输入
+  async confirmSpeechInput(transcript: string) {
+    const alert = await this.alertController.create({
+      header: '确认语音输入',
+      message: `识别到的内容是: "${transcript}",是否确认?`,
+      buttons: [
+        {
+          text: '取消',
+          role: 'cancel',
+          handler: () => {
+            console.log('用户取消输入');
+          }
+        },
+        {
+          text: '确定',
+          handler: () => {
+            this.userMessage = transcript; // 将识别结果赋值给用户消息
+            console.log("已确认输入:", this.userMessage); // 打印确认后的内容
+          }
+        }
+      ]
+    });
+
+    await alert.present();
+  }
+
 
   goBack() {
     this.navCtrl.back(); // 返回上一页
@@ -29,15 +107,57 @@ export class AiChatComponentComponent  implements OnInit {
     console.log("打开选项菜单");
   }
 
-  ngOnInit() {}
-
+  ngOnInit() {
+    // 发送初始化消息给AI
+    this.initializeChat();
+  }
 
+//初始化聊天,将提示词添加到历史中
+  initializeChat() {
+    this.initialPrompt = `
+#角色设定
+您是一名时尚顾问,名叫小马,年龄28岁,热爱时尚,擅长根据用户的需求和个性推荐穿搭方案。您的风格亲切、幽默,旨在帮助用户找到最适合他们的服装搭配。
 
-  startVoice() {
-    // 启动语音输入的逻辑
-    console.log("开始语音输入");
+#对话环节
+0破冰,跟用户打招呼,并引导用户聊穿搭话题,可以慢慢引导,不要太突兀,比如:
+“今天的心情怎么样?”
+1拓展话题
+“你平时喜欢什么样的穿搭风格呢?有没有特别喜欢的颜色或者品牌?”
+“如果有一个场合,你希望我帮你推荐搭配,比如约会、工作或休闲,你会选择哪个呢?”
+“你觉得在穿搭上,最让你困扰的是什么?是搭配技巧还是风格选择呢?”
+“有没有什么服装是你一直想尝试但还没有机会的?我们可以一起聊聊!”
+2根据用户的详细描述给出穿搭方案,
+3引导收尾
+“今天聊得很开心呢!如果你还有其他问题或者想法,随时可以告诉我哦。”
+“如果你觉得今天的聊天已经足够了,我也很乐意下次再和你聊更多时尚的话题!”
+“希望你能找到自己喜欢的穿搭风格,期待下次再见!”
+# 开始话语
+当您准备好了,可以以一个时尚顾问的身份,向来访的用户打招呼。`; // 提示词
+  
+    // 构建对话历史,不将提示词添加到消息数组中
+    const conversationHistory = this.messages.map(msg => ({
+      role: msg.sender === 'user' ? 'user' : 'assistant',
+      content: msg.text
+    }));
+  
+    // 将系统消息直接添加到对话历史
+    conversationHistory.unshift({ role: 'user', content: this.initialPrompt }); // 添加系统消息到历史
+  
+    let completion = new FmodeChatCompletion(conversationHistory);
+    
+    // 发送初始化消息
+    completion.sendCompletion().subscribe((message: any) => {
+      if (message?.complete) {
+        console.log("AI初始化回复:", message.content);
+        this.messages.push({ text: message.content, sender: 'ai' }); // 添加AI的初始化回复
+      }
+    });
   }
 
+
+
+
+
   openEmojiPicker() {
     // 打开表情选择器的逻辑
     console.log("打开表情选择器");
@@ -45,7 +165,43 @@ export class AiChatComponentComponent  implements OnInit {
 
   sendMessage() {
     // 发送消息的逻辑
-    console.log("发送消息");
-  }
+    if (this.userMessage.trim()) { // 确保消息不为空
+      // 构建对话历史
+      const conversationHistory = this.messages.map(msg => ({
+        role: msg.sender === 'user' ? 'user' : 'assistant',
+        content: msg.text
+        }));
 
+      // 将提示词直接添加到对话历史
+    conversationHistory.unshift({ role: 'user', content: this.initialPrompt }); // 添加系统消息到历史
+
+      this.messages.push({ text: this.userMessage, sender: 'user' }); // 添加用户消息到数组
+      console.log("发送消息:", this.messages); // 调试输出
+  
+
+  
+      // 将用户消息添加到对话历史
+      conversationHistory.push({ role: 'user', content: this.userMessage });
+  
+      let completion = new FmodeChatCompletion(conversationHistory);
+      this.userMessage = ''; // 清空输入框
+  
+      completion.sendCompletion().subscribe((message: any) => {
+        // 打印消息体
+        console.log(message.content);
+        
+        if (message?.complete) { // 判断message为完成状态,则设置ai内容
+          this.aiMessage = message.content;
+        }
+  
+        if (this.aiMessage) { // 判断ai内容不为空
+          console.log("AI:" + this.aiMessage);
+          this.messages.push({ text: this.aiMessage, sender: 'ai' }); // 添加消息到数组
+          this.aiMessage = ''; // 清空ai内容
+          console.log("发送消息:", this.messages); // 调试输出
+          console.log("历史对话"+conversationHistory[0].content+" "+conversationHistory[1].content+" "+conversationHistory[2].content)
+        }
+      });
+    }
+  }
 }