page-companion.component_20241201204531.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Component, OnInit } from '@angular/core';
  2. import {IonHeader, IonToolbar, IonTitle,IonInput, IonContent,IonButton, IonIcon } from '@ionic/angular/standalone';
  3. import { addIcons } from 'ionicons';
  4. import { chevronBack,heart } from 'ionicons/icons';
  5. import { Router } from '@angular/router';
  6. import { FmodeChatCompletion } from 'fmode-ng';
  7. import { CommonModule } from '@angular/common'; // 添加 CommonModule
  8. import { FormsModule } from '@angular/forms'; // 添加 FormsModule
  9. @Component({
  10. selector: 'app-page-companion',
  11. templateUrl: './page-companion.component.html',
  12. styleUrls: ['./page-companion.component.scss'],
  13. standalone: true,
  14. imports:[IonHeader, CommonModule, FormsModule, IonToolbar, IonTitle, IonContent,IonButton,IonInput, IonIcon]
  15. })
  16. export class PageCompanionComponent implements OnInit {
  17. userInput: string = ''; // 用户输入内容
  18. messages: { role: string, content: string }[] = []; // 消息列表
  19. // 用户输入变化
  20. onInputChange(ev: any) {
  21. this.userInput = ev.detail.value;
  22. }
  23. // 发送消息
  24. sendMessage() {
  25. if (!this.userInput.trim()) return; // 确保输入不为空
  26. // 添加用户消息到消息列表
  27. this.messages.push({ role: 'user', content: this.userInput });
  28. // 调用 AI 接口
  29. const promptTemplate = `
  30. 请你先分析用户的口述,如果是明显需要心理咨询帮助的意思,那么请你作为专业的心理咨询师,根据用户的描述提供情感疏导和建议;如果用户只是简单的日常聊天,比如吐槽、唠嗑,那么请你作为一个朋友的形象,根据的用户的消息提供友好并有情绪价值的回复。
  31. 以下是用户的口述:${this.userInput}
  32. `;
  33. const completion = new FmodeChatCompletion([
  34. { role: 'system', content: '' },
  35. { role: 'user', content: promptTemplate }
  36. ]);
  37. let aiResponse = '';
  38. completion.sendCompletion().subscribe((message: any) => {
  39. // 将生成的消息内容累加到 aiResponse 中
  40. aiResponse += message.content; // 假设 message.content 是 AI 生成的内容
  41. // 添加 AI 消息到消息列表
  42. this.messages.push({ role: 'ai', content:aiResponse });
  43. // 清空用户输入框
  44. this.userInput = '';
  45. });
  46. }
  47. constructor(private router: Router) {
  48. addIcons({chevronBack,heart});
  49. }
  50. goTab1(){
  51. this.router.navigate(['tabs/tab1']);
  52. }
  53. ngOnInit() {}
  54. }