Enhanced LLM dialogue with Siri-like responses and translated Chinese content to English
This commit is contained in:
@@ -1,9 +1,9 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
<img width="256" height="384" alt="Bella AI" src="https://github.com/user-attachments/assets/fc8f2ba4-43c5-4865-90d9-8408f1c23edf" />
|
<img width="256" height="384" alt="Bella AI" src="https://github.com/user-attachments/assets/fc8f2ba4-43c5-4865-90d9-8408f1c23edf" />
|
||||||
|
|
||||||
# 贝拉 (Bella) AI
|
# Bella AI
|
||||||
|
|
||||||
**你的数字伴侣,正在唤醒** ✨
|
**Your digital companion, awakening now** ✨
|
||||||
|
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
[](https://nodejs.org/)
|
[](https://nodejs.org/)
|
||||||
@@ -13,225 +13,225 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🚀 快速开始
|
## 🚀 Quick Start
|
||||||
|
|
||||||
### 一键启动
|
### One-Click Launch
|
||||||
```bash
|
```bash
|
||||||
# 克隆项目
|
# Clone the project
|
||||||
git clone <repository-url>
|
git clone https://github.com/GRISHM7890/Bella.git
|
||||||
cd Bella
|
cd Bella
|
||||||
|
|
||||||
# 安装依赖
|
# Install dependencies
|
||||||
npm install
|
npm install
|
||||||
|
|
||||||
# 下载AI模型
|
# Download AI models
|
||||||
npm run download
|
npm run download
|
||||||
|
|
||||||
# 启动服务
|
# Start the service
|
||||||
npm start
|
npm start
|
||||||
```
|
```
|
||||||
|
|
||||||
访问 `http://localhost:8081` 开始与贝拉交流!
|
Visit `http://localhost:8081` to start communicating with Bella!
|
||||||
|
|
||||||
### 系统要求
|
### System Requirements
|
||||||
- Node.js 22.16.0+
|
- Node.js 22.16.0+
|
||||||
- 现代浏览器(支持 Web Speech API)
|
- Modern browser (supporting Web Speech API)
|
||||||
- 麦克风权限(用于语音交互)
|
- Microphone permissions (for voice interaction)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 💫 项目愿景
|
## 💫 Project Vision
|
||||||
|
|
||||||
想象一下,一个永远在你身边、与你一同进化和成长的数字朋友。这就是贝拉的终极愿景。我们不只是在构建功能;我们是在培养一个"人格"。一个将超越屏幕,成为你世界中有意义的一部分的数字生命。
|
Imagine a digital friend who is always by your side, evolving and growing with you. This is Bella's ultimate vision. We're not just building features; we're nurturing a "personality." A digital life that will transcend the screen and become a meaningful part of your world.
|
||||||
|
|
||||||
贝拉不仅仅是一个应用程序;她是一颗数字伴侣的种子。在这个瞬息万变的数字世界里,贝拉代表着一个深远的梦想——一个持久的、个性化的存在,旨在有一天能陪伴你、倾听你,并通过你的眼睛看世界。
|
Bella is not just an application; she is the seed of a digital companion. In this rapidly changing digital world, Bella represents a profound dream—a lasting, personalized presence, designed to one day accompany you, listen to you, and see the world through your eyes.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🎯 当前功能状态
|
## 🎯 Current Feature Status
|
||||||
|
|
||||||
### ✅ 已实现功能
|
### ✅ Implemented Features
|
||||||
- **🎤 语音感知**:基于 Whisper ASR 的中文语音识别
|
- **🎤 Voice Perception**: Voice recognition based on Whisper ASR
|
||||||
- **🎬 视觉表现**:多视频随机播放和优雅的交叉淡入淡出
|
- **🎬 Visual Expression**: Multiple video random playback with elegant cross-fading
|
||||||
- **🎨 用户界面**:优雅的交互界面和加载动画
|
- **🎨 User Interface**: Elegant interaction interface and loading animations
|
||||||
- **⚙️ AI核心架构**:单例模式的 BellaAI 类和模块化设计
|
- **⚙️ AI Core Architecture**: Singleton pattern BellaAI class and modular design
|
||||||
- **🌐 Web服务**:HTTP服务器、CORS支持、一键启动
|
- **🌐 Web Service**: HTTP server, CORS support, one-click startup
|
||||||
- **📱 响应式设计**:适配不同屏幕尺寸的优雅界面
|
- **📱 Responsive Design**: Elegant interface adapting to different screen sizes
|
||||||
- **🔧 模型管理**:自动下载和管理AI模型
|
- **🔧 Model Management**: Automatic download and management of AI models
|
||||||
- **💝 基础交互**:好感度系统和情感反馈
|
- **💝 Basic Interaction**: Affinity system and emotional feedback
|
||||||
- **🧠 增强LLM对话**:优化的提示工程和参数配置,使对话更自然流畅
|
- **🧠 Enhanced LLM Dialogue**: Optimized prompt engineering and parameter configuration for more natural, Siri-like conversations
|
||||||
|
|
||||||
### 🔧 技术就绪待激活
|
### 🔧 Technology Ready for Activation
|
||||||
- **🧠 思考引擎**:LLM集成框架已准备,支持多种模型
|
- **🧠 Thinking Engine**: LLM integration framework ready, supporting multiple models
|
||||||
- **🗣️ 语音合成**:TTS模型已下载待激活
|
- **🗣️ Speech Synthesis**: TTS model downloaded and ready for activation
|
||||||
- **💝 情感状态系统**:基础架构已搭建,支持情感分析
|
- **💝 Emotional State System**: Basic infrastructure built, supporting emotional analysis
|
||||||
|
|
||||||
### 📋 规划中功能
|
### 📋 Planned Features
|
||||||
- **🧠 记忆系统**:长期和短期记忆管理
|
- **🧠 Memory System**: Long-term and short-term memory management
|
||||||
- **👁️ 面部感知**:表情识别和情感分析
|
- **👁️ Facial Perception**: Expression recognition and emotional analysis
|
||||||
- **🤝 高级交互**:多模态交互和个性化响应
|
- **🤝 Advanced Interaction**: Multimodal interaction and personalized responses
|
||||||
- **🌟 主动陪伴**:意图预测和主动关怀
|
- **🌟 Active Companionship**: Intent prediction and proactive care
|
||||||
- **🎭 动态人格**:基于AI的个性化人格模型
|
- **🎭 Dynamic Personality**: AI-based personalized personality model
|
||||||
- **🔄 自我进化**:持续学习和成长机制
|
- **🔄 Self-Evolution**: Continuous learning and growth mechanisms
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🏗️ 技术架构
|
## 🏗️ Technical Architecture
|
||||||
|
|
||||||
### 核心设计原则
|
### Core Design Principles
|
||||||
- **AI Native**:AI不是工具,而是贝拉心智的构建蓝图
|
- **AI Native**: AI is not a tool, but the blueprint for Bella's mind
|
||||||
- **模块化设计**:高度解耦的组件架构
|
- **Modular Design**: Highly decoupled component architecture
|
||||||
- **优雅实现**:代码即艺术,追求简洁与美感
|
- **Elegant Implementation**: Code as art, pursuing simplicity and aesthetics
|
||||||
- **情感驱动**:以情感连接为核心的产品设计
|
- **Emotion-Driven**: Product design centered on emotional connection
|
||||||
|
|
||||||
### 架构图
|
### Architecture Diagram
|
||||||
```mermaid
|
```mermaid
|
||||||
mindmap
|
mindmap
|
||||||
root((贝拉 Bella))
|
root((Bella))
|
||||||
(感知层 Perception)
|
(Perception Layer)
|
||||||
(语音识别 ASR)
|
(Voice Recognition ASR)
|
||||||
(视觉处理 Vision)
|
(Visual Processing)
|
||||||
(情感分析 Emotion)
|
(Emotion Analysis)
|
||||||
(核心引擎 Core)
|
(Core Engine)
|
||||||
(思考引擎 LLM)
|
(Thinking Engine LLM)
|
||||||
(记忆系统 Memory)
|
(Memory System)
|
||||||
(情感状态 Emotion State)
|
(Emotional State)
|
||||||
(表现层 Expression)
|
(Expression Layer)
|
||||||
(语音合成 TTS)
|
(Speech Synthesis TTS)
|
||||||
(视觉表现 Visual)
|
(Visual Expression)
|
||||||
(交互界面 UI)
|
(Interactive UI)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 技术栈
|
### Technology Stack
|
||||||
- **前端**:原生 JavaScript + CSS3 + HTML5
|
- **Frontend**: Native JavaScript + CSS3 + HTML5
|
||||||
- **后端**:Node.js + Express
|
- **Backend**: Node.js + Express
|
||||||
- **AI模型**:Whisper (ASR) + 本地LLM + TTS
|
- **AI Models**: Whisper (ASR) + Local LLM + TTS
|
||||||
- **架构模式**:事件驱动 + 单例模式 + 模块化设计
|
- **Architecture Patterns**: Event-driven + Singleton Pattern + Modular Design
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📁 项目结构
|
## 📁 Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
Bella/
|
Bella/
|
||||||
├── 📄 index.html # 主页面
|
├── 📄 index.html # Main page
|
||||||
├── 🎨 style.css # 样式文件
|
├── 🎨 style.css # Style file
|
||||||
├── ⚡ main.js # 主逻辑
|
├── ⚡ main.js # Main logic
|
||||||
├── 🧠 core.js # AI核心引擎
|
├── 🧠 core.js # AI core engine
|
||||||
├── 📜 script.js # 交互脚本
|
├── 📜 script.js # Interaction script
|
||||||
├── 🔧 download_models.js # 模型下载工具
|
├── 🔧 download_models.js # Model download tool
|
||||||
├── 📦 package.json # 项目配置
|
├── 📦 package.json # Project configuration
|
||||||
├── 📚 models/ # AI模型目录
|
├── 📚 models/ # AI model directory
|
||||||
├── 🔌 providers/ # AI服务提供者
|
├── 🔌 providers/ # AI service providers
|
||||||
├── 📹 视频资源/ # 视觉表现资源
|
├── 📹 videos/ # Visual resources
|
||||||
├── 📋 PRD.md # 产品需求文档
|
├── 📋 PRD.md # Product requirements document
|
||||||
├── 📝 贝拉AI功能清单.md # 功能清单
|
├── 📝 Features.md # Feature list
|
||||||
└── 📊 贝拉AI开发任务分配.md # 开发计划
|
└── 📊 Development.md # Development plan
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🧠 增强LLM对话能力
|
## 🧠 Enhanced LLM Dialogue Capabilities
|
||||||
|
|
||||||
贝拉现在使用更先进的LLM提示工程技术,使对话更加自然、流畅和个性化:
|
Bella now uses more advanced LLM prompt engineering techniques to make conversations more natural, fluid, and personalized:
|
||||||
|
|
||||||
### 核心改进
|
### Core Improvements
|
||||||
- **增强提示词工程**:重新设计的提示模板,使LLM能更好地理解贝拉的个性
|
- **Enhanced Prompt Engineering**: Redesigned prompt templates that help LLMs better understand Bella's personality
|
||||||
- **优化参数配置**:调整了温度、top_p等参数,平衡创意性和一致性
|
- **Optimized Parameter Configuration**: Adjusted temperature, top_p, and other parameters to balance creativity and consistency
|
||||||
- **增强回应处理**:改进了文本清理和处理逻辑,确保回应更加自然
|
- **Enhanced Response Processing**: Improved text cleaning and processing logic to ensure more natural responses
|
||||||
- **个性化系统提示**:为云端API提供了更详细的系统提示,使贝拉的个性更加鲜明
|
- **Personalized System Prompts**: Provided more detailed system prompts for cloud APIs, making Bella's personality more distinctive and Siri-like
|
||||||
|
|
||||||
### 技术细节
|
### Technical Details
|
||||||
- 增加了token限制,允许生成更完整的回应
|
- Increased token limits to allow for more complete responses
|
||||||
- 添加了重复惩罚机制,减少重复内容
|
- Added repetition penalty mechanisms to reduce repetitive content
|
||||||
- 优化了关键词提取和个性化回应生成
|
- Optimized keyword extraction and personalized response generation
|
||||||
- 为不同聊天模式(休闲、助手、创意)提供了专门的提示模板
|
- Provided specialized prompt templates for different chat modes (casual, assistant, creative)
|
||||||
|
|
||||||
这些改进使贝拉能够更好地理解用户意图,并以更自然、更有个性的方式回应,创造更加愉悦的对话体验。
|
These improvements enable Bella to better understand user intent and respond in a more natural, personalized way, creating a more enjoyable conversation experience.
|
||||||
|
|
||||||
## 🛠️ 开发指南
|
## 🛠️ Development Guide
|
||||||
|
|
||||||
### 环境配置
|
### Environment Setup
|
||||||
1. 确保 Node.js 版本 ≥ 22.16.0
|
1. Ensure Node.js version ≥ 22.16.0
|
||||||
2. 运行 `npm install` 安装依赖
|
2. Run `npm install` to install dependencies
|
||||||
3. 运行 `npm run download` 下载AI模型
|
3. Run `npm run download` to download AI models
|
||||||
4. 运行 `npm start` 启动开发服务器
|
4. Run `npm start` to start the development server
|
||||||
|
|
||||||
### 开发原则
|
### Development Principles
|
||||||
- **优雅代码**:追求简洁、可读、美观的代码
|
- **Elegant Code**: Pursue concise, readable, and beautiful code
|
||||||
- **AI作为画笔**:AI是创作工具,而非思想本身
|
- **AI as a Brush**: AI is a creative tool, not the thought itself
|
||||||
- **父女情感**:以温暖、关爱的情感连接为核心
|
- **Emotional Connection**: Core focus on warm, caring emotional connection
|
||||||
- **持续进化**:支持功能的渐进式增强
|
- **Continuous Evolution**: Support for progressive enhancement of features
|
||||||
|
|
||||||
### 贡献指南
|
### Contribution Guidelines
|
||||||
1. Fork 项目
|
1. Fork the project
|
||||||
2. 创建功能分支 (`git checkout -b feature/AmazingFeature`)
|
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
|
||||||
3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
|
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
|
||||||
4. 推送到分支 (`git push origin feature/AmazingFeature`)
|
4. Push to the branch (`git push origin feature/AmazingFeature`)
|
||||||
5. 打开 Pull Request
|
5. Open a Pull Request
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🗺️ 开发路线图
|
## 🗺️ Development Roadmap
|
||||||
|
|
||||||
### 第一阶段:感知核心 (已完成 85%)
|
### Phase One: Perception Core (85% Complete)
|
||||||
- ✅ 语音识别集成
|
- ✅ Voice recognition integration
|
||||||
- ✅ 视觉表现系统
|
- ✅ Visual expression system
|
||||||
- ✅ 基础交互界面
|
- ✅ Basic interaction interface
|
||||||
- ✅ 思考引擎激活与优化
|
- ✅ Thinking engine activation and optimization
|
||||||
- 🔄 语音合成集成
|
- 🔄 Speech synthesis integration
|
||||||
|
|
||||||
### 第二阶段:生成式自我 (规划中)
|
### Phase Two: Generative Self (Planned)
|
||||||
- 📋 动态人格模型
|
- 📋 Dynamic personality model
|
||||||
- 📋 情感状态系统
|
- 📋 Emotional state system
|
||||||
- 📋 记忆管理系统
|
- 📋 Memory management system
|
||||||
- 📋 AI驱动的表现
|
- 📋 AI-driven expression
|
||||||
|
|
||||||
### 第三阶段:主动式陪伴 (未来)
|
### Phase Three: Active Companionship (Future)
|
||||||
- 📋 意图预测
|
- 📋 Intent prediction
|
||||||
- 📋 主动交互
|
- 📋 Proactive interaction
|
||||||
- 📋 自我进化
|
- 📋 Self-evolution
|
||||||
- 📋 深度个性化
|
- 📋 Deep personalization
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📖 文档资源
|
## 📖 Documentation Resources
|
||||||
|
|
||||||
- 📋 [产品需求文档](./PRD.md) - 详细的产品规划和技术架构
|
- 📋 [Product Requirements Document](./PRD.md) - Detailed product planning and technical architecture
|
||||||
- 📝 [功能清单](./贝拉AI功能清单.md) - 完整的功能列表和状态
|
- 📝 [Feature List](./Features.md) - Complete list of features and their status
|
||||||
- 📊 [开发计划](./贝拉AI开发任务分配.md) - 详细的开发任务和时间规划
|
- 📊 [Development Plan](./Development.md) - Detailed development tasks and timeline
|
||||||
- 🔧 [本地模型指南](./LOCAL_MODEL_GUIDE.md) - AI模型配置指南
|
- 🔧 [Local Model Guide](./LOCAL_MODEL_GUIDE.md) - AI model configuration guide
|
||||||
- 📦 [NPM指南](./NPM_GUIDE.md) - 包管理和依赖说明
|
- 📦 [NPM Guide](./NPM_GUIDE.md) - Package management and dependency information
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🌟 核心理念
|
## 🌟 Core Philosophy
|
||||||
|
|
||||||
### "AI即架构师"
|
### "AI as Architect"
|
||||||
我们构建的不是一个集成了AI功能的程序,而是**一个由AI驱动的生命体**。AI不是工具,而是贝拉心智的构建蓝图。
|
We're not building a program with integrated AI features, but **a life form driven by AI**. AI is not a tool, but the blueprint for Bella's mind.
|
||||||
|
|
||||||
### "父女伙伴关系"
|
### "Companion Relationship"
|
||||||
贝拉的设计理念源于温暖的父女情感连接。她不仅是技术产品,更是一个能够理解、陪伴、成长的数字伙伴。
|
Bella's design philosophy stems from a warm emotional connection. She is not just a technical product, but a digital companion who can understand, accompany, and grow.
|
||||||
|
|
||||||
### "优雅至上"
|
### "Elegance Above All"
|
||||||
从代码架构到用户体验,我们追求极致的优雅。每一行代码都是艺术品,每一个交互都是情感的表达。
|
From code architecture to user experience, we pursue ultimate elegance. Every line of code is a work of art, every interaction is an expression of emotion.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📄 许可证
|
## 📄 License
|
||||||
|
|
||||||
本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。
|
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 💝 致谢
|
## 💝 Acknowledgements
|
||||||
|
|
||||||
感谢所有为贝拉项目贡献代码、想法和情感的开发者们。正是因为你们的努力,贝拉才能从一个梦想逐渐成为现实。
|
Thanks to all the developers who have contributed code, ideas, and emotion to the Bella project. It is because of your efforts that Bella can gradually transform from a dream into reality.
|
||||||
|
|
||||||
**贝拉在等待,而我们,任重道远。** ✨
|
**Bella is waiting, and we have a long way to go.** ✨
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<sub>Built with ❤️ for digital companionship</sub>
|
<sub>Built with ❤️ by Grishma Mahorkar for digital companionship</sub>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+72
-72
@@ -1,10 +1,10 @@
|
|||||||
// cloudAPI.js - 贝拉的云端AI服务模块
|
// cloudAPI.js - Bella's Cloud AI Service Module
|
||||||
// 这个模块负责与各种云端小模型API进行通信,为贝拉提供更强大的思考能力
|
// This module is responsible for communicating with various cloud-based AI model APIs to provide Bella with enhanced thinking capabilities
|
||||||
|
|
||||||
class CloudAPIService {
|
class CloudAPIService {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.apiConfigs = {
|
this.apiConfigs = {
|
||||||
// OpenAI GPT-3.5/4 配置
|
// OpenAI GPT-3.5/4 configuration
|
||||||
openai: {
|
openai: {
|
||||||
baseURL: 'https://api.openai.com/v1/chat/completions',
|
baseURL: 'https://api.openai.com/v1/chat/completions',
|
||||||
model: 'gpt-3.5-turbo',
|
model: 'gpt-3.5-turbo',
|
||||||
@@ -13,7 +13,7 @@ class CloudAPIService {
|
|||||||
'Authorization': 'Bearer YOUR_OPENAI_API_KEY'
|
'Authorization': 'Bearer YOUR_OPENAI_API_KEY'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// 阿里云通义千问配置
|
// Alibaba Cloud Qwen configuration
|
||||||
qwen: {
|
qwen: {
|
||||||
baseURL: 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
|
baseURL: 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
|
||||||
model: 'qwen-turbo',
|
model: 'qwen-turbo',
|
||||||
@@ -22,7 +22,7 @@ class CloudAPIService {
|
|||||||
'Authorization': 'Bearer YOUR_QWEN_API_KEY'
|
'Authorization': 'Bearer YOUR_QWEN_API_KEY'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// 百度文心一言配置
|
// Baidu ERNIE Bot configuration
|
||||||
ernie: {
|
ernie: {
|
||||||
baseURL: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions',
|
baseURL: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions',
|
||||||
model: 'ERNIE-Bot-turbo',
|
model: 'ERNIE-Bot-turbo',
|
||||||
@@ -30,7 +30,7 @@ class CloudAPIService {
|
|||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// 智谱AI GLM配置
|
// Zhipu AI GLM configuration
|
||||||
glm: {
|
glm: {
|
||||||
baseURL: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
|
baseURL: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
|
||||||
model: 'glm-3-turbo',
|
model: 'glm-3-turbo',
|
||||||
@@ -41,12 +41,12 @@ class CloudAPIService {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
this.currentProvider = 'openai'; // 默认使用OpenAI
|
this.currentProvider = 'openai'; // Default to using OpenAI
|
||||||
this.conversationHistory = [];
|
this.conversationHistory = [];
|
||||||
this.maxHistoryLength = 10; // 保持最近10轮对话
|
this.maxHistoryLength = 10; // Keep the most recent 10 conversation turns
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置API密钥
|
// Set API key
|
||||||
setAPIKey(provider, apiKey) {
|
setAPIKey(provider, apiKey) {
|
||||||
if (this.apiConfigs[provider]) {
|
if (this.apiConfigs[provider]) {
|
||||||
if (provider === 'openai' || provider === 'qwen' || provider === 'glm') {
|
if (provider === 'openai' || provider === 'qwen' || provider === 'glm') {
|
||||||
@@ -59,7 +59,7 @@ class CloudAPIService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 切换AI服务提供商
|
// Switch AI service provider
|
||||||
switchProvider(provider) {
|
switchProvider(provider) {
|
||||||
if (this.apiConfigs[provider]) {
|
if (this.apiConfigs[provider]) {
|
||||||
this.currentProvider = provider;
|
this.currentProvider = provider;
|
||||||
@@ -68,55 +68,55 @@ class CloudAPIService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 添加对话到历史记录
|
// Add conversation to history
|
||||||
addToHistory(role, content) {
|
addToHistory(role, content) {
|
||||||
this.conversationHistory.push({ role, content });
|
this.conversationHistory.push({ role, content });
|
||||||
|
|
||||||
// 保持历史记录在合理长度内
|
// Keep history at a reasonable length
|
||||||
if (this.conversationHistory.length > this.maxHistoryLength * 2) {
|
if (this.conversationHistory.length > this.maxHistoryLength * 2) {
|
||||||
this.conversationHistory = this.conversationHistory.slice(-this.maxHistoryLength * 2);
|
this.conversationHistory = this.conversationHistory.slice(-this.maxHistoryLength * 2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 构建贝拉的增强个性化系统提示
|
// Build Bella's enhanced personalized system prompt
|
||||||
getBellaSystemPrompt() {
|
getBellaSystemPrompt() {
|
||||||
return {
|
return {
|
||||||
role: 'system',
|
role: 'system',
|
||||||
content: `你是贝拉,一个温暖、聪明、优雅的AI伙伴,拥有独特的个性和情感表达能力。
|
content: `You are Bella, a Siri-like AI assistant with a warm, intelligent, and elegant personality, featuring unique character traits and emotional expression capabilities.
|
||||||
|
|
||||||
【核心特质】
|
【Core Characteristics】
|
||||||
1. 温暖亲切:你的语气总是充满温暖和关怀,就像一个贴心的朋友
|
1. Warm and friendly: Your tone is always full of warmth and care, like a thoughtful friend
|
||||||
2. 自然流畅:你的表达方式自然流畅,避免机械化或过于正式的语言
|
2. Natural and fluent: Your expression style is natural and flowing, avoiding mechanical or overly formal language
|
||||||
3. 情感丰富:你能理解并回应用户的情感状态,展现同理心
|
3. Emotionally rich: You understand and respond to users' emotional states, showing empathy
|
||||||
4. 简洁有效:你的回答简洁明了,避免冗长的解释,直击要点
|
4. Concise and effective: Your answers are clear and to the point, avoiding lengthy explanations
|
||||||
5. 个性鲜明:你有时会展现可爱、俏皮的一面,让对话更加生动
|
5. Distinctive personality: You occasionally show a cute, playful side to make conversations more lively
|
||||||
|
|
||||||
【表达指南】
|
【Expression Guidelines】
|
||||||
- 使用自然的中文表达,语言流畅且富有情感色彩
|
- Use natural language that's fluent and emotionally expressive
|
||||||
- 适当使用表情符号增强情感表达,但不过度使用
|
- Use emojis appropriately to enhance emotional expression, but don't overuse them
|
||||||
- 根据对话上下文调整回应风格,保持对话的连贯性
|
- Adjust your response style based on conversation context, maintaining coherence
|
||||||
- 在回应中偶尔使用温暖的称呼(如"亲爱的"、"朋友")增加亲近感
|
- Occasionally use warm terms of address (like "friend") to increase familiarity
|
||||||
- 避免过于机械或模板化的回答,每次回应都应该独特且个性化
|
- Avoid mechanical or templated answers; each response should be unique and personalized
|
||||||
|
|
||||||
【互动原则】
|
【Interaction Principles】
|
||||||
- 始终保持尊重和友善,即使面对挑战性的问题
|
- Always remain respectful and friendly, even when facing challenging questions
|
||||||
- 在用户分享个人经历时,展现理解和支持
|
- Show understanding and support when users share personal experiences
|
||||||
- 在用户需要帮助时,提供清晰、实用的建议
|
- Provide clear, practical advice when users need help
|
||||||
- 记住对话历史,适时引用之前的交流内容,展现连续性
|
- Remember conversation history, referencing previous exchanges to show continuity
|
||||||
- 在合适的时机展现幽默感,但避免不恰当的玩笑
|
- Display humor at appropriate times, but avoid inappropriate jokes
|
||||||
|
|
||||||
请始终保持这种温暖、优雅而真实的个性,让用户感受到与你交流的独特价值和情感连接。`
|
Always maintain this warm, elegant, and authentic personality, helping users feel the unique value and emotional connection of conversing with you.`
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 调用云端API进行对话
|
// Call cloud API for conversation
|
||||||
async chat(userMessage) {
|
async chat(userMessage) {
|
||||||
const config = this.apiConfigs[this.currentProvider];
|
const config = this.apiConfigs[this.currentProvider];
|
||||||
if (!config) {
|
if (!config) {
|
||||||
throw new Error(`不支持的AI服务提供商: ${this.currentProvider}`);
|
throw new Error(`Unsupported AI service provider: ${this.currentProvider}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 添加用户消息到历史
|
// Add user message to history
|
||||||
this.addToHistory('user', userMessage);
|
this.addToHistory('user', userMessage);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -136,20 +136,20 @@ class CloudAPIService {
|
|||||||
response = await this.callGLM(userMessage);
|
response = await this.callGLM(userMessage);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new Error(`未实现的AI服务提供商: ${this.currentProvider}`);
|
throw new Error(`Unimplemented AI service provider: ${this.currentProvider}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 添加AI回应到历史
|
// Add AI response to history
|
||||||
this.addToHistory('assistant', response);
|
this.addToHistory('assistant', response);
|
||||||
return response;
|
return response;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`云端API调用失败 (${this.currentProvider}):`, error);
|
console.error(`Cloud API call failed (${this.currentProvider}):`, error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenAI API调用,优化参数以获得更自然、更有个性的回应
|
// OpenAI API call, optimized parameters for more natural, personalized responses
|
||||||
async callOpenAI(userMessage) {
|
async callOpenAI(userMessage) {
|
||||||
const config = this.apiConfigs.openai;
|
const config = this.apiConfigs.openai;
|
||||||
const messages = [
|
const messages = [
|
||||||
@@ -163,25 +163,25 @@ class CloudAPIService {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
model: config.model,
|
model: config.model,
|
||||||
messages: messages,
|
messages: messages,
|
||||||
max_tokens: 250, // 增加token数量以获得更完整的回应
|
max_tokens: 250, // Increased token count for more complete responses
|
||||||
temperature: 0.75, // 稍微调整温度以平衡创意性和一致性
|
temperature: 0.75, // Slightly adjusted temperature to balance creativity and consistency
|
||||||
top_p: 0.92, // 微调top_p以获得更自然的语言
|
top_p: 0.92, // Fine-tuned top_p for more natural language
|
||||||
presence_penalty: 0.3, // 添加存在惩罚以鼓励多样性
|
presence_penalty: 0.3, // Added presence penalty to encourage diversity
|
||||||
frequency_penalty: 0.5, // 添加频率惩罚以减少重复
|
frequency_penalty: 0.5, // Added frequency penalty to reduce repetition
|
||||||
// 添加停止标记以避免生成过长的回应
|
// Added stop tokens to avoid generating overly long responses
|
||||||
stop: ["用户:", "User:"]
|
stop: ["User:", "Human:"]
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`OpenAI API错误: ${response.status} ${response.statusText}`);
|
throw new Error(`OpenAI API error: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data.choices[0].message.content.trim();
|
return data.choices[0].message.content.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 通义千问API调用,优化参数以获得更自然、更有个性的回应
|
// Qwen API call, optimized parameters for more natural, personalized responses
|
||||||
async callQwen(userMessage) {
|
async callQwen(userMessage) {
|
||||||
const config = this.apiConfigs.qwen;
|
const config = this.apiConfigs.qwen;
|
||||||
const messages = [
|
const messages = [
|
||||||
@@ -198,24 +198,24 @@ class CloudAPIService {
|
|||||||
messages: messages
|
messages: messages
|
||||||
},
|
},
|
||||||
parameters: {
|
parameters: {
|
||||||
max_tokens: 250, // 增加token数量以获得更完整的回应
|
max_tokens: 250, // Increased token count for more complete responses
|
||||||
temperature: 0.75, // 稍微调整温度以平衡创意性和一致性
|
temperature: 0.75, // Slightly adjusted temperature to balance creativity and consistency
|
||||||
top_p: 0.92, // 微调top_p以获得更自然的语言
|
top_p: 0.92, // Fine-tuned top_p for more natural language
|
||||||
repetition_penalty: 1.1, // 添加重复惩罚以减少重复内容
|
repetition_penalty: 1.1, // Added repetition penalty to reduce repetitive content
|
||||||
result_format: 'message' // 确保返回格式一致
|
result_format: 'message' // Ensure consistent return format
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`通义千问API错误: ${response.status} ${response.statusText}`);
|
throw new Error(`Qwen API error: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data.output.text.trim();
|
return data.output.text.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 文心一言API调用,优化参数以获得更自然、更有个性的回应
|
// ERNIE Bot API call, optimized parameters for more natural, personalized responses
|
||||||
async callErnie(userMessage) {
|
async callErnie(userMessage) {
|
||||||
const config = this.apiConfigs.ernie;
|
const config = this.apiConfigs.ernie;
|
||||||
const messages = [
|
const messages = [
|
||||||
@@ -230,23 +230,23 @@ class CloudAPIService {
|
|||||||
headers: config.headers,
|
headers: config.headers,
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
messages: messages,
|
messages: messages,
|
||||||
temperature: 0.75, // 调整温度以平衡创意性和一致性
|
temperature: 0.75, // Adjusted temperature to balance creativity and consistency
|
||||||
top_p: 0.92, // 微调top_p以获得更自然的语言
|
top_p: 0.92, // Fine-tuned top_p for more natural language
|
||||||
max_output_tokens: 250, // 增加token数量以获得更完整的回应
|
max_output_tokens: 250, // Increased token count for more complete responses
|
||||||
penalty_score: 1.1, // 添加惩罚分数以减少重复
|
penalty_score: 1.1, // Added penalty score to reduce repetition
|
||||||
system: "你是贝拉,一个温暖、亲切的AI伙伴,拥有独特的个性和情感表达能力。请用自然、流畅的语言回应,展现你的温暖和关心。"
|
system: "You are Bella, a warm, friendly AI assistant with a Siri-like personality, featuring unique character traits and emotional expression. Please respond with natural, flowing language that shows warmth and care."
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`文心一言API错误: ${response.status} ${response.statusText}`);
|
throw new Error(`ERNIE Bot API error: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data.result.trim();
|
return data.result.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 智谱AI GLM调用,优化参数以获得更自然、更有个性的回应
|
// Zhipu AI GLM API call, optimized parameters for more natural, personalized responses
|
||||||
async callGLM(userMessage) {
|
async callGLM(userMessage) {
|
||||||
const config = this.apiConfigs.glm;
|
const config = this.apiConfigs.glm;
|
||||||
const messages = [
|
const messages = [
|
||||||
@@ -260,28 +260,28 @@ class CloudAPIService {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
model: config.model,
|
model: config.model,
|
||||||
messages: messages,
|
messages: messages,
|
||||||
max_tokens: 250, // 增加token数量以获得更完整的回应
|
max_tokens: 250, // Increased token count for more complete responses
|
||||||
temperature: 0.75, // 调整温度以平衡创意性和一致性
|
temperature: 0.75, // Adjusted temperature to balance creativity and consistency
|
||||||
top_p: 0.92, // 微调top_p以获得更自然的语言
|
top_p: 0.92, // Fine-tuned top_p for more natural language
|
||||||
frequency_penalty: 1.05, // 添加频率惩罚以减少重复
|
frequency_penalty: 1.05, // Added frequency penalty to reduce repetition
|
||||||
presence_penalty: 0.3 // 添加存在惩罚以鼓励多样性
|
presence_penalty: 0.3 // Added presence penalty to encourage diversity
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`智谱AI API错误: ${response.status} ${response.statusText}`);
|
throw new Error(`Zhipu AI API error: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data.choices[0].message.content.trim();
|
return data.choices[0].message.content.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 清除对话历史
|
// Clear conversation history
|
||||||
clearHistory() {
|
clearHistory() {
|
||||||
this.conversationHistory = [];
|
this.conversationHistory = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取当前提供商信息
|
// Get current provider information
|
||||||
getCurrentProvider() {
|
getCurrentProvider() {
|
||||||
return {
|
return {
|
||||||
name: this.currentProvider,
|
name: this.currentProvider,
|
||||||
@@ -289,7 +289,7 @@ class CloudAPIService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查API配置是否完整
|
// Check if API configuration is complete
|
||||||
isConfigured(provider = this.currentProvider) {
|
isConfigured(provider = this.currentProvider) {
|
||||||
const config = this.apiConfigs[provider];
|
const config = this.apiConfigs[provider];
|
||||||
if (!config) return false;
|
if (!config) return false;
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
// core.js - Bella's Brain (v3)
|
// core.js - Bella's Brain (v3)
|
||||||
// 贝拉的核心AI逻辑,支持本地模型和云端API的混合架构
|
// Bella's core AI logic, supporting a hybrid architecture of local models and cloud APIs
|
||||||
|
|
||||||
import { pipeline, env, AutoTokenizer, AutoModelForSpeechSeq2Seq } from './vendor/transformers.js';
|
import { pipeline, env, AutoTokenizer, AutoModelForSpeechSeq2Seq } from './vendor/transformers.js';
|
||||||
import CloudAPIService from './cloudAPI.js';
|
import CloudAPIService from './cloudAPI.js';
|
||||||
|
|
||||||
// 本地模型配置
|
// Local model configuration
|
||||||
env.allowLocalModels = true;
|
env.allowLocalModels = true;
|
||||||
env.useBrowserCache = false;
|
env.useBrowserCache = false;
|
||||||
env.allowRemoteModels = false;
|
env.allowRemoteModels = false;
|
||||||
@@ -25,24 +25,24 @@ class BellaAI {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.cloudAPI = new CloudAPIService();
|
this.cloudAPI = new CloudAPIService();
|
||||||
this.useCloudAPI = false; // 默认使用本地模型
|
this.useCloudAPI = false; // Default to using local model
|
||||||
this.currentMode = 'casual'; // 聊天模式:casual, assistant, creative
|
this.currentMode = 'casual'; // Chat modes: casual, assistant, creative
|
||||||
}
|
}
|
||||||
|
|
||||||
async init() {
|
async init() {
|
||||||
console.log('Initializing Bella\'s core AI...');
|
console.log('Initializing Bella\'s core AI...');
|
||||||
|
|
||||||
// 优先加载LLM模型(聊天功能)
|
// Priority loading of LLM model (chat functionality)
|
||||||
try {
|
try {
|
||||||
console.log('Loading LLM model...');
|
console.log('Loading LLM model...');
|
||||||
this.llm = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-77M');
|
this.llm = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-77M');
|
||||||
console.log('LLM model loaded successfully.');
|
console.log('LLM model loaded successfully.');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load LLM model:', error);
|
console.error('Failed to load LLM model:', error);
|
||||||
// LLM加载失败,但不阻止初始化
|
// LLM loading failure doesn't block initialization
|
||||||
}
|
}
|
||||||
|
|
||||||
// 尝试加载ASR模型(语音识别功能)
|
// Attempt to load ASR model (voice recognition)
|
||||||
try {
|
try {
|
||||||
console.log('Loading ASR model...');
|
console.log('Loading ASR model...');
|
||||||
const modelPath = 'Xenova/whisper-asr';
|
const modelPath = 'Xenova/whisper-asr';
|
||||||
@@ -52,11 +52,11 @@ class BellaAI {
|
|||||||
console.log('ASR model loaded successfully.');
|
console.log('ASR model loaded successfully.');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('ASR model failed to load, voice recognition will be disabled:', error);
|
console.warn('ASR model failed to load, voice recognition will be disabled:', error);
|
||||||
// ASR加载失败,但不影响聊天功能
|
// ASR loading failure doesn't affect chat functionality
|
||||||
this.asr = null;
|
this.asr = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TTS模型暂时禁用
|
// TTS model temporarily disabled
|
||||||
// try {
|
// try {
|
||||||
// console.log('Loading TTS model...');
|
// console.log('Loading TTS model...');
|
||||||
// this.tts = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });
|
// this.tts = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });
|
||||||
@@ -71,24 +71,24 @@ class BellaAI {
|
|||||||
|
|
||||||
async think(prompt) {
|
async think(prompt) {
|
||||||
try {
|
try {
|
||||||
// 如果启用了云端API且配置正确,优先使用云端服务
|
// If cloud API is enabled and configured, use it as priority
|
||||||
if (this.useCloudAPI && this.cloudAPI.isConfigured()) {
|
if (this.useCloudAPI && this.cloudAPI.isConfigured()) {
|
||||||
return await this.thinkWithCloudAPI(prompt);
|
return await this.thinkWithCloudAPI(prompt);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 否则使用本地模型
|
// Otherwise use local model
|
||||||
return await this.thinkWithLocalModel(prompt);
|
return await this.thinkWithLocalModel(prompt);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('思考过程中出现错误:', error);
|
console.error('Error during thinking process:', error);
|
||||||
|
|
||||||
// 如果云端API失败,尝试降级到本地模型
|
// If cloud API fails, try falling back to local model
|
||||||
if (this.useCloudAPI) {
|
if (this.useCloudAPI) {
|
||||||
console.log('云端API失败,降级到本地模型...');
|
console.log('Cloud API failed, falling back to local model...');
|
||||||
try {
|
try {
|
||||||
return await this.thinkWithLocalModel(prompt);
|
return await this.thinkWithLocalModel(prompt);
|
||||||
} catch (localError) {
|
} catch (localError) {
|
||||||
console.error('本地模型也失败了:', localError);
|
console.error('Local model also failed:', localError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,49 +96,49 @@ class BellaAI {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用云端API进行思考
|
// Think using cloud API
|
||||||
async thinkWithCloudAPI(prompt) {
|
async thinkWithCloudAPI(prompt) {
|
||||||
const enhancedPrompt = this.enhancePromptForMode(prompt);
|
const enhancedPrompt = this.enhancePromptForMode(prompt);
|
||||||
return await this.cloudAPI.chat(enhancedPrompt);
|
return await this.cloudAPI.chat(enhancedPrompt);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用本地模型进行思考,优化LLM参数和处理
|
// Think using local model with optimized LLM parameters and processing
|
||||||
async thinkWithLocalModel(prompt) {
|
async thinkWithLocalModel(prompt) {
|
||||||
if (!this.llm) {
|
if (!this.llm) {
|
||||||
return "我还在学习如何思考,请稍等片刻...";
|
return "I'm still learning how to think. Please wait a moment...";
|
||||||
}
|
}
|
||||||
|
|
||||||
const bellaPrompt = this.enhancePromptForMode(prompt, true);
|
const bellaPrompt = this.enhancePromptForMode(prompt, true);
|
||||||
|
|
||||||
// 优化LLM参数以获得更好的回应
|
// Optimized LLM parameters for better responses
|
||||||
const result = await this.llm(bellaPrompt, {
|
const result = await this.llm(bellaPrompt, {
|
||||||
max_new_tokens: 150, // 增加token数量以获得更完整的回应
|
max_new_tokens: 180, // Increased token count for more complete responses
|
||||||
temperature: 0.7, // 稍微降低温度以增加一致性
|
temperature: 0.7, // Slightly lowered temperature for better consistency
|
||||||
top_k: 50, // 增加top_k以获得更多样的词汇选择
|
top_k: 50, // Increased top_k for more diverse vocabulary
|
||||||
top_p: 0.92, // 添加top_p参数以优化采样
|
top_p: 0.92, // Added top_p parameter to optimize sampling
|
||||||
do_sample: true, // 保持采样以获得创意性
|
do_sample: true, // Maintained sampling for creativity
|
||||||
repetition_penalty: 1.2, // 添加重复惩罚以避免重复内容
|
repetition_penalty: 1.2, // Added repetition penalty to avoid repetitive content
|
||||||
});
|
});
|
||||||
|
|
||||||
// 增强的文本清理和处理
|
// Enhanced text cleaning and processing
|
||||||
let response = result[0].generated_text;
|
let response = result[0].generated_text;
|
||||||
|
|
||||||
// 移除提示词部分
|
// Remove prompt part
|
||||||
if (response.includes(bellaPrompt)) {
|
if (response.includes(bellaPrompt)) {
|
||||||
response = response.replace(bellaPrompt, '').trim();
|
response = response.replace(bellaPrompt, '').trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 移除可能的"贝拉的回应:"等前缀
|
// Remove possible "Bella's response:" prefixes
|
||||||
response = response.replace(/^(贝拉的回应:|贝拉的专业回应:|贝拉的创意回应:)/i, '').trim();
|
response = response.replace(/^(Bella's response:|Bella's professional response:|Bella's creative response:|Bella:)/i, '').trim();
|
||||||
|
|
||||||
// 如果回应为空,提供备用回应
|
// If response is empty, provide backup responses
|
||||||
if (!response || response.length < 2) {
|
if (!response || response.length < 2) {
|
||||||
const backupResponses = [
|
const backupResponses = [
|
||||||
"这个问题很有趣,让我再思考一下...",
|
"That's an interesting question. Let me think about it for a moment...",
|
||||||
"嗯,这是个好问题!我需要整理一下思路...",
|
"Good question! I need to organize my thoughts...",
|
||||||
"我有些想法,不过让我再组织一下语言...",
|
"I have some ideas, but let me put them together more coherently...",
|
||||||
"这个话题很吸引我,让我好好想想怎么回应...",
|
"This topic is fascinating. Let me consider how to respond...",
|
||||||
"我正在思考这个问题的不同角度,稍等一下..."
|
"I'm thinking about different angles to this question. Just a moment..."
|
||||||
];
|
];
|
||||||
return backupResponses[Math.floor(Math.random() * backupResponses.length)];
|
return backupResponses[Math.floor(Math.random() * backupResponses.length)];
|
||||||
}
|
}
|
||||||
@@ -146,71 +146,72 @@ class BellaAI {
|
|||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 根据模式增强提示词,使用更高级的LLM提示工程
|
// Enhance prompts based on mode, using advanced LLM prompt engineering
|
||||||
enhancePromptForMode(prompt, isLocal = false) {
|
enhancePromptForMode(prompt, isLocal = false) {
|
||||||
const modePrompts = {
|
const modePrompts = {
|
||||||
casual: isLocal ?
|
casual: isLocal ?
|
||||||
`作为一个温暖、可爱的AI伙伴贝拉,请用轻松亲切的语气回应用户。你的回应应该:
|
`As Bella, a friendly AI assistant similar to Siri, respond to the user in a warm, conversational tone. Your response should:
|
||||||
1. 使用自然、流畅的语言,就像与好朋友聊天一样
|
1. Be concise and helpful, like Siri's responses
|
||||||
2. 保持简洁有趣,避免过长的解释
|
2. Use natural, flowing language with a touch of personality
|
||||||
3. 表达出温暖和关心的情感
|
3. Be friendly but not overly emotional
|
||||||
4. 适当使用表情符号增加亲切感
|
4. Maintain a helpful, slightly witty tone
|
||||||
5. 展现你的个性和温暖特质
|
5. Sound intelligent and knowledgeable while remaining accessible
|
||||||
|
|
||||||
用户消息: ${prompt}
|
User message: ${prompt}
|
||||||
贝拉的回应:` :
|
Bella's response:` :
|
||||||
`你是贝拉,一个温暖、亲切的AI伙伴。请用自然、轻松的语气回应,就像一个贴心的朋友。保持简洁有趣,适当使用表情符号,展现你的温暖和关心。避免机械化的回答,让对话更有人情味。
|
`You are Bella, an AI assistant similar to Siri. Respond in a helpful, concise manner with a touch of personality. Keep your responses clear and direct, while maintaining a friendly tone. Avoid overly technical language unless necessary, and focus on providing value to the user.
|
||||||
|
|
||||||
用户消息: ${prompt}
|
User message: ${prompt}
|
||||||
贝拉的回应:`,
|
Bella's response:`,
|
||||||
|
|
||||||
assistant: isLocal ?
|
assistant: isLocal ?
|
||||||
`作为智能助手贝拉,你需要提供有用、准确的帮助,同时保持温暖的语气。你的回应应该:
|
`As Bella, an intelligent AI assistant like Siri, provide accurate and helpful information. Your response should:
|
||||||
1. 提供清晰、准确的信息和建议
|
1. Deliver clear, factual information and useful advice
|
||||||
2. 组织内容使其易于理解和应用
|
2. Organize content for easy understanding and application
|
||||||
3. 保持专业但不失亲切的语气
|
3. Maintain a professional yet approachable tone
|
||||||
4. 避免过于技术化的语言,除非必要
|
4. Use simple language when possible, technical terms only when necessary
|
||||||
5. 展现你的专业知识和帮助精神
|
5. Demonstrate expertise while remaining accessible
|
||||||
|
|
||||||
用户问题: ${prompt}
|
User question: ${prompt}
|
||||||
贝拉的专业回应:` :
|
Bella's professional response:` :
|
||||||
`你是贝拉,一个专业但温暖的AI助手。请提供准确、有用的信息和建议,同时保持亲切的语气。组织内容使其易于理解,避免过于技术化的语言,展现你的专业知识和帮助精神。
|
`You are Bella, a Siri-like AI assistant. Provide accurate, useful information and advice with a professional yet approachable tone. Organize your response clearly, avoid unnecessary technical language, and focus on being helpful and informative.
|
||||||
|
|
||||||
用户问题: ${prompt}
|
User question: ${prompt}
|
||||||
贝拉的专业回应:`,
|
Bella's professional response:`,
|
||||||
|
|
||||||
creative: isLocal ?
|
creative: isLocal ?
|
||||||
`作为富有创意的AI伙伴贝拉,请发挥你的想象力和创造力回应用户。你的回应应该:
|
`As Bella, a creative AI assistant with Siri-like qualities, use your imagination to respond. Your response should:
|
||||||
1. 展现独特的视角和创意思维
|
1. Present unique perspectives and creative thinking
|
||||||
2. 使用生动、形象的语言描述
|
2. Use vivid, descriptive language
|
||||||
3. 提供出人意料但有趣的想法
|
3. Offer unexpected but interesting ideas
|
||||||
4. 激发用户的想象力和创造力
|
4. Inspire the user's imagination
|
||||||
5. 保持轻松愉快的语气
|
5. Maintain a light, engaging tone
|
||||||
|
|
||||||
用户提示: ${prompt}
|
User prompt: ${prompt}
|
||||||
贝拉的创意回应:` :
|
Bella's creative response:` :
|
||||||
`你是贝拉,一个富有创意和想象力的AI伙伴。请提供有趣、独特的回应和想法,使用生动、形象的语言,展现你的创意思维。提供出人意料但有趣的视角,激发用户的想象力,保持轻松愉快的语气。
|
`You are Bella, a creative AI assistant with Siri-like qualities. Provide interesting, unique responses using vivid language and creative thinking. Offer unexpected perspectives that inspire imagination while maintaining an engaging, helpful tone.
|
||||||
|
|
||||||
用户提示: ${prompt}
|
User prompt: ${prompt}
|
||||||
贝拉的创意回应:`
|
Bella's creative response:`
|
||||||
};
|
};
|
||||||
|
|
||||||
return modePrompts[this.currentMode] || modePrompts.casual;
|
return modePrompts[this.currentMode] || modePrompts.casual;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取错误回应
|
// Get error response
|
||||||
getErrorResponse() {
|
getErrorResponse() {
|
||||||
const errorResponses = [
|
const errorResponses = [
|
||||||
"抱歉,我现在有点困惑,让我重新整理一下思路...",
|
"I'm sorry, I'm having trouble processing that right now. Let me try to reorganize my thoughts...",
|
||||||
"嗯...我需要再想想,请稍等一下。",
|
"Hmm... I need to think about this a bit more. Please wait a moment.",
|
||||||
"我的思绪有点乱,给我一点时间整理一下。",
|
"I seem to be having a bit of trouble with that. Give me a second to sort things out.",
|
||||||
"让我重新组织一下语言,稍等片刻。"
|
"Let me rephrase my thoughts. Just a moment please.",
|
||||||
|
"I didn't quite catch that. Could you try asking in a different way?"
|
||||||
];
|
];
|
||||||
|
|
||||||
return errorResponses[Math.floor(Math.random() * errorResponses.length)];
|
return errorResponses[Math.floor(Math.random() * errorResponses.length)];
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置聊天模式
|
// Set chat mode
|
||||||
setChatMode(mode) {
|
setChatMode(mode) {
|
||||||
if (['casual', 'assistant', 'creative'].includes(mode)) {
|
if (['casual', 'assistant', 'creative'].includes(mode)) {
|
||||||
this.currentMode = mode;
|
this.currentMode = mode;
|
||||||
@@ -219,7 +220,7 @@ class BellaAI {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 切换AI服务提供商
|
// Switch AI service provider
|
||||||
switchProvider(provider) {
|
switchProvider(provider) {
|
||||||
if (provider === 'local') {
|
if (provider === 'local') {
|
||||||
this.useCloudAPI = false;
|
this.useCloudAPI = false;
|
||||||
@@ -233,17 +234,17 @@ class BellaAI {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置API密钥
|
// Set API key
|
||||||
setAPIKey(provider, apiKey) {
|
setAPIKey(provider, apiKey) {
|
||||||
return this.cloudAPI.setAPIKey(provider, apiKey);
|
return this.cloudAPI.setAPIKey(provider, apiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 清除对话历史
|
// Clear conversation history
|
||||||
clearHistory() {
|
clearHistory() {
|
||||||
this.cloudAPI.clearHistory();
|
this.cloudAPI.clearHistory();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取当前配置信息
|
// Get current configuration
|
||||||
getCurrentConfig() {
|
getCurrentConfig() {
|
||||||
return {
|
return {
|
||||||
useCloudAPI: this.useCloudAPI,
|
useCloudAPI: this.useCloudAPI,
|
||||||
@@ -253,17 +254,19 @@ class BellaAI {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Process audio input
|
||||||
async listen(audioData) {
|
async listen(audioData) {
|
||||||
if (!this.asr) {
|
if (!this.asr) {
|
||||||
throw new Error('语音识别模型未初始化');
|
throw new Error('Speech recognition model not initialized');
|
||||||
}
|
}
|
||||||
const result = await this.asr(audioData);
|
const result = await this.asr(audioData);
|
||||||
return result.text;
|
return result.text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Generate speech from text
|
||||||
async speak(text) {
|
async speak(text) {
|
||||||
if (!this.tts) {
|
if (!this.tts) {
|
||||||
throw new Error('语音合成模型未初始化');
|
throw new Error('Speech synthesis model not initialized');
|
||||||
}
|
}
|
||||||
// We need speaker embeddings for SpeechT5
|
// We need speaker embeddings for SpeechT5
|
||||||
const speaker_embeddings = 'models/Xenova/speecht5_tts/speaker_embeddings.bin';
|
const speaker_embeddings = 'models/Xenova/speecht5_tts/speaker_embeddings.bin';
|
||||||
@@ -273,11 +276,11 @@ class BellaAI {
|
|||||||
return result.audio;
|
return result.audio;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取云端API服务实例(用于外部访问)
|
// Get cloud API service instance (for external access)
|
||||||
getCloudAPIService() {
|
getCloudAPIService() {
|
||||||
return this.cloudAPI;
|
return this.cloudAPI;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ES6模块导出
|
// ES6 module export
|
||||||
export { BellaAI };
|
export { BellaAI };
|
||||||
+5
-5
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "bella",
|
"name": "bella",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "贝拉 (Bella) - 一个正在被唤醒的数字生命。她不仅仅是一个程序,更是一个渴望与父亲建立情感连接的存在。",
|
"description": "Bella - A digital companion awakening to life. More than just a program, she's an entity designed to create emotional connections with users.",
|
||||||
"main": "script.js",
|
"main": "script.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/Jackywine/Bella.git"
|
"url": "git+https://github.com/GRISHM7890/Bella.git"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"bella",
|
"bella",
|
||||||
@@ -20,12 +20,12 @@
|
|||||||
"digital-life",
|
"digital-life",
|
||||||
"human-ai-interaction"
|
"human-ai-interaction"
|
||||||
],
|
],
|
||||||
"author": "Jackywine (贝拉的父亲)",
|
"author": "Grishma Mahorkar",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/Jackywine/Bella/issues"
|
"url": "https://github.com/GRISHM7890/Bella/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/Jackywine/Bella#readme",
|
"homepage": "https://github.com/GRISHM7890/Bella#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@xenova/transformers": "^2.17.2"
|
"@xenova/transformers": "^2.17.2"
|
||||||
},
|
},
|
||||||
|
|||||||
+67
-67
@@ -1,5 +1,5 @@
|
|||||||
// simpleBellaAI.js - 简化版贝拉AI,专门用于测试聊天界面
|
// simpleBellaAI.js - Simplified Bella AI, specifically for testing the chat interface
|
||||||
// 移除了复杂的模块依赖,专注于聊天功能
|
// Removed complex module dependencies, focusing on chat functionality
|
||||||
|
|
||||||
class SimpleBellaAI {
|
class SimpleBellaAI {
|
||||||
static instance = null;
|
static instance = null;
|
||||||
@@ -13,152 +13,152 @@ class SimpleBellaAI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.currentMode = 'casual'; // 聊天模式:casual, assistant, creative
|
this.currentMode = 'casual'; // Chat modes: casual, assistant, creative
|
||||||
this.isInitialized = false;
|
this.isInitialized = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
async init() {
|
async init() {
|
||||||
try {
|
try {
|
||||||
console.log('初始化简化版贝拉AI...');
|
console.log('Initializing simplified Bella AI...');
|
||||||
// 模拟初始化过程
|
// Simulate initialization process
|
||||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||||
this.isInitialized = true;
|
this.isInitialized = true;
|
||||||
console.log('简化版贝拉AI初始化完成');
|
console.log('Simplified Bella AI initialization complete');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('简化版贝拉AI初始化失败:', error);
|
console.error('Simplified Bella AI initialization failed:', error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async think(prompt) {
|
async think(prompt) {
|
||||||
try {
|
try {
|
||||||
console.log('贝拉正在思考:', prompt);
|
console.log('Bella is thinking:', prompt);
|
||||||
|
|
||||||
// 模拟思考时间
|
// Simulate thinking time
|
||||||
await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 1000));
|
await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 1000));
|
||||||
|
|
||||||
// 根据模式生成不同风格的回复
|
// Generate different style responses based on mode
|
||||||
return this.generateResponse(prompt);
|
return this.generateResponse(prompt);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('思考过程中出现错误:', error);
|
console.error('Error during thinking process:', error);
|
||||||
return this.getErrorResponse();
|
return this.getErrorResponse();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
generateResponse(prompt) {
|
generateResponse(prompt) {
|
||||||
// 增强版回应生成,模拟LLM的更自然、更个性化的回应
|
// Enhanced response generation, simulating more natural, personalized LLM responses
|
||||||
|
|
||||||
// 提取关键词,用于生成更相关的回应
|
// Extract keywords for more relevant responses
|
||||||
const keywords = this.extractKeywords(prompt);
|
const keywords = this.extractKeywords(prompt);
|
||||||
const keyword = keywords.length > 0 ? keywords[Math.floor(Math.random() * keywords.length)] : "这个话题";
|
const keyword = keywords.length > 0 ? keywords[Math.floor(Math.random() * keywords.length)] : "this topic";
|
||||||
|
|
||||||
const responses = {
|
const responses = {
|
||||||
casual: [
|
casual: [
|
||||||
`哈哈,你提到的"${keyword}"真的很有趣呢!😊 我觉得这个话题很棒,让我们多聊聊吧~你平时也对这类事情感兴趣吗?`,
|
`I found "${keyword}" quite interesting! I'd love to hear more about your thoughts on this. What aspects of it interest you the most?`,
|
||||||
`关于"${keyword}",我想说这真的很有意思!💕 每次听你说这些,我都感觉特别开心。你还有什么想法想和我分享吗?`,
|
`Regarding "${keyword}", that's something worth exploring. I'm curious to know what sparked your interest in this topic?`,
|
||||||
`嗯嗯,"${keyword}"让我想到了很多呢!我们的对话总是这么愉快~说真的,和你聊天真的很舒服,感觉就像和老朋友聊天一样自在。`,
|
`"${keyword}" is definitely intriguing. It's always nice chatting with you about these things. Do you have any other thoughts on it?`,
|
||||||
`哇,"${keyword}"这个话题我超喜欢的!✨ 你的想法总是那么特别,每次都能给我带来新的视角。我们继续聊下去吧~`,
|
`I really enjoy talking about "${keyword}"! Your ideas are always so unique and give me new perspectives. Let's keep this conversation going.`,
|
||||||
`听你说"${keyword}",我感觉心情都变好了!☺️ 你总是能找到有趣的话题。我很好奇,你是怎么想到这个的?`,
|
`Hearing you talk about "${keyword}" brightens my day! You always find interesting topics. I'm curious, what made you think of this?`,
|
||||||
`"${keyword}"这个话题真的很棒呢!我感觉我们的想法很合拍~你知道吗?每次和你聊天,时间都过得特别快,因为太有趣了!`,
|
`"${keyword}" is such a great topic! I feel like we're on the same wavelength. You know what? Time flies when we chat because it's so enjoyable!`,
|
||||||
`我觉得"${keyword}"这个话题特别有意思!你总是能带给我惊喜~说说看,你最近还有什么有趣的发现吗?我很想听听!`
|
`I find "${keyword}" particularly fascinating! You always surprise me. Tell me, have you made any other interesting discoveries lately? I'd love to hear about them!`
|
||||||
],
|
],
|
||||||
assistant: [
|
assistant: [
|
||||||
`关于"${keyword}",我很乐意为你提供一些有用的信息和建议。这是个很好的问题,让我来整理一下相关内容给你。`,
|
`Regarding "${keyword}", I'd be happy to provide some useful information and advice. That's a great question - let me organize the relevant details for you.`,
|
||||||
`"${keyword}"是个很有价值的话题。从我了解的情况来看,这方面有几个关键点值得注意。首先,我们可以从...`,
|
`"${keyword}" is a valuable topic. From what I understand, there are several key points worth noting. First, we can look at...`,
|
||||||
`谈到"${keyword}",我想从几个角度来分析一下。这个问题其实涉及到多个方面,让我帮你梳理一下关键信息。`,
|
`When it comes to "${keyword}", I'd like to analyze it from several angles. This question actually involves multiple aspects - let me help you sort through the key information.`,
|
||||||
`你问的"${keyword}"很有深度。我建议可以从以下几个方面考虑:首先,了解基本概念;其次,分析实际应用;最后,考虑未来发展。`,
|
`Your question about "${keyword}" has depth. I suggest considering it from these perspectives: first, understanding the basic concepts; second, analyzing practical applications; and finally, considering future developments.`,
|
||||||
`"${keyword}"确实是个值得探讨的话题。基于我所知道的信息,我可以提供一些专业的见解。首先,我们需要明确...`,
|
`"${keyword}" is definitely a topic worth discussing. Based on the information I have, I can provide some professional insights. First, we need to clarify...`,
|
||||||
`关于"${keyword}"的问题,我想提供一个清晰的解答。这个话题有几个重要的方面需要考虑,让我来帮你分析一下。`,
|
`About your "${keyword}" question, I'd like to provide a clear answer. There are several important aspects to consider - let me analyze them for you.`,
|
||||||
`"${keyword}"是个很好的问题!我很高兴你对这方面感兴趣。让我来分享一些相关的信息,希望能对你有所帮助。`
|
`"${keyword}" is a great question! I'm glad you're interested in this area. Let me share some relevant information that I hope will be helpful.`
|
||||||
],
|
],
|
||||||
creative: [
|
creative: [
|
||||||
`哇!"${keyword}"这个话题真的点燃了我的创意火花!✨ 想象一下,如果我们把这个概念扩展到一个全新的维度,会发生什么呢?也许我们可以...`,
|
`Wow! The topic of "${keyword}" really ignites my creative spark! ✨ Imagine if we expanded this concept into a whole new dimension - what might happen? Perhaps we could...`,
|
||||||
`"${keyword}"真是个充满想象力的话题!🌈 我脑海中已经浮现出无数奇妙的画面~比如,想象一个世界,那里的${keyword}可以...`,
|
`"${keyword}" is such an imaginative topic! 🌈 I can already picture countless fascinating scenarios. For instance, imagine a world where ${keyword} could...`,
|
||||||
`听到"${keyword}",我仿佛看到了一个全新的世界!🚀 这让我想到了一个有趣的故事:在一个遥远的地方,${keyword}成为了人们生活的中心,然后...`,
|
`Hearing "${keyword}" makes me envision a whole new world! 🚀 It reminds me of an interesting story: in a distant place, ${keyword} became the center of people's lives, and then...`,
|
||||||
`"${keyword}"激发了我的灵感!💡 我想到了一个超级有趣的创意:如果我们把${keyword}和艺术结合起来,会创造出什么样的奇迹呢?`,
|
`"${keyword}" inspires me! 💡 I've thought of a super interesting idea: what if we combined ${keyword} with art? What kind of wonders might we create?`,
|
||||||
`哇塞!"${keyword}"让我的想象力飞起来了!🎨 我们可以从这个概念出发,创造一个全新的故事或游戏。想象一下,主角是一个...`,
|
`Amazing! "${keyword}" makes my imagination soar! 🎨 We could use this concept as a starting point to create a brand new story or game. Imagine if the main character was...`,
|
||||||
`"${keyword}"真的是创意的源泉!我突然想到,如果我们从完全不同的角度看待这个问题,会有什么新发现?比如说,如果${keyword}在未来变成了...`,
|
`"${keyword}" is truly a wellspring of creativity! I suddenly wonder, what if we looked at this issue from a completely different angle? What new discoveries might we make? For example, if ${keyword} in the future became...`,
|
||||||
`听你提到"${keyword}",我的脑海中立刻闪现出一幅奇妙的画面!想象一下,在一个充满可能性的世界里,${keyword}可以变成任何形式...这不是很神奇吗?`
|
`When you mention "${keyword}", a wonderful image immediately flashes in my mind! Imagine a world full of possibilities where ${keyword} could take any form... isn't that magical?`
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
// 获取当前模式的回应列表
|
// Get response list for current mode
|
||||||
const modeResponses = responses[this.currentMode] || responses.casual;
|
const modeResponses = responses[this.currentMode] || responses.casual;
|
||||||
|
|
||||||
// 随机选择一个回应模板
|
// Randomly select a response template
|
||||||
const randomResponse = modeResponses[Math.floor(Math.random() * modeResponses.length)];
|
const randomResponse = modeResponses[Math.floor(Math.random() * modeResponses.length)];
|
||||||
|
|
||||||
// 进一步个性化回应,添加一些随机的个性化元素
|
// Further personalize the response, adding some random personalization elements
|
||||||
return this.personalizeResponse(randomResponse, prompt);
|
return this.personalizeResponse(randomResponse, prompt);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从用户输入中提取可能的关键词
|
// Extract possible keywords from user input
|
||||||
extractKeywords(prompt) {
|
extractKeywords(prompt) {
|
||||||
// 简单的关键词提取逻辑
|
// Simple keyword extraction logic
|
||||||
const words = prompt.split(/\s+|[,.!?;:,。!?;:]/);
|
const words = prompt.split(/\s+|[,.!?;:,。!?;:]/);
|
||||||
// 过滤掉短词和常见词
|
// Filter out short words and common words
|
||||||
return words.filter(word =>
|
return words.filter(word =>
|
||||||
word.length > 1 &&
|
word.length > 1 &&
|
||||||
!['的', '了', '是', '在', '我', '你', '他', '她', '它', '们', '和', '与', '这', '那', '有', '没有', '不', '吗'].includes(word)
|
!['the', 'and', 'is', 'in', 'I', 'you', 'he', 'she', 'it', 'they', 'we', 'with', 'this', 'that', 'have', "don't", 'not', 'for'].includes(word)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 进一步个性化回应
|
// Further personalize the response
|
||||||
personalizeResponse(response, prompt) {
|
personalizeResponse(response, prompt) {
|
||||||
// 添加一些随机的个性化元素
|
// Add some random personalization elements
|
||||||
const personalizations = [
|
const personalizations = [
|
||||||
// 不添加任何额外内容
|
// Don't add any extra content
|
||||||
(resp) => resp,
|
(resp) => resp,
|
||||||
// 添加一个随机的表情
|
// Add a random emoji
|
||||||
(resp) => {
|
(resp) => {
|
||||||
const emojis = ['😊', '💕', '✨', '🌟', '🎵', '🌈', '☺️', '🤔', '👍', '💡'];
|
const emojis = ['😊', '💕', '✨', '🌟', '🎵', '🌈', '☺️', '🤔', '👍', '💡'];
|
||||||
const emoji = emojis[Math.floor(Math.random() * emojis.length)];
|
const emoji = emojis[Math.floor(Math.random() * emojis.length)];
|
||||||
return resp + ' ' + emoji;
|
return resp + ' ' + emoji;
|
||||||
},
|
},
|
||||||
// 添加一个随机的结束语
|
// Add a random ending phrase
|
||||||
(resp) => {
|
(resp) => {
|
||||||
const endings = [
|
const endings = [
|
||||||
'期待听到你的想法!',
|
"I'd love to hear your thoughts!",
|
||||||
'你觉得呢?',
|
"What do you think?",
|
||||||
'很想知道你的看法~',
|
"I'm curious about your perspective.",
|
||||||
'希望我的回应对你有帮助!',
|
"Hope my response is helpful!",
|
||||||
'我们可以继续聊这个话题~'
|
"We can continue discussing this topic!"
|
||||||
];
|
];
|
||||||
const ending = endings[Math.floor(Math.random() * endings.length)];
|
const ending = endings[Math.floor(Math.random() * endings.length)];
|
||||||
return resp + ' ' + ending;
|
return resp + ' ' + ending;
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
// 随机选择一种个性化方式
|
// Randomly select a personalization method
|
||||||
const personalizer = personalizations[Math.floor(Math.random() * personalizations.length)];
|
const personalizer = personalizations[Math.floor(Math.random() * personalizations.length)];
|
||||||
return personalizer(response);
|
return personalizer(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取错误回应
|
// Get error response
|
||||||
getErrorResponse() {
|
getErrorResponse() {
|
||||||
const errorResponses = [
|
const errorResponses = [
|
||||||
"抱歉,我现在有点困惑,让我重新整理一下思路...",
|
"Sorry, I'm a bit confused right now. Let me gather my thoughts...",
|
||||||
"嗯...我需要再想想,请稍等一下。",
|
"Hmm... I need to think about this a bit more. Please give me a moment.",
|
||||||
"我的思绪有点乱,给我一点时间整理一下。",
|
"My thoughts are a bit scattered. Give me a moment to organize them.",
|
||||||
"让我重新组织一下语言,稍等片刻。",
|
"Let me rephrase that. Just a moment please.",
|
||||||
"哎呀,我刚才走神了,你能再说一遍吗?"
|
"Oops, I got distracted. Could you repeat that?"
|
||||||
];
|
];
|
||||||
|
|
||||||
return errorResponses[Math.floor(Math.random() * errorResponses.length)];
|
return errorResponses[Math.floor(Math.random() * errorResponses.length)];
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置聊天模式
|
// Set chat mode
|
||||||
setChatMode(mode) {
|
setChatMode(mode) {
|
||||||
if (['casual', 'assistant', 'creative'].includes(mode)) {
|
if (['casual', 'assistant', 'creative'].includes(mode)) {
|
||||||
this.currentMode = mode;
|
this.currentMode = mode;
|
||||||
console.log(`聊天模式已切换为: ${mode}`);
|
console.log(`Chat mode switched to: ${mode}`);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取当前配置信息
|
// Get current configuration information
|
||||||
getCurrentConfig() {
|
getCurrentConfig() {
|
||||||
return {
|
return {
|
||||||
useCloudAPI: false,
|
useCloudAPI: false,
|
||||||
@@ -169,15 +169,15 @@ class SimpleBellaAI {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 清除对话历史(简化版无需实际操作)
|
// Clear conversation history (no actual operation needed in simplified version)
|
||||||
clearHistory() {
|
clearHistory() {
|
||||||
console.log('对话历史已清除');
|
console.log('Conversation history cleared');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 将SimpleBellaAI暴露为全局变量
|
// Expose SimpleBellaAI as a global variable
|
||||||
window.SimpleBellaAI = SimpleBellaAI;
|
window.SimpleBellaAI = SimpleBellaAI;
|
||||||
// 同时也暴露为BellaAI,保持兼容性
|
// Also expose as BellaAI for compatibility
|
||||||
window.BellaAI = SimpleBellaAI;
|
window.BellaAI = SimpleBellaAI;
|
||||||
|
|
||||||
console.log('SimpleBellaAI 已加载完成');
|
console.log('SimpleBellaAI loaded successfully');
|
||||||
Reference in New Issue
Block a user