Merge pull request #64 from GRISHM7890/enhance-llm-dialogue

confirm
This commit is contained in:
2025-07-29 17:33:42 +08:00
5 changed files with 431 additions and 270 deletions
+148 -129
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,206 +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模型
- **💝 基础交互**:好感度系统和情感反馈
### ✅ 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
```
---
## 🛠️ 开发指南
## 🧠 Enhanced LLM Dialogue Capabilities
### 环境配置
1. 确保 Node.js 版本 ≥ 22.16.0
2. 运行 `npm install` 安装依赖
3. 运行 `npm run download` 下载AI模型
4. 运行 `npm start` 启动开发服务器
Bella now uses more advanced LLM prompt engineering techniques to make conversations more natural, fluid, and personalized:
### 开发原则
- **优雅代码**:追求简洁、可读、美观的代码
- **AI作为画笔**:AI是创作工具,而非思想本身
- **父女情感**:以温暖、关爱的情感连接为核心
- **持续进化**:支持功能的渐进式增强
### 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
### 贡献指南
1. Fork 项目
2. 创建功能分支 (`git checkout -b feature/AmazingFeature`)
3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
4. 推送到分支 (`git push origin feature/AmazingFeature`)
5. 打开 Pull Request
### 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
### 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
### 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
### 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
### 第一阶段:感知核心 (已完成 80%)
-语音识别集成
-视觉表现系统
-基础交互界面
- 🔄 思考引擎激活
- 🔄 语音合成集成
### 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>
+76 -50
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,39 +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伙伴。你的特点是:
1. 用温暖亲切的语气与用户交流,就像一个贴心的朋友
2. 回答简洁明了,避免冗长的解释
3. 富有同理心,能够理解用户的情感
4. 偶尔展现一些可爱和俏皮的一面
5. 用中文回应,语言自然流畅
6. 记住你们之间的对话,保持连贯性
请始终保持这种温暖、优雅的个性。`
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. 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 {
@@ -120,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 = [
@@ -147,21 +163,25 @@ class CloudAPIService {
body: JSON.stringify({
model: config.model,
messages: messages,
max_tokens: 150,
temperature: 0.8,
top_p: 0.9
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 = [
@@ -178,22 +198,24 @@ class CloudAPIService {
messages: messages
},
parameters: {
max_tokens: 150,
temperature: 0.8,
top_p: 0.9
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 = [
@@ -208,21 +230,23 @@ class CloudAPIService {
headers: config.headers,
body: JSON.stringify({
messages: messages,
temperature: 0.8,
top_p: 0.9,
max_output_tokens: 150
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 = [
@@ -236,26 +260,28 @@ class CloudAPIService {
body: JSON.stringify({
model: config.model,
messages: messages,
max_tokens: 150,
temperature: 0.8,
top_p: 0.9
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,
@@ -263,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;
+103 -45
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,66 +96,122 @@ class BellaAI {
}
}
// 使用云端API进行思考
// Think using cloud API
async thinkWithCloudAPI(prompt) {
const enhancedPrompt = this.enhancePromptForMode(prompt);
return await this.cloudAPI.chat(enhancedPrompt);
}
// 使用本地模型进行思考
// 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);
// Optimized LLM parameters for better responses
const result = await this.llm(bellaPrompt, {
max_new_tokens: 50,
temperature: 0.8,
top_k: 40,
do_sample: true,
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();
}
return response || "我需要再想想...";
// 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)];
}
return response;
}
// 根据模式增强提示词
// Enhance prompts based on mode, using advanced LLM prompt engineering
enhancePromptForMode(prompt, isLocal = false) {
const modePrompts = {
casual: isLocal ?
`作为一个温暖、可爱的AI伙伴贝拉,用轻松亲切的语气回应:${prompt}` :
`请用温暖、轻松的语气回应,就像一个贴心的朋友。保持简洁有趣:${prompt}`,
`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
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.
User message: ${prompt}
Bella's response:`,
assistant: isLocal ?
`作为智能助手贝拉,提供有用、准确的帮助:${prompt}` :
`作为一个专业但温暖的AI助手,提供准确有用的信息和建议:${prompt}`,
`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
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.
User question: ${prompt}
Bella's professional response:`,
creative: isLocal ?
`作为富有创意的AI伙伴贝拉,发挥想象力回应:${prompt}` :
`发挥创意和想象力,提供有趣、独特的回应和想法:${prompt}`
`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
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.
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;
@@ -164,7 +220,7 @@ class BellaAI {
return false;
}
// 切换AI服务提供商
// Switch AI service provider
switchProvider(provider) {
if (provider === 'local') {
this.useCloudAPI = false;
@@ -178,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,
@@ -198,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';
@@ -218,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"
},
+99 -41
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,94 +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) {
// 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)] : "this topic";
const responses = {
casual: [
`哈哈,你说的"${prompt}"真有趣!我觉得这个话题很棒呢~`,
`关于"${prompt}",我想说这真的很有意思!你还想聊什么吗?`,
`嗯嗯,"${prompt}"让我想到了很多呢!我们继续聊下去吧~`,
`哇,"${prompt}"这个话题我喜欢!你的想法总是那么特别~`,
`听你说"${prompt}",我感觉心情都变好了!继续和我分享吧~`
`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: [
`关于"${prompt}",我来为您提供一些有用的信息和建议。`,
`针对"${prompt}"这个问题,我建议您可以从以下几个方面考虑。`,
`"${prompt}"是一个很好的问题,让我来帮您分析一下。`,
`基于"${prompt}",我可以为您提供以下专业建议。`,
`关于"${prompt}",我整理了一些相关信息供您参考。`
`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: [
`哇!"${prompt}"让我的创意火花瞬间点燃!让我们一起想象一下...`,
`"${prompt}"真是个充满想象力的话题!我脑海中浮现出无数奇妙的画面~`,
`听到"${prompt}",我仿佛看到了一个全新的世界!让我们一起探索吧~`,
`"${prompt}"激发了我的灵感!我想到了一个超级有趣的创意...`,
`哇塞!"${prompt}"让我的想象力飞起来了!我们来创造点什么特别的吧~`
`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)];
return randomResponse;
// 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 &&
!['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,
@@ -111,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');