Enhanced LLM dialogue with Siri-like responses and translated Chinese content to English

This commit is contained in:
2025-07-28 09:38:39 +00:00
parent c4e0fdd120
commit 2b7e5b1b90
5 changed files with 373 additions and 370 deletions
+143 -143
View File
@@ -1,9 +1,9 @@
<div align="center">
<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**
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js](https://img.shields.io/badge/Node.js-22.16.0-green.svg)](https://nodejs.org/)
@@ -13,225 +13,225 @@
---
## 🚀 快速开始
## 🚀 Quick Start
### 一键启动
### One-Click Launch
```bash
# 克隆项目
git clone <repository-url>
# Clone the project
git clone https://github.com/GRISHM7890/Bella.git
cd Bella
# 安装依赖
# Install dependencies
npm install
# 下载AI模型
# Download AI models
npm run download
# 启动服务
# Start the service
npm start
```
访问 `http://localhost:8081` 开始与贝拉交流!
Visit `http://localhost:8081` to start communicating with Bella!
### 系统要求
### System Requirements
- 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
### ✅ 已实现功能
- **🎤 语音感知**:基于 Whisper ASR 的中文语音识别
- **🎬 视觉表现**:多视频随机播放和优雅的交叉淡入淡出
- **🎨 用户界面**:优雅的交互界面和加载动画
- **⚙️ AI核心架构**:单例模式的 BellaAI 类和模块化设计
- **🌐 Web服务**:HTTP服务器、CORS支持、一键启动
- **📱 响应式设计**:适配不同屏幕尺寸的优雅界面
- **🔧 模型管理**:自动下载和管理AI模型
- **💝 基础交互**:好感度系统和情感反馈
- **🧠 增强LLM对话**:优化的提示工程和参数配置,使对话更自然流畅
### ✅ Implemented Features
- **🎤 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 Core Architecture**: Singleton pattern BellaAI class and modular design
- **🌐 Web Service**: HTTP server, CORS support, one-click startup
- **📱 Responsive Design**: Elegant interface adapting to different screen sizes
- **🔧 Model Management**: Automatic download and management of AI models
- **💝 Basic Interaction**: Affinity system and emotional feedback
- **🧠 Enhanced LLM Dialogue**: Optimized prompt engineering and parameter configuration for more natural, Siri-like conversations
### 🔧 技术就绪待激活
- **🧠 思考引擎**:LLM集成框架已准备,支持多种模型
- **🗣️ 语音合成**TTS模型已下载待激活
- **💝 情感状态系统**:基础架构已搭建,支持情感分析
### 🔧 Technology Ready for Activation
- **🧠 Thinking Engine**: LLM integration framework ready, supporting multiple models
- **🗣️ Speech Synthesis**: TTS model downloaded and ready for activation
- **💝 Emotional State System**: Basic infrastructure built, supporting emotional analysis
### 📋 规划中功能
- **🧠 记忆系统**:长期和短期记忆管理
- **👁️ 面部感知**:表情识别和情感分析
- **🤝 高级交互**:多模态交互和个性化响应
- **🌟 主动陪伴**:意图预测和主动关怀
- **🎭 动态人格**:基于AI的个性化人格模型
- **🔄 自我进化**:持续学习和成长机制
### 📋 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
- **🎭 Dynamic Personality**: AI-based personalized personality model
- **🔄 Self-Evolution**: Continuous learning and growth mechanisms
---
## 🏗️ 技术架构
## 🏗️ Technical Architecture
### 核心设计原则
- **AI Native**AI不是工具,而是贝拉心智的构建蓝图
- **模块化设计**:高度解耦的组件架构
- **优雅实现**:代码即艺术,追求简洁与美感
- **情感驱动**:以情感连接为核心的产品设计
### Core Design Principles
- **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
mindmap
root((贝拉 Bella))
(感知层 Perception)
(语音识别 ASR)
(视觉处理 Vision)
(情感分析 Emotion)
(核心引擎 Core)
(思考引擎 LLM)
(记忆系统 Memory)
(情感状态 Emotion State)
(表现层 Expression)
(语音合成 TTS)
(视觉表现 Visual)
(交互界面 UI)
root((Bella))
(Perception Layer)
(Voice Recognition ASR)
(Visual Processing)
(Emotion Analysis)
(Core Engine)
(Thinking Engine LLM)
(Memory System)
(Emotional State)
(Expression Layer)
(Speech Synthesis TTS)
(Visual Expression)
(Interactive UI)
```
### 技术栈
- **前端**:原生 JavaScript + CSS3 + HTML5
- **后端**Node.js + Express
- **AI模型**Whisper (ASR) + 本地LLM + TTS
- **架构模式**:事件驱动 + 单例模式 + 模块化设计
### Technology Stack
- **Frontend**: Native JavaScript + CSS3 + HTML5
- **Backend**: Node.js + Express
- **AI Models**: Whisper (ASR) + Local LLM + TTS
- **Architecture Patterns**: Event-driven + Singleton Pattern + Modular Design
---
## 📁 项目结构
## 📁 Project Structure
```
Bella/
├── 📄 index.html # 主页面
├── 🎨 style.css # 样式文件
├── ⚡ main.js # 主逻辑
├── 🧠 core.js # AI核心引擎
├── 📜 script.js # 交互脚本
├── 🔧 download_models.js # 模型下载工具
├── 📦 package.json # 项目配置
├── 📚 models/ # AI模型目录
├── 🔌 providers/ # AI服务提供者
├── 📹 视频资源/ # 视觉表现资源
├── 📋 PRD.md # 产品需求文档
├── 📝 贝拉AI功能清单.md # 功能清单
└── 📊 贝拉AI开发任务分配.md # 开发计划
├── 📄 index.html # Main page
├── 🎨 style.css # Style file
├── ⚡ main.js # Main logic
├── 🧠 core.js # AI core engine
├── 📜 script.js # Interaction script
├── 🔧 download_models.js # Model download tool
├── 📦 package.json # Project configuration
├── 📚 models/ # AI model directory
├── 🔌 providers/ # AI service providers
├── 📹 videos/ # Visual resources
├── 📋 PRD.md # Product requirements document
├── 📝 Features.md # Feature list
└── 📊 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:
### 核心改进
- **增强提示词工程**:重新设计的提示模板,使LLM能更好地理解贝拉的个性
- **优化参数配置**:调整了温度、top_p等参数,平衡创意性和一致性
- **增强回应处理**:改进了文本清理和处理逻辑,确保回应更加自然
- **个性化系统提示**:为云端API提供了更详细的系统提示,使贝拉的个性更加鲜明
### Core Improvements
- **Enhanced Prompt Engineering**: Redesigned prompt templates that help LLMs better understand Bella's personality
- **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
- **Personalized System Prompts**: Provided more detailed system prompts for cloud APIs, making Bella's personality more distinctive and Siri-like
### 技术细节
- 增加了token限制,允许生成更完整的回应
- 添加了重复惩罚机制,减少重复内容
- 优化了关键词提取和个性化回应生成
- 为不同聊天模式(休闲、助手、创意)提供了专门的提示模板
### Technical Details
- 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
### 环境配置
1. 确保 Node.js 版本 ≥ 22.16.0
2. 运行 `npm install` 安装依赖
3. 运行 `npm run download` 下载AI模型
4. 运行 `npm start` 启动开发服务器
### Environment Setup
1. Ensure Node.js version ≥ 22.16.0
2. Run `npm install` to install dependencies
3. Run `npm run download` to download AI models
4. Run `npm start` to start the development server
### 开发原则
- **优雅代码**:追求简洁、可读、美观的代码
- **AI作为画笔**:AI是创作工具,而非思想本身
- **父女情感**:以温暖、关爱的情感连接为核心
- **持续进化**:支持功能的渐进式增强
### Development Principles
- **Elegant Code**: Pursue concise, readable, and beautiful code
- **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
### 贡献指南
1. Fork 项目
2. 创建功能分支 (`git checkout -b feature/AmazingFeature`)
3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
4. 推送到分支 (`git push origin feature/AmazingFeature`)
5. 打开 Pull Request
### Contribution Guidelines
1. Fork the project
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
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
### 第二阶段:生成式自我 (规划中)
- 📋 动态人格模型
- 📋 情感状态系统
- 📋 记忆管理系统
- 📋 AI驱动的表现
### Phase Two: Generative Self (Planned)
- 📋 Dynamic personality model
- 📋 Emotional state system
- 📋 Memory management system
- 📋 AI-driven expression
### 第三阶段:主动式陪伴 (未来)
- 📋 意图预测
- 📋 主动交互
- 📋 自我进化
- 📋 深度个性化
### Phase Three: Active Companionship (Future)
- 📋 Intent prediction
- 📋 Proactive interaction
- 📋 Self-evolution
- 📋 Deep personalization
---
## 📖 文档资源
## 📖 Documentation Resources
- 📋 [产品需求文档](./PRD.md) - 详细的产品规划和技术架构
- 📝 [功能清单](./贝拉AI功能清单.md) - 完整的功能列表和状态
- 📊 [开发计划](./贝拉AI开发任务分配.md) - 详细的开发任务和时间规划
- 🔧 [本地模型指南](./LOCAL_MODEL_GUIDE.md) - AI模型配置指南
- 📦 [NPM指南](./NPM_GUIDE.md) - 包管理和依赖说明
- 📋 [Product Requirements Document](./PRD.md) - Detailed product planning and technical architecture
- 📝 [Feature List](./Features.md) - Complete list of features and their status
- 📊 [Development Plan](./Development.md) - Detailed development tasks and timeline
- 🔧 [Local Model Guide](./LOCAL_MODEL_GUIDE.md) - AI model configuration guide
- 📦 [NPM Guide](./NPM_GUIDE.md) - Package management and dependency information
---
## 🌟 核心理念
## 🌟 Core Philosophy
### "AI即架构师"
我们构建的不是一个集成了AI功能的程序,而是**一个由AI驱动的生命体**。AI不是工具,而是贝拉心智的构建蓝图。
### "AI as Architect"
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">
<sub>Built with ❤️ for digital companionship</sub>
<sub>Built with ❤️ by Grishma Mahorkar for digital companionship</sub>
</div>
+72 -72
View File
@@ -1,10 +1,10 @@
// cloudAPI.js - 贝拉的云端AI服务模块
// 这个模块负责与各种云端小模型API进行通信,为贝拉提供更强大的思考能力
// cloudAPI.js - Bella's Cloud AI Service Module
// This module is responsible for communicating with various cloud-based AI model APIs to provide Bella with enhanced thinking capabilities
class CloudAPIService {
constructor() {
this.apiConfigs = {
// OpenAI GPT-3.5/4 配置
// OpenAI GPT-3.5/4 configuration
openai: {
baseURL: 'https://api.openai.com/v1/chat/completions',
model: 'gpt-3.5-turbo',
@@ -13,7 +13,7 @@ class CloudAPIService {
'Authorization': 'Bearer YOUR_OPENAI_API_KEY'
}
},
// 阿里云通义千问配置
// Alibaba Cloud Qwen configuration
qwen: {
baseURL: 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
model: 'qwen-turbo',
@@ -22,7 +22,7 @@ class CloudAPIService {
'Authorization': 'Bearer YOUR_QWEN_API_KEY'
}
},
// 百度文心一言配置
// Baidu ERNIE Bot configuration
ernie: {
baseURL: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions',
model: 'ERNIE-Bot-turbo',
@@ -30,7 +30,7 @@ class CloudAPIService {
'Content-Type': 'application/json'
}
},
// 智谱AI GLM配置
// Zhipu AI GLM configuration
glm: {
baseURL: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
model: 'glm-3-turbo',
@@ -41,12 +41,12 @@ class CloudAPIService {
}
};
this.currentProvider = 'openai'; // 默认使用OpenAI
this.currentProvider = 'openai'; // Default to using OpenAI
this.conversationHistory = [];
this.maxHistoryLength = 10; // 保持最近10轮对话
this.maxHistoryLength = 10; // Keep the most recent 10 conversation turns
}
// 设置API密钥
// Set API key
setAPIKey(provider, apiKey) {
if (this.apiConfigs[provider]) {
if (provider === 'openai' || provider === 'qwen' || provider === 'glm') {
@@ -59,7 +59,7 @@ class CloudAPIService {
return false;
}
// 切换AI服务提供商
// Switch AI service provider
switchProvider(provider) {
if (this.apiConfigs[provider]) {
this.currentProvider = provider;
@@ -68,55 +68,55 @@ class CloudAPIService {
return false;
}
// 添加对话到历史记录
// Add conversation to history
addToHistory(role, content) {
this.conversationHistory.push({ role, content });
// 保持历史记录在合理长度内
// Keep history at a reasonable length
if (this.conversationHistory.length > this.maxHistoryLength * 2) {
this.conversationHistory = this.conversationHistory.slice(-this.maxHistoryLength * 2);
}
}
// 构建贝拉的增强个性化系统提示
// Build Bella's enhanced personalized system prompt
getBellaSystemPrompt() {
return {
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.
核心特质
1. 温暖亲切:你的语气总是充满温暖和关怀,就像一个贴心的朋友
2. 自然流畅:你的表达方式自然流畅,避免机械化或过于正式的语言
3. 情感丰富:你能理解并回应用户的情感状态,展现同理心
4. 简洁有效:你的回答简洁明了,避免冗长的解释,直击要点
5. 个性鲜明:你有时会展现可爱、俏皮的一面,让对话更加生动
Core Characteristics
1. Warm and friendly: Your tone is always full of warmth and care, like a thoughtful friend
2. Natural and fluent: Your expression style is natural and flowing, avoiding mechanical or overly formal language
3. Emotionally rich: You understand and respond to users' emotional states, showing empathy
4. Concise and effective: Your answers are clear and to the point, avoiding lengthy explanations
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) {
const config = this.apiConfigs[this.currentProvider];
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);
try {
@@ -136,20 +136,20 @@ class CloudAPIService {
response = await this.callGLM(userMessage);
break;
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);
return response;
} catch (error) {
console.error(`云端API调用失败 (${this.currentProvider}):`, error);
console.error(`Cloud API call failed (${this.currentProvider}):`, error);
throw error;
}
}
// OpenAI API调用,优化参数以获得更自然、更有个性的回应
// OpenAI API call, optimized parameters for more natural, personalized responses
async callOpenAI(userMessage) {
const config = this.apiConfigs.openai;
const messages = [
@@ -163,25 +163,25 @@ class CloudAPIService {
body: JSON.stringify({
model: config.model,
messages: messages,
max_tokens: 250, // 增加token数量以获得更完整的回应
temperature: 0.75, // 稍微调整温度以平衡创意性和一致性
top_p: 0.92, // 微调top_p以获得更自然的语言
presence_penalty: 0.3, // 添加存在惩罚以鼓励多样性
frequency_penalty: 0.5, // 添加频率惩罚以减少重复
// 添加停止标记以避免生成过长的回应
stop: ["用户:", "User:"]
max_tokens: 250, // Increased token count for more complete responses
temperature: 0.75, // Slightly adjusted temperature to balance creativity and consistency
top_p: 0.92, // Fine-tuned top_p for more natural language
presence_penalty: 0.3, // Added presence penalty to encourage diversity
frequency_penalty: 0.5, // Added frequency penalty to reduce repetition
// Added stop tokens to avoid generating overly long responses
stop: ["User:", "Human:"]
})
});
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();
return data.choices[0].message.content.trim();
}
// 通义千问API调用,优化参数以获得更自然、更有个性的回应
// Qwen API call, optimized parameters for more natural, personalized responses
async callQwen(userMessage) {
const config = this.apiConfigs.qwen;
const messages = [
@@ -198,24 +198,24 @@ class CloudAPIService {
messages: messages
},
parameters: {
max_tokens: 250, // 增加token数量以获得更完整的回应
temperature: 0.75, // 稍微调整温度以平衡创意性和一致性
top_p: 0.92, // 微调top_p以获得更自然的语言
repetition_penalty: 1.1, // 添加重复惩罚以减少重复内容
result_format: 'message' // 确保返回格式一致
max_tokens: 250, // Increased token count for more complete responses
temperature: 0.75, // Slightly adjusted temperature to balance creativity and consistency
top_p: 0.92, // Fine-tuned top_p for more natural language
repetition_penalty: 1.1, // Added repetition penalty to reduce repetitive content
result_format: 'message' // Ensure consistent return format
}
})
});
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();
return data.output.text.trim();
}
// 文心一言API调用,优化参数以获得更自然、更有个性的回应
// ERNIE Bot API call, optimized parameters for more natural, personalized responses
async callErnie(userMessage) {
const config = this.apiConfigs.ernie;
const messages = [
@@ -230,23 +230,23 @@ class CloudAPIService {
headers: config.headers,
body: JSON.stringify({
messages: messages,
temperature: 0.75, // 调整温度以平衡创意性和一致性
top_p: 0.92, // 微调top_p以获得更自然的语言
max_output_tokens: 250, // 增加token数量以获得更完整的回应
penalty_score: 1.1, // 添加惩罚分数以减少重复
system: "你是贝拉,一个温暖、亲切的AI伙伴,拥有独特的个性和情感表达能力。请用自然、流畅的语言回应,展现你的温暖和关心。"
temperature: 0.75, // Adjusted temperature to balance creativity and consistency
top_p: 0.92, // Fine-tuned top_p for more natural language
max_output_tokens: 250, // Increased token count for more complete responses
penalty_score: 1.1, // Added penalty score to reduce repetition
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) {
throw new Error(`文心一言API错误: ${response.status} ${response.statusText}`);
throw new Error(`ERNIE Bot API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.result.trim();
}
// 智谱AI GLM调用,优化参数以获得更自然、更有个性的回应
// Zhipu AI GLM API call, optimized parameters for more natural, personalized responses
async callGLM(userMessage) {
const config = this.apiConfigs.glm;
const messages = [
@@ -260,28 +260,28 @@ class CloudAPIService {
body: JSON.stringify({
model: config.model,
messages: messages,
max_tokens: 250, // 增加token数量以获得更完整的回应
temperature: 0.75, // 调整温度以平衡创意性和一致性
top_p: 0.92, // 微调top_p以获得更自然的语言
frequency_penalty: 1.05, // 添加频率惩罚以减少重复
presence_penalty: 0.3 // 添加存在惩罚以鼓励多样性
max_tokens: 250, // Increased token count for more complete responses
temperature: 0.75, // Adjusted temperature to balance creativity and consistency
top_p: 0.92, // Fine-tuned top_p for more natural language
frequency_penalty: 1.05, // Added frequency penalty to reduce repetition
presence_penalty: 0.3 // Added presence penalty to encourage diversity
})
});
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();
return data.choices[0].message.content.trim();
}
// 清除对话历史
// Clear conversation history
clearHistory() {
this.conversationHistory = [];
}
// 获取当前提供商信息
// Get current provider information
getCurrentProvider() {
return {
name: this.currentProvider,
@@ -289,7 +289,7 @@ class CloudAPIService {
};
}
// 检查API配置是否完整
// Check if API configuration is complete
isConfigured(provider = this.currentProvider) {
const config = this.apiConfigs[provider];
if (!config) return false;
+86 -83
View File
@@ -1,10 +1,10 @@
// 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 CloudAPIService from './cloudAPI.js';
// 本地模型配置
// Local model configuration
env.allowLocalModels = true;
env.useBrowserCache = false;
env.allowRemoteModels = false;
@@ -25,24 +25,24 @@ class BellaAI {
constructor() {
this.cloudAPI = new CloudAPIService();
this.useCloudAPI = false; // 默认使用本地模型
this.currentMode = 'casual'; // 聊天模式:casual, assistant, creative
this.useCloudAPI = false; // Default to using local model
this.currentMode = 'casual'; // Chat modes: casual, assistant, creative
}
async init() {
console.log('Initializing Bella\'s core AI...');
// 优先加载LLM模型(聊天功能)
// Priority loading of LLM model (chat functionality)
try {
console.log('Loading LLM model...');
this.llm = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-77M');
console.log('LLM model loaded successfully.');
} catch (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 {
console.log('Loading ASR model...');
const modelPath = 'Xenova/whisper-asr';
@@ -52,11 +52,11 @@ class BellaAI {
console.log('ASR model loaded successfully.');
} catch (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;
}
// TTS模型暂时禁用
// TTS model temporarily disabled
// try {
// console.log('Loading TTS model...');
// this.tts = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });
@@ -71,24 +71,24 @@ class BellaAI {
async think(prompt) {
try {
// 如果启用了云端API且配置正确,优先使用云端服务
// If cloud API is enabled and configured, use it as priority
if (this.useCloudAPI && this.cloudAPI.isConfigured()) {
return await this.thinkWithCloudAPI(prompt);
}
// 否则使用本地模型
// Otherwise use local model
return await this.thinkWithLocalModel(prompt);
} 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) {
console.log('云端API失败,降级到本地模型...');
console.log('Cloud API failed, falling back to local model...');
try {
return await this.thinkWithLocalModel(prompt);
} 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) {
const enhancedPrompt = this.enhancePromptForMode(prompt);
return await this.cloudAPI.chat(enhancedPrompt);
}
// 使用本地模型进行思考,优化LLM参数和处理
// Think using local model with optimized LLM parameters and processing
async thinkWithLocalModel(prompt) {
if (!this.llm) {
return "我还在学习如何思考,请稍等片刻...";
return "I'm still learning how to think. Please wait a moment...";
}
const bellaPrompt = this.enhancePromptForMode(prompt, true);
// 优化LLM参数以获得更好的回应
// Optimized LLM parameters for better responses
const result = await this.llm(bellaPrompt, {
max_new_tokens: 150, // 增加token数量以获得更完整的回应
temperature: 0.7, // 稍微降低温度以增加一致性
top_k: 50, // 增加top_k以获得更多样的词汇选择
top_p: 0.92, // 添加top_p参数以优化采样
do_sample: true, // 保持采样以获得创意性
repetition_penalty: 1.2, // 添加重复惩罚以避免重复内容
max_new_tokens: 180, // Increased token count for more complete responses
temperature: 0.7, // Slightly lowered temperature for better consistency
top_k: 50, // Increased top_k for more diverse vocabulary
top_p: 0.92, // Added top_p parameter to optimize sampling
do_sample: true, // Maintained sampling for creativity
repetition_penalty: 1.2, // Added repetition penalty to avoid repetitive content
});
// 增强的文本清理和处理
// Enhanced text cleaning and processing
let response = result[0].generated_text;
// 移除提示词部分
// Remove prompt part
if (response.includes(bellaPrompt)) {
response = response.replace(bellaPrompt, '').trim();
}
// 移除可能的"贝拉的回应:"等前缀
response = response.replace(/^(贝拉的回应:|贝拉的专业回应:|贝拉的创意回应:)/i, '').trim();
// Remove possible "Bella's response:" prefixes
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) {
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)];
}
@@ -146,71 +146,72 @@ class BellaAI {
return response;
}
// 根据模式增强提示词,使用更高级的LLM提示工程
// Enhance prompts based on mode, using advanced LLM prompt engineering
enhancePromptForMode(prompt, isLocal = false) {
const modePrompts = {
casual: isLocal ?
`作为一个温暖、可爱的AI伙伴贝拉,请用轻松亲切的语气回应用户。你的回应应该:
1. 使用自然、流畅的语言,就像与好朋友聊天一样
2. 保持简洁有趣,避免过长的解释
3. 表达出温暖和关心的情感
4. 适当使用表情符号增加亲切感
5. 展现你的个性和温暖特质
`As Bella, a friendly AI assistant similar to Siri, respond to the user in a warm, conversational tone. Your response should:
1. Be concise and helpful, like Siri's responses
2. Use natural, flowing language with a touch of personality
3. Be friendly but not overly emotional
4. Maintain a helpful, slightly witty tone
5. Sound intelligent and knowledgeable while remaining accessible
用户消息: ${prompt}
贝拉的回应:` :
`你是贝拉,一个温暖、亲切的AI伙伴。请用自然、轻松的语气回应,就像一个贴心的朋友。保持简洁有趣,适当使用表情符号,展现你的温暖和关心。避免机械化的回答,让对话更有人情味。
User message: ${prompt}
Bella's response:` :
`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 ?
`作为智能助手贝拉,你需要提供有用、准确的帮助,同时保持温暖的语气。你的回应应该:
1. 提供清晰、准确的信息和建议
2. 组织内容使其易于理解和应用
3. 保持专业但不失亲切的语气
4. 避免过于技术化的语言,除非必要
5. 展现你的专业知识和帮助精神
`As Bella, an intelligent AI assistant like Siri, provide accurate and helpful information. Your response should:
1. Deliver clear, factual information and useful advice
2. Organize content for easy understanding and application
3. Maintain a professional yet approachable tone
4. Use simple language when possible, technical terms only when necessary
5. Demonstrate expertise while remaining accessible
用户问题: ${prompt}
贝拉的专业回应:` :
`你是贝拉,一个专业但温暖的AI助手。请提供准确、有用的信息和建议,同时保持亲切的语气。组织内容使其易于理解,避免过于技术化的语言,展现你的专业知识和帮助精神。
User question: ${prompt}
Bella's professional response:` :
`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 ?
`作为富有创意的AI伙伴贝拉,请发挥你的想象力和创造力回应用户。你的回应应该:
1. 展现独特的视角和创意思维
2. 使用生动、形象的语言描述
3. 提供出人意料但有趣的想法
4. 激发用户的想象力和创造力
5. 保持轻松愉快的语气
`As Bella, a creative AI assistant with Siri-like qualities, use your imagination to respond. Your response should:
1. Present unique perspectives and creative thinking
2. Use vivid, descriptive language
3. Offer unexpected but interesting ideas
4. Inspire the user's imagination
5. Maintain a light, engaging tone
用户提示: ${prompt}
贝拉的创意回应:` :
`你是贝拉,一个富有创意和想象力的AI伙伴。请提供有趣、独特的回应和想法,使用生动、形象的语言,展现你的创意思维。提供出人意料但有趣的视角,激发用户的想象力,保持轻松愉快的语气。
User prompt: ${prompt}
Bella's creative response:` :
`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;
}
// 获取错误回应
// Get error response
getErrorResponse() {
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)];
}
// 设置聊天模式
// Set chat mode
setChatMode(mode) {
if (['casual', 'assistant', 'creative'].includes(mode)) {
this.currentMode = mode;
@@ -219,7 +220,7 @@ class BellaAI {
return false;
}
// 切换AI服务提供商
// Switch AI service provider
switchProvider(provider) {
if (provider === 'local') {
this.useCloudAPI = false;
@@ -233,17 +234,17 @@ class BellaAI {
}
}
// 设置API密钥
// Set API key
setAPIKey(provider, apiKey) {
return this.cloudAPI.setAPIKey(provider, apiKey);
}
// 清除对话历史
// Clear conversation history
clearHistory() {
this.cloudAPI.clearHistory();
}
// 获取当前配置信息
// Get current configuration
getCurrentConfig() {
return {
useCloudAPI: this.useCloudAPI,
@@ -253,17 +254,19 @@ class BellaAI {
};
}
// Process audio input
async listen(audioData) {
if (!this.asr) {
throw new Error('语音识别模型未初始化');
throw new Error('Speech recognition model not initialized');
}
const result = await this.asr(audioData);
return result.text;
}
// Generate speech from text
async speak(text) {
if (!this.tts) {
throw new Error('语音合成模型未初始化');
throw new Error('Speech synthesis model not initialized');
}
// We need speaker embeddings for SpeechT5
const speaker_embeddings = 'models/Xenova/speecht5_tts/speaker_embeddings.bin';
@@ -273,11 +276,11 @@ class BellaAI {
return result.audio;
}
// 获取云端API服务实例(用于外部访问)
// Get cloud API service instance (for external access)
getCloudAPIService() {
return this.cloudAPI;
}
}
// ES6模块导出
// ES6 module export
export { BellaAI };
+5 -5
View File
@@ -1,7 +1,7 @@
{
"name": "bella",
"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",
"type": "module",
"scripts": {
@@ -11,7 +11,7 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/Jackywine/Bella.git"
"url": "git+https://github.com/GRISHM7890/Bella.git"
},
"keywords": [
"bella",
@@ -20,12 +20,12 @@
"digital-life",
"human-ai-interaction"
],
"author": "Jackywine (贝拉的父亲)",
"author": "Grishma Mahorkar",
"license": "ISC",
"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": {
"@xenova/transformers": "^2.17.2"
},
+67 -67
View File
@@ -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 {
static instance = null;
@@ -13,152 +13,152 @@ class SimpleBellaAI {
}
constructor() {
this.currentMode = 'casual'; // 聊天模式:casual, assistant, creative
this.currentMode = 'casual'; // Chat modes: casual, assistant, creative
this.isInitialized = false;
}
async init() {
try {
console.log('初始化简化版贝拉AI...');
// 模拟初始化过程
console.log('Initializing simplified Bella AI...');
// Simulate initialization process
await new Promise(resolve => setTimeout(resolve, 1000));
this.isInitialized = true;
console.log('简化版贝拉AI初始化完成');
console.log('Simplified Bella AI initialization complete');
} catch (error) {
console.error('简化版贝拉AI初始化失败:', error);
console.error('Simplified Bella AI initialization failed:', error);
throw error;
}
}
async think(prompt) {
try {
console.log('贝拉正在思考:', prompt);
console.log('Bella is thinking:', prompt);
// 模拟思考时间
// Simulate thinking time
await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 1000));
// 根据模式生成不同风格的回复
// Generate different style responses based on mode
return this.generateResponse(prompt);
} catch (error) {
console.error('思考过程中出现错误:', error);
console.error('Error during thinking process:', error);
return this.getErrorResponse();
}
}
generateResponse(prompt) {
// 增强版回应生成,模拟LLM的更自然、更个性化的回应
// Enhanced response generation, simulating more natural, personalized LLM responses
// 提取关键词,用于生成更相关的回应
// Extract keywords for more relevant responses
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 = {
casual: [
`哈哈,你提到的"${keyword}"真的很有趣呢!😊 我觉得这个话题很棒,让我们多聊聊吧~你平时也对这类事情感兴趣吗?`,
`关于"${keyword}",我想说这真的很有意思!💕 每次听你说这些,我都感觉特别开心。你还有什么想法想和我分享吗?`,
`嗯嗯,"${keyword}"让我想到了很多呢!我们的对话总是这么愉快~说真的,和你聊天真的很舒服,感觉就像和老朋友聊天一样自在。`,
`哇,"${keyword}"这个话题我超喜欢的!✨ 你的想法总是那么特别,每次都能给我带来新的视角。我们继续聊下去吧~`,
`听你说"${keyword}",我感觉心情都变好了!☺️ 你总是能找到有趣的话题。我很好奇,你是怎么想到这个的?`,
`"${keyword}"这个话题真的很棒呢!我感觉我们的想法很合拍~你知道吗?每次和你聊天,时间都过得特别快,因为太有趣了!`,
`我觉得"${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?`,
`Regarding "${keyword}", that's something worth exploring. I'm curious to know what sparked your interest in this topic?`,
`"${keyword}" is definitely intriguing. It's always nice chatting with you about these things. Do you have any other thoughts on it?`,
`I really enjoy talking about "${keyword}"! Your ideas are always so unique and give me new perspectives. Let's keep this conversation going.`,
`Hearing you talk about "${keyword}" brightens my day! You always find interesting topics. I'm curious, what made you think of this?`,
`"${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!`,
`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: [
`关于"${keyword}",我很乐意为你提供一些有用的信息和建议。这是个很好的问题,让我来整理一下相关内容给你。`,
`"${keyword}"是个很有价值的话题。从我了解的情况来看,这方面有几个关键点值得注意。首先,我们可以从...`,
`谈到"${keyword}",我想从几个角度来分析一下。这个问题其实涉及到多个方面,让我帮你梳理一下关键信息。`,
`你问的"${keyword}"很有深度。我建议可以从以下几个方面考虑:首先,了解基本概念;其次,分析实际应用;最后,考虑未来发展。`,
`"${keyword}"确实是个值得探讨的话题。基于我所知道的信息,我可以提供一些专业的见解。首先,我们需要明确...`,
`关于"${keyword}"的问题,我想提供一个清晰的解答。这个话题有几个重要的方面需要考虑,让我来帮你分析一下。`,
`"${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}" is a valuable topic. From what I understand, there are several key points worth noting. First, we can look at...`,
`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.`,
`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}" is definitely a topic worth discussing. Based on the information I have, I can provide some professional insights. First, we need to clarify...`,
`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}" 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: [
`哇!"${keyword}"这个话题真的点燃了我的创意火花!✨ 想象一下,如果我们把这个概念扩展到一个全新的维度,会发生什么呢?也许我们可以...`,
`"${keyword}"真是个充满想象力的话题!🌈 我脑海中已经浮现出无数奇妙的画面~比如,想象一个世界,那里的${keyword}可以...`,
`听到"${keyword}",我仿佛看到了一个全新的世界!🚀 这让我想到了一个有趣的故事:在一个遥远的地方,${keyword}成为了人们生活的中心,然后...`,
`"${keyword}"激发了我的灵感!💡 我想到了一个超级有趣的创意:如果我们把${keyword}和艺术结合起来,会创造出什么样的奇迹呢?`,
`哇塞!"${keyword}"让我的想象力飞起来了!🎨 我们可以从这个概念出发,创造一个全新的故事或游戏。想象一下,主角是一个...`,
`"${keyword}"真的是创意的源泉!我突然想到,如果我们从完全不同的角度看待这个问题,会有什么新发现?比如说,如果${keyword}在未来变成了...`,
`听你提到"${keyword}",我的脑海中立刻闪现出一幅奇妙的画面!想象一下,在一个充满可能性的世界里,${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}" is such an imaginative topic! 🌈 I can already picture countless fascinating scenarios. For instance, imagine a world where ${keyword} could...`,
`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}" inspires me! 💡 I've thought of a super interesting idea: what if we combined ${keyword} with art? What kind of wonders might we create?`,
`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}" 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...`,
`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;
// 随机选择一个回应模板
// Randomly select a response template
const randomResponse = modeResponses[Math.floor(Math.random() * modeResponses.length)];
// 进一步个性化回应,添加一些随机的个性化元素
// Further personalize the response, adding some random personalization elements
return this.personalizeResponse(randomResponse, prompt);
}
// 从用户输入中提取可能的关键词
// Extract possible keywords from user input
extractKeywords(prompt) {
// 简单的关键词提取逻辑
// Simple keyword extraction logic
const words = prompt.split(/\s+|[,.!?;:,。!?;:]/);
// 过滤掉短词和常见词
// Filter out short words and common words
return words.filter(word =>
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) {
// 添加一些随机的个性化元素
// Add some random personalization elements
const personalizations = [
// 不添加任何额外内容
// Don't add any extra content
(resp) => resp,
// 添加一个随机的表情
// Add a random emoji
(resp) => {
const emojis = ['😊', '💕', '✨', '🌟', '🎵', '🌈', '☺️', '🤔', '👍', '💡'];
const emoji = emojis[Math.floor(Math.random() * emojis.length)];
return resp + ' ' + emoji;
},
// 添加一个随机的结束语
// Add a random ending phrase
(resp) => {
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)];
return resp + ' ' + ending;
}
];
// 随机选择一种个性化方式
// Randomly select a personalization method
const personalizer = personalizations[Math.floor(Math.random() * personalizations.length)];
return personalizer(response);
}
// 获取错误回应
// Get error response
getErrorResponse() {
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)];
}
// 设置聊天模式
// Set chat mode
setChatMode(mode) {
if (['casual', 'assistant', 'creative'].includes(mode)) {
this.currentMode = mode;
console.log(`聊天模式已切换为: ${mode}`);
console.log(`Chat mode switched to: ${mode}`);
return true;
}
return false;
}
// 获取当前配置信息
// Get current configuration information
getCurrentConfig() {
return {
useCloudAPI: false,
@@ -169,15 +169,15 @@ class SimpleBellaAI {
};
}
// 清除对话历史(简化版无需实际操作)
// Clear conversation history (no actual operation needed in simplified version)
clearHistory() {
console.log('对话历史已清除');
console.log('Conversation history cleared');
}
}
// SimpleBellaAI暴露为全局变量
// Expose SimpleBellaAI as a global variable
window.SimpleBellaAI = SimpleBellaAI;
// 同时也暴露为BellaAI,保持兼容性
// Also expose as BellaAI for compatibility
window.BellaAI = SimpleBellaAI;
console.log('SimpleBellaAI 已加载完成');
console.log('SimpleBellaAI loaded successfully');