diff --git a/.gitignore b/.gitignore index 6cc16b409..b6eae4a81 100644 --- a/.gitignore +++ b/.gitignore @@ -171,6 +171,7 @@ main/manager-api/.vscode # Ignore webpack cache directory main/manager-web/.webpack_cache/ main/xiaozhi-server/mysql +main/xiaozhi-server/redis uploadfile *.json .vscode diff --git a/main/manager-api/src/main/resources/db/changelog/202511051120.sql b/main/manager-api/src/main/resources/db/changelog/202511051120.sql new file mode 100644 index 000000000..ccc4322d6 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202511051120.sql @@ -0,0 +1,68 @@ +-- 添加 ElevenLabs 和 Cartesia TTS 供应器和模型配置 + +-- ==================== ElevenLabs TTS ==================== + +-- 添加 ElevenLabs TTS 供应器 +DELETE FROM `ai_model_provider` WHERE id = 'TTS_ElevenLabs'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('TTS_ElevenLabs', 'TTS', 'elevenlabs', 'ElevenLabs TTS', '[{"key":"api_key","label":"API Key","type":"string"},{"key":"voice_id","label":"Voice ID","type":"string"},{"key":"model","label":"Model","type":"string"},{"key":"output_format","label":"Output Format","type":"string"},{"key":"stability","label":"Stability","type":"number"},{"key":"similarity_boost","label":"Similarity Boost","type":"number"},{"key":"style","label":"Style","type":"number"},{"key":"use_speaker_boost","label":"Use Speaker Boost","type":"string"},{"key":"optimize_streaming_latency","label":"Optimize Streaming Latency","type":"number"},{"key":"output_dir","label":"Output Directory","type":"string"}]', 21, 1, NOW(), 1, NOW()); + +-- 添加 ElevenLabs TTS 模型配置 +DELETE FROM `ai_model_config` WHERE id = 'TTS_ElevenLabs'; +INSERT INTO `ai_model_config` VALUES ( + 'TTS_ElevenLabs', + 'TTS', + 'ElevenLabs', + 'ElevenLabs TTS', + 0, + 1, + '{\"type\": \"elevenlabs\", \"api_key\": \"\", \"voice_id\": \"21m00Tcm4TlvDq8ikWAM\", \"model\": \"eleven_multilingual_v2\", \"output_format\": \"pcm_16000\", \"stability\": 0.5, \"similarity_boost\": 0.75, \"style\": 0.0, \"use_speaker_boost\": true, \"optimize_streaming_latency\": 3, \"output_dir\": \"tmp/\"}', + 'https://elevenlabs.io/docs/introduction', + 'ElevenLabs TTS 配置说明:\n1. ElevenLabs 提供高质量、情感丰富的语音合成服务\n2. 支持多语言(包括英文、中文等)和声音克隆功能\n3. 使用官方 Python SDK,延迟低、质量高\n4. API Key 获取:访问 https://elevenlabs.io/ 注册并获取\n5. Voice ID 可在 ElevenLabs 控制台中找到预设音色或创建自定义音色\n6. Model 推荐使用 eleven_multilingual_v2(多语言)或 eleven_turbo_v2(低延迟)\n7. Stability (0-1): 控制语音稳定性,越高越稳定但变化少\n8. Similarity Boost (0-1): 控制与原音色的相似度\n9. Style (0-1): 控制语音风格强度\n10. Optimize Streaming Latency (0-4): 优化流式延迟,推荐 2-3', + 23, + NULL, + NULL, + NULL, + NULL +); + +-- 添加 ElevenLabs 音色配置 +DELETE FROM `ai_tts_voice` WHERE id IN ('TTS_ElevenLabs0001', 'TTS_ElevenLabs0002', 'TTS_ElevenLabs0003', 'TTS_ElevenLabs0004'); +INSERT INTO `ai_tts_voice` VALUES ('TTS_ElevenLabs0001', 'TTS_ElevenLabs', 'Rachel - Female', '21m00Tcm4TlvDq8ikWAM', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_ElevenLabs0002', 'TTS_ElevenLabs', 'Drew - Male', '29vD33N1CtxCmqQRPOHJ', 'English', NULL, NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_ElevenLabs0003', 'TTS_ElevenLabs', 'Clyde - Male', '2EiwWnXFnvU5JabPnv8n', 'English', NULL, NULL, NULL, NULL, 3, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_ElevenLabs0004', 'TTS_ElevenLabs', 'Bella - Female', 'EXAVITQu4vr4xnSDxMaL', 'English', NULL, NULL, NULL, NULL, 4, NULL, NULL, NULL, NULL); + +-- ==================== Cartesia TTS ==================== + +-- 添加 Cartesia TTS 供应器 +DELETE FROM `ai_model_provider` WHERE id = 'TTS_Cartesia'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('TTS_Cartesia', 'TTS', 'cartesia', 'Cartesia TTS', '[{"key":"api_key","label":"API Key","type":"string"},{"key":"voice_id","label":"Voice ID","type":"string"},{"key":"model","label":"Model","type":"string"},{"key":"language","label":"Language","type":"string"},{"key":"encoding","label":"Encoding","type":"string"},{"key":"sample_rate","label":"Sample Rate","type":"number"},{"key":"output_dir","label":"Output Directory","type":"string"}]', 22, 1, NOW(), 1, NOW()); + +-- 添加 Cartesia TTS 模型配置 +DELETE FROM `ai_model_config` WHERE id = 'TTS_Cartesia'; +INSERT INTO `ai_model_config` VALUES ( + 'TTS_Cartesia', + 'TTS', + 'Cartesia', + 'Cartesia TTS', + 0, + 1, + '{\"type\": \"cartesia\", \"api_key\": \"\", \"voice_id\": \"a0e99841-438c-4a64-b679-ae501e7d6091\", \"model\": \"sonic-3\", \"language\": \"en\", \"encoding\": \"pcm_s16le\", \"sample_rate\": 24000, \"output_dir\": \"tmp/\"}', + 'https://docs.cartesia.ai/', + 'Cartesia TTS 配置说明:\n1. Cartesia 提供超低延迟的流式语音合成服务\n2. 使用官方 Python SDK,首包延迟极低(通常 < 200ms)\n3. 支持多种语言和声音(英语、西班牙语、法语、德语、中文等)\n4. API Key 获取:访问 https://cartesia.ai/ 注册并获取\n5. Voice ID 可在 Cartesia 控制台查看预设音色\n6. Model 选项:sonic-english(英语)、sonic-multilingual(多语言)\n7. Encoding: pcm_s16le(推荐)、pcm_mulaw 等\n8. Sample Rate: 8000/16000/24000/44100(推荐 24000)\n9. 特别适合需要实时交互的场景(如语音助手、客服)', + 24, + NULL, + NULL, + NULL, + NULL +); + +-- 添加 Cartesia 音色配置 +DELETE FROM `ai_tts_voice` WHERE id IN ('TTS_Cartesia0001', 'TTS_Cartesia0002', 'TTS_Cartesia0003', 'TTS_Cartesia0004'); +INSERT INTO `ai_tts_voice` VALUES ('TTS_Cartesia0001', 'TTS_Cartesia', 'Barbershop Man', 'a0e99841-438c-4a64-b679-ae501e7d6091', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_Cartesia0002', 'TTS_Cartesia', 'Kentucky Man', '41534e16-2966-4c6b-9670-111411def906', 'English', NULL, NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_Cartesia0003', 'TTS_Cartesia', 'British Lady', '79a125e8-cd45-4c13-8a67-188112f4dd22', 'English', NULL, NULL, NULL, NULL, 3, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_Cartesia0004', 'TTS_Cartesia', 'Friendly Reader', '69267136-1bdc-412f-ad78-0caad210fb40', 'English', NULL, NULL, NULL, NULL, 4, NULL, NULL, NULL, NULL); + diff --git a/main/manager-api/src/main/resources/db/changelog/202511071245.sql b/main/manager-api/src/main/resources/db/changelog/202511071245.sql new file mode 100644 index 000000000..ab09b80bc --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202511071245.sql @@ -0,0 +1,43 @@ +-- Add Deepgram TTS Provider and Model Configuration + +-- ==================== Deepgram TTS ==================== + +-- Add Deepgram TTS Provider +DELETE FROM `ai_model_provider` WHERE id = 'TTS_Deepgram'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('TTS_Deepgram', 'TTS', 'deepgram', 'Deepgram TTS', '[{"key":"api_key","label":"API Key","type":"string"},{"key":"model","label":"Model","type":"string"}]', 20, 1, NOW(), 1, NOW()); + +-- Add Deepgram TTS Model Configuration +DELETE FROM `ai_model_config` WHERE id = 'TTS_Deepgram'; +INSERT INTO `ai_model_config` ( + `id`, + `model_type`, + `model_code`, + `model_name`, + `is_default`, + `is_enabled`, + `config_json`, + `doc_link`, + `remark`, + `sort`, + `creator`, + `create_date`, + `updater`, + `update_date` +) VALUES ( + 'TTS_Deepgram', + 'TTS', + 'Deepgram', + 'Deepgram TTS', + 0, + 1, + '{"type": "deepgram", "api_key": "", "model": "aura-2-thalia-en"}', + 'https://developers.deepgram.com/docs/text-to-speech', + 'Deepgram TTS Configuration:\n1. Deepgram provides high-quality, low-latency AI text-to-speech service\n2. Uses official Deepgram Python SDK (deepgram-sdk)\n3. Supports multiple languages and Aura 2 voice models\n4. API Key: Register at https://console.deepgram.com/ to get your API key\n5. Model: Deepgram voice models directly specify the voice (e.g., aura-2-thalia-en, aura-2-stella-en, aura-2-orion-en)\n6. Available Models:\n - Female: aura-2-asteria-en, aura-2-luna-en, aura-2-stella-en, aura-2-athena-en\n - Male: aura-2-orion-en, aura-2-arcas-en, aura-2-perseus-en, aura-2-zeus-en\n7. Features: Natural voices, multi-language support, low latency\n8. Perfect for real-time voice applications and conversational AI', + 22, + NULL, + NULL, + NULL, + NULL +); + diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index b6b88bf39..3675c27e4 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -402,3 +402,17 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202510191042.sql + - changeSet: + id: 202511051120 + author: pany + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202511051120.sql + - changeSet: + id: 202511071245 + author: harold + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202511071245.sql diff --git a/main/xiaozhi-server/.dockerignore b/main/xiaozhi-server/.dockerignore new file mode 100644 index 000000000..4a1359add --- /dev/null +++ b/main/xiaozhi-server/.dockerignore @@ -0,0 +1,80 @@ +# Python cache and compiled files +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python + +# Virtual environments +venv/ +env/ +ENV/ +.venv + +# IDE and editor files +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store + +# Git +.git/ +.gitignore +.gitattributes + +# Documentation +*.md +docs/ + +# Docker files +Dockerfile* +docker-compose*.yml +.dockerignore + +# Test files +test/ +tests/ +performance_tester/ +performance_tester.py + +# Data directories (should be mounted as volumes) +# Note: data/ directory should be mounted as volume for persistent config +# But we exclude some files that shouldn't be in the image +data/.config.yaml +data/*.log +data/tmp/ +mysql/ +redis/ +uploadfile/ +logs/ + +# Temporary files +tmp/ +*.tmp +*.log + +# Model files (should be mounted as volumes) +models/*/model.pt + +# Music files (optional, can be mounted) +music/ + +# Backup and old files +*.bak +*.backup +*.old +# Note: custom_config.yaml is required in the image as default config +# config_from_api.yaml is generated at runtime, exclude it +config_from_api.yaml + +# OS generated files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + diff --git a/main/xiaozhi-server/Dockerfile b/main/xiaozhi-server/Dockerfile new file mode 100644 index 000000000..a5dca8b51 --- /dev/null +++ b/main/xiaozhi-server/Dockerfile @@ -0,0 +1,49 @@ +# Dockerfile for local development and testing +# Build xiaozhi-server image from local source code + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + libopus0 \ + ffmpeg \ + build-essential \ + git && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +# Configure pip to use Aliyun mirror for faster downloads in China +RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \ + pip config set global.trusted-host mirrors.aliyun.com && \ + pip config set global.timeout 120 && \ + pip config set install.retries 5 + +# Set working directory +WORKDIR /opt/xiaozhi-esp32-server + +# Copy requirements file +COPY requirements.txt . + +# Install Python dependencies +RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \ + pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5 + +# Copy application code +COPY . . + +# Set timezone +ENV TZ=Asia/Shanghai + +# Expose ports +# 8000: WebSocket server +# 8003: HTTP server for OTA and vision analysis +EXPOSE 8000 8003 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ + CMD python -c "import socket; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.settimeout(5); s.connect(('localhost', 8000)); s.close()" || exit 1 + +# Start application +CMD ["python", "app.py"] + diff --git a/main/xiaozhi-server/START_SCRIPT_USAGE.txt b/main/xiaozhi-server/START_SCRIPT_USAGE.txt new file mode 100644 index 000000000..5e4cf0c32 --- /dev/null +++ b/main/xiaozhi-server/START_SCRIPT_USAGE.txt @@ -0,0 +1,134 @@ +Xiaozhi Server Startup Script Usage +==================================== + +QUICK START +----------- + +1. Start server only (most common for development): + ./start.sh --region --action server + ./start.sh -r -a server + +2. Start all services (first time or full restart): + ./start.sh --region --action all + ./start.sh -r -a all + + +COMMAND LINE OPTIONS +-------------------- + + -r, --region Deployment region (required) + Values: sg, us, local + + -a, --action Action to perform (required) + Values: server, all + + -h, --help Show help message + + +REGION OPTIONS +-------------- + +sg - Singapore deployment (uses docker-compose_sg_all.yml) + REGION=SINGAPORE, secret: a1c50356-4307-4bb7-8c16-c661d06ec17b + +us - US West 2 deployment (uses docker-compose_us_all.yml) + REGION=US-WEST-2, secret: ff22d758-79dd-47ff-a897-c6e39983e0e1 + +local - Local development (uses docker-compose_local_all.yml) + REGION=LOCAL, secret: from custom_config.yaml + + +ACTION OPTIONS +-------------- + +server - Restart ONLY xiaozhi-esp32-server + Other services (web, db, redis) keep running + Fast restart for code iteration + ✓ Preserves database data + ✓ Preserves Redis cache + ✓ Avoids web service restart + +all - Start/restart ALL services + Runs: docker compose up -d + Use when: + - First time setup + - After modifying docker-compose files + - Need to restart web/db/redis + + +COMMON USAGE EXAMPLES +--------------------- + +# Development iteration (most frequent) +./start.sh --region local --action server # Local dev, restart server only +./start.sh -r sg -a server # Singapore, restart server only + +# First time or full restart +./start.sh --region local --action all # Start everything locally +./start.sh -r sg -a all # Deploy to Singapore +./start.sh -r us -a all # Deploy to US West 2 + +# Show help +./start.sh --help +./start.sh -h + + +WORKFLOW EXAMPLE +---------------- + +1. Initial setup: + ./start.sh --region local --action all + +2. Make code changes in xiaozhi-server + +3. Quick restart to test: + ./start.sh -r local -a server + +4. View logs: + docker compose -f docker-compose_local_all.yml logs -f xiaozhi-esp32-server + +5. Repeat steps 2-4 for rapid development + + +TIPS +---- + +* Server restart takes ~10 seconds +* All services restart takes ~1-2 minutes +* Database and Redis data persist between restarts +* Check container status: docker ps --filter name=xiaozhi +* Stop all services: docker compose -f docker-compose__all.yml down +* Both long (--region) and short (-r) options are supported +* Requires Docker Compose v2 (uses 'docker compose' without hyphen) + + +TROUBLESHOOTING +--------------- + +Q: "docker: 'compose' is not a docker command" +A: You need Docker Compose v2. Install it: + - Ubuntu/Debian: sudo apt-get install docker-compose-plugin + - macOS: Install Docker Desktop (includes Compose v2) + - Or see: https://docs.docker.com/compose/install/ + +Q: "Error: Invalid region 'XX'" +A: Use only: sg, us, or local (case insensitive) + +Q: "Error: Invalid action 'XX'" +A: Use only: server or all (case insensitive) + +Q: "Error: Unknown option" +A: Check syntax: ./start.sh --region --action + Or use short form: ./start.sh -r -a + +Q: "Error: Compose file not found" +A: Make sure you run the script from xiaozhi-server directory + +Q: Container not starting +A: Check logs with: + docker compose -f docker-compose__all.yml logs xiaozhi-esp32-server + +Q: Need to rebuild image after code changes +A: docker compose -f docker-compose__all.yml build xiaozhi-esp32-server + Then run: ./start.sh -r -a server + diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 248be252e..630b1c650 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -182,6 +182,23 @@ prompt: | # 默认系统提示词模板文件 prompt_template: agent-base-prompt.txt +# Role 配置 +# 指定要加载的 role 配置文件(位于 core/roles/data/目录) +# 如果不指定或加载失败,将使用 prompt 字段的内容作为 profile +role_id: hospital_assistant + +# 时区配置(用于系统提示词中的时间显示) +# 支持的时区格式:Asia/Shanghai, America/New_York, Europe/London 等 +# 默认:Asia/Shanghai +# 注意:如果 role 配置文件中指定了 timezone,将优先使用 role 配置中的值 +timezone: Asia/Shanghai + +# 语言配置(用于系统提示词中的语言特定提示) +# 支持:zh(中文)、en(英文) +# 默认:zh +# 注意:如果 role 配置文件中指定了 language,将优先使用 role 配置中的值 +language: zh + # 结束语prompt end_prompt: enable: true # 是否开启结束语 @@ -630,6 +647,49 @@ TTS: type: edge voice: zh-CN-XiaoxiaoNeural output_dir: tmp/ + # ============== SDK 版本TTS(推荐)============== + # 使用官方SDK,代码更简洁、性能更好、维护成本更低 + Cartesia: + # Cartesia TTS - SDK版本(推荐) + # 官方SDK实现,低延迟,支持流式合成 + # API Key获取地址:https://play.cartesia.ai/console + # 或设置环境变量:export CARTESIA_API_KEY=your-api-key + type: cartesia + api_key: 你的Cartesia API密钥 + # Voice ID或voice embedding + voice_id: 你的语音ID + # 模型选择:sonic-english, sonic-multilingual等 + model: sonic-english + # 语言代码:en, zh, es等 + language: en + # 音频编码:pcm_s16le, pcm_f32le, pcm_mulaw等 + encoding: pcm_s16le + # 采样率:8000, 16000, 22050, 24000, 44100等 + sample_rate: 24000 + output_dir: tmp/ + ElevenLabs: + # ElevenLabs TTS - SDK版本(推荐) + # 官方SDK实现,代码更简洁,维护成本更低,性能更好 + # API Key获取地址:https://elevenlabs.io/app/settings/api-keys + # 或设置环境变量:export ELEVEN_API_KEY=your-api-key + type: elevenlabs + api_key: 你的ElevenLabs API密钥 + # Voice ID获取:https://elevenlabs.io/app/voice-library + # 默认:21m00Tcm4TlvDq8ikWAM (Rachel) + voice_id: 21m00Tcm4TlvDq8ikWAM + # 模型选择:eleven_multilingual_v2, eleven_turbo_v2_5等 + model: eleven_multilingual_v2 + # 音频输出格式:pcm_16000, pcm_22050, pcm_24000, mp3_44100等 + output_format: pcm_16000 + # 语音稳定性:0-1,越高越稳定 + stability: 0.5 + # 相似度增强:0-1,越高越接近原音色 + similarity_boost: 0.75 + # 风格夸张:0-1 + style: 0.0 + # 启用说话人增强 + use_speaker_boost: true + output_dir: tmp/ DoubaoTTS: # 定义TTS API类型 type: doubao diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index b70cf9617..4c3f01b19 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -24,18 +24,18 @@ def load_config(): if cached_config is not None: return cached_config - default_config_path = get_project_dir() + "config.yaml" - custom_config_path = get_project_dir() + "data/.config.yaml" + # default_config_path = get_project_dir() + "config.yaml" + custom_config_path = get_project_dir() + "custom_config.yaml" # 加载默认配置 - default_config = read_config(default_config_path) + # default_config = read_config(default_config_path) custom_config = read_config(custom_config_path) if custom_config.get("manager-api", {}).get("url"): config = get_config_from_api(custom_config) - else: - # 合并配置 - config = merge_configs(default_config, custom_config) + # else: + # # 合并配置 + # config = merge_configs(default_config, custom_config) # 初始化目录 ensure_directories(config) diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index cd3f86c42..785cae3e9 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -44,7 +44,17 @@ class ManageApiClient: if "你" in cls.config.get("secret"): raise Exception("请先配置manager-api的secret") - cls._secret = cls.config.get("secret") + # 根据aws服务器所在机房路由不同secret + region = os.getenv("REGION", "LOCAL") # 默认 LOCAL + if region == "SINGAPORE": + cls._secret = "a1c50356-4307-4bb7-8c16-c661d06ec17b" + elif region == "US-WEST-2": + cls._secret = "ff22d758-79dd-47ff-a897-c6e39983e0e1" + else: + # LOCAL 或其他未知区域,使用配置文件中的 secret + cls._secret = cls.config.get("secret") + + print(f"[ManageApiClient] Region: {region}, Secret: {cls._secret[:8]}...") cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数 cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒) # NOTE(goody): 2025/4/16 http相关资源统一管理,后续可以增加线程池或者超时 diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py index fb8868b40..fcb7e855b 100644 --- a/main/xiaozhi-server/config/settings.py +++ b/main/xiaozhi-server/config/settings.py @@ -2,7 +2,7 @@ import os from config.config_loader import read_config, get_project_dir, load_config -default_config_file = "config.yaml" +default_config_file = "custom_config.yaml" config_file_valid = False @@ -13,21 +13,16 @@ def check_config_file(): """ 简化的配置检查,仅提示用户配置文件的使用情况 """ - custom_config_file = get_project_dir() + "data/." + default_config_file + custom_config_file = get_project_dir() + default_config_file if not os.path.exists(custom_config_file): raise FileNotFoundError( - "找不到data/.config.yaml文件,请按教程确认该配置文件是否存在" + "找不到custom_config.yaml文件,请按教程确认该配置文件是否存在" ) # 检查是否从API读取配置 config = load_config() if config.get("read_config_from_api", False): print("从API读取配置") - old_config_origin = read_config(custom_config_file) - if old_config_origin.get("selected_module") is not None: - error_msg = "您的配置文件好像既包含智控台的配置又包含本地配置:\n" - error_msg += "\n建议您:\n" - error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\n" - error_msg += "2、按教程配置好接口地址和密钥\n" - raise ValueError(error_msg) + # 支持混合模式:API 优先,本地配置作为兜底 + # 允许同时存在 API 配置和本地 selected_module/role_id config_file_valid = True diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 92043e9bd..db0b062eb 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -419,6 +419,15 @@ class ConnectionHandler: asyncio.run_coroutine_threadsafe( self.asr.open_audio_channels(self), self.loop ) + + """加载记忆""" + self._initialize_memory() + """加载意图识别""" + self._initialize_intent() + """更新系统提示词(必须在 TTS 初始化前,以便加载 role 的 TTS 配置)""" + self._init_prompt_enhancement() + + # 初始化 TTS(在 prompt 初始化之后,以便使用 role 的 TTS 配置) if self.tts is None: self.tts = self._initialize_tts() # 打开语音合成通道 @@ -426,24 +435,48 @@ class ConnectionHandler: self.tts.open_audio_channels(self), self.loop ) - """加载记忆""" - self._initialize_memory() - """加载意图识别""" - self._initialize_intent() """初始化上报线程""" self._init_report_threads() - """更新系统提示词""" - self._init_prompt_enhancement() except Exception as e: self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") def _init_prompt_enhancement(self): + """初始化并更新系统提示词""" # 更新上下文信息 self.prompt_manager.update_context_info(self, self.client_ip) - enhanced_prompt = self.prompt_manager.build_enhanced_prompt( - self.config["prompt"], self.device_id, self.client_ip + + # 获取用户画像(如果 Memory 模块已初始化) + user_persona = None + if self.memory and hasattr(self.memory, 'get_user_persona'): + try: + user_persona = self.memory.get_user_persona() + if user_persona: + self.logger.bind(tag=TAG).debug(f"获取到用户画像,长度: {len(user_persona)}") + except Exception as e: + self.logger.bind(tag=TAG).warning(f"获取用户画像失败: {e}") + + # 构建增强的系统提示词(返回 (enhanced_prompt, role_tts_config)) + result = self.prompt_manager.build_enhanced_prompt( + self.config["prompt"], + self.device_id, + self.client_ip, + user_persona=user_persona, ) + + # 解包返回值 + if isinstance(result, tuple): + enhanced_prompt, role_tts_config = result + # 保存 role 的 TTS 配置到 self.config(供 TTS 初始化使用) + if role_tts_config: + self.config["_role_tts_config"] = role_tts_config + self.logger.bind(tag=TAG).info( + f"保存 Role TTS 配置到 config: {role_tts_config}" + ) + else: + # 兼容旧版本返回值(仅返回 prompt 字符串) + enhanced_prompt = result + if enhanced_prompt: self.change_system_prompt(enhanced_prompt) self.logger.bind(tag=TAG).info("系统提示词已增强更新") @@ -462,15 +495,90 @@ class ConnectionHandler: self.logger.bind(tag=TAG).info("TTS上报线程已启动") def _initialize_tts(self): - """初始化TTS""" + """ + 初始化TTS(支持三级优先级配置) + + 优先级: + 1. API 下发的 TTS 配置(在 _initialize_private_config 中已应用) + 2. Role 中的 TTS 配置 + 3. selected_module.TTS(兜底配置) + """ tts = None if not self.need_bind: + # 检查是否有 role 的 TTS 配置(优先级2) + role_tts_config = self.config.get("_role_tts_config") + self.logger.bind(tag=TAG).info(f"🔍 检查 _role_tts_config: {role_tts_config}") + if role_tts_config: + self.logger.bind(tag=TAG).info("✅ 发现 Role TTS 配置,准备应用") + self._apply_role_tts_config(role_tts_config) + else: + self.logger.bind(tag=TAG).info("ℹ️ 没有 Role TTS 配置,使用默认配置") + + # 初始化 TTS(优先级1和3在这里统一处理) tts = initialize_tts(self.config) if tts is None: tts = DefaultTTS(self.config, delete_audio_file=True) return tts + + def _apply_role_tts_config(self, role_tts_config: dict): + """应用 role 中的 TTS 配置""" + self.logger.bind(tag=TAG).debug(f"开始应用 Role TTS 配置: {role_tts_config}") + provider = role_tts_config.get("provider") + voice_id = role_tts_config.get("voice_id") + + if not provider or not voice_id: + self.logger.bind(tag=TAG).warning("Role TTS 配置不完整,跳过应用") + return + + # 检查当前 selected_module.TTS 是否已经被 API 覆盖 + # 如果 API 已经设置了 TTS,则不应用 role 配置(API 优先级更高) + current_tts = self.config["selected_module"]["TTS"] + if self.config.get("_api_tts_applied"): + self.logger.bind(tag=TAG).info( + f"API 已设置 TTS 配置(优先级1),跳过 Role TTS 配置: {provider}" + ) + return + + # 应用 role 的 TTS 配置 + # 根据 provider 映射到实际的 TTS 模块名 + tts_module_map = { + "elevenlabs": "ElevenLabsSDK", + "cartesia": "CartesiaSDK", + "edge": "EdgeTTS", + "doubao": "VolcanoStreamTTS", + # 可以继续添加更多映射... + } + + tts_module = tts_module_map.get(provider.lower()) + if not tts_module: + self.logger.bind(tag=TAG).warning( + f"未知的 TTS provider: {provider},使用默认配置" + ) + return + + # 检查该 TTS 模块是否在配置中存在 + if tts_module not in self.config.get("TTS", {}): + self.logger.bind(tag=TAG).warning( + f"TTS 模块 {tts_module} 未在配置中定义,跳过应用" + ) + return + + # 更新 selected_module.TTS + self.config["selected_module"]["TTS"] = tts_module + + # 更新 voice_id(如果该 TTS 模块支持) + if "voice_id" in self.config["TTS"][tts_module]: + self.config["TTS"][tts_module]["voice_id"] = voice_id + self.logger.bind(tag=TAG).info( + f"✅ 应用 Role TTS 配置: provider={provider}, " + f"module={tts_module}, voice_id={voice_id[:16]}..." + ) + else: + self.logger.bind(tag=TAG).warning( + f"TTS 模块 {tts_module} 不支持 voice_id 配置" + ) def _initialize_asr(self): """初始化ASR""" @@ -555,6 +663,8 @@ class ConnectionHandler: self.config["selected_module"]["TTS"] = private_config["selected_module"][ "TTS" ] + # 标记 API 已设置 TTS 配置(优先级1) + self.config["_api_tts_applied"] = True if private_config.get("LLM", None) is not None: init_llm = True self.config["LLM"] = private_config["LLM"] @@ -753,24 +863,26 @@ class ConnectionHandler: ) memory_str = future.result() + # 获取对话历史 + dialogue_history = self.dialogue.get_llm_dialogue_with_memory( + memory_str, self.config.get("voiceprint", {}) + ) + if self.intent_type == "function_call" and functions is not None: - # 使用支持functions的streaming接口 + # 直接使用同步生成器(response_with_functions 是同步方法) llm_responses = self.llm.response_with_functions( self.session_id, - self.dialogue.get_llm_dialogue_with_memory( - memory_str, self.config.get("voiceprint", {}) - ), + dialogue_history, functions=functions, ) else: + # 直接使用同步生成器(response 是同步方法) llm_responses = self.llm.response( self.session_id, - self.dialogue.get_llm_dialogue_with_memory( - memory_str, self.config.get("voiceprint", {}) - ), + dialogue_history, ) except Exception as e: - self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") + self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}", exc_info=True) return None # 处理流式响应 @@ -781,6 +893,7 @@ class ConnectionHandler: content_arguments = "" self.client_abort = False emotion_flag = True + for response in llm_responses: if self.client_abort: break diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index 5c85c6478..f2f87c511 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -86,7 +86,11 @@ class LLMProvider(LLMProviderBase): yield content except Exception as e: - logger.bind(tag=TAG).error(f"Error in response generation: {e}") + try: + error_msg = repr(e)[:200] + except: + error_msg = "encoding error" + logger.bind(tag=TAG).error(f"Error in response generation: {error_msg}") def response_with_functions(self, session_id, dialogue, functions=None): try: @@ -97,18 +101,22 @@ class LLMProvider(LLMProviderBase): for chunk in stream: # 检查是否存在有效的choice且content不为空 if getattr(chunk, "choices", None): - yield chunk.choices[0].delta.content, chunk.choices[ - 0 - ].delta.tool_calls + content = chunk.choices[0].delta.content + tool_calls = chunk.choices[0].delta.tool_calls + yield content, tool_calls # 存在 CompletionUsage 消息时,生成 Token 消耗 log elif isinstance(getattr(chunk, "usage", None), CompletionUsage): usage_info = getattr(chunk, "usage", None) - logger.bind(tag=TAG).info( + logger.bind(tag=TAG).debug( f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," f"共计 {getattr(usage_info, 'total_tokens', '未知')}" ) except Exception as e: - logger.bind(tag=TAG).error(f"Error in function call streaming: {e}") - yield f"【OpenAI服务响应异常: {e}】", None + try: + error_msg = repr(e)[:200] + except: + error_msg = "encoding error" + logger.bind(tag=TAG).error(f"Error in function call streaming: {error_msg}") + yield "OpenAI service error", None diff --git a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py index d61d73f3e..c4f7d3f9d 100644 --- a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py +++ b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py @@ -1,4 +1,5 @@ import traceback +from typing import Optional from ..base import MemoryProviderBase, logger from mem0 import MemoryClient @@ -85,3 +86,37 @@ class MemoryProvider(MemoryProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}") return "" + + def get_user_persona(self) -> Optional[str]: + """获取格式化的用户画像信息(用于 prompt) + + Returns: + 格式化后的用户画像字符串,如果无记忆则返回 None + """ + if not self.use_mem0: + return None + + try: + # 使用通用查询获取所有记忆 + results = self.client.search( + "user information, preferences, background, personal details", + user_id=self.role_id, + output_format=self.api_version, + limit=10 # 限制返回数量 + ) + + if not results or "results" not in results: + return None + + # 格式化记忆条目 + persona_items = [] + for entry in results["results"]: + memory = entry.get("memory", "") + if memory: + persona_items.append(f"- {memory}") + + return "\n".join(persona_items) if persona_items else None + + except Exception as e: + logger.bind(tag=TAG).debug(f"获取用户画像失败: {str(e)}") + return None diff --git a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py index e4486b82c..10e3cfab2 100644 --- a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py +++ b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py @@ -3,6 +3,7 @@ import time import json import os import yaml +from typing import Optional from config.config_loader import get_project_dir from config.manage_api_client import save_mem_local_short from core.utils.util import check_model_key @@ -200,3 +201,57 @@ class MemoryProvider(MemoryProviderBase): async def query_memory(self, query: str) -> str: return self.short_memory + + def get_user_persona(self) -> Optional[str]: + """获取格式化的用户画像信息(用于 prompt) + + Returns: + 格式化后的用户画像字符串,如果无记忆则返回 None + """ + if not self.short_memory: + return None + + try: + # 尝试解析 JSON 格式的记忆 + memory_data = json.loads(self.short_memory) + + # 提取关键信息 + persona_items = [] + + # 提取身份信息 + if "时空档案" in memory_data: + identity = memory_data["时空档案"].get("身份图谱", {}) + if identity.get("现用名"): + persona_items.append(f"- 名字:{identity['现用名']}") + if identity.get("特征标记"): + tags = identity["特征标记"] + if isinstance(tags, list) and tags: + persona_items.append(f"- 特征:{', '.join(tags)}") + + # 提取记忆立方中的关键事件 + if "时空档案" in memory_data and "记忆立方" in memory_data["时空档案"]: + events = memory_data["时空档案"]["记忆立方"] + if isinstance(events, list) and events: + persona_items.append("\n重要事件:") + for event in events[:5]: # 只取前5个事件 + if isinstance(event, dict) and event.get("事件"): + persona_items.append(f" - {event['事件']}") + + # 提取高光语录 + if "高光语录" in memory_data and memory_data["高光语录"]: + quotes = memory_data["高光语录"] + if isinstance(quotes, list) and quotes: + persona_items.append("\n高光语录:") + for quote in quotes[:3]: # 只取前3条 + if quote: + persona_items.append(f" - {quote}") + + return "\n".join(persona_items) if persona_items else None + + except (json.JSONDecodeError, KeyError, TypeError) as e: + # 如果解析失败,可能是纯文本格式,直接返回 + logger.bind(tag=TAG).debug(f"记忆不是 JSON 格式,使用原始文本: {e}") + # 如果 short_memory 是纯文本,直接返回(但限制长度) + if isinstance(self.short_memory, str) and len(self.short_memory) > 0: + return self.short_memory[:500] # 限制长度避免 prompt 过长 + return None diff --git a/main/xiaozhi-server/core/providers/tts/cartesia.py b/main/xiaozhi-server/core/providers/tts/cartesia.py new file mode 100644 index 000000000..b4b69bca2 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/cartesia.py @@ -0,0 +1,165 @@ +""" +Cartesia TTS SDK 实现 + +使用官方 Cartesia Python SDK 实现流式 TTS +文档: https://docs.cartesia.ai/ +""" + +import asyncio +import os +import time +from typing import Optional, Callable, Dict, Any +from config.logger import setup_logging +from core.providers.tts.base import TTSProviderBase +from core.providers.tts.dto.dto import InterfaceType +import cartesia + +TAG = __name__ +logger = setup_logging() + + +class TTSProvider(TTSProviderBase): + """ + Cartesia TTS SDK 提供商 + + 特点: + - 低延迟流式合成 + - 支持多种语言和声音 + - 使用官方 SDK,代码简洁 + + 配置示例: + CartesiaSDK: + type: cartesia_sdk + api_key: your_api_key + voice_id: your_voice_id # 或 voice_embedding + model: sonic-3 + language: en + encoding: pcm_s16le + sample_rate: 24000 + output_dir: tmp/ + """ + + def __init__(self, config: dict, delete_audio_file: bool = True): + super().__init__(config, delete_audio_file) + + # 标记为单流式接口 + self.interface_type = InterfaceType.SINGLE_STREAM + # 设置音频文件类型为 WAV + self.audio_file_type = "pcm" + + # 获取 API Key + self.api_key = config.get("api_key") or os.environ.get("CARTESIA_API_KEY") + if not self.api_key: + raise ValueError( + "Cartesia API key is required. " + "Provide via api_key in config or set CARTESIA_API_KEY environment variable" + ) + + # Voice 配置(支持 voice_id 或 voice_embedding) + # 优先读取顶层 voice_id,然后检查嵌套的 voice.id 和 voice.embedding + self.voice_id = config.get("voice_id", "") + self.voice_embedding = None + + if not self.voice_id: + voice_config = config.get("voice", {}) + if isinstance(voice_config, dict): + self.voice_id = voice_config.get("id", "") + self.voice_embedding = voice_config.get("embedding") + elif voice_config: # 如果 voice 是字符串,直接作为 voice_id + self.voice_id = voice_config + + # 模型和语言配置 + self.model = config.get("model", "sonic-3") + self.language = config.get("language", "en") + + # 音频配置 + self.encoding = config.get("encoding", "pcm_s16le") + # 确保 sample_rate 是整数类型(配置文件可能返回字符串) + sample_rate_value = config.get("sample_rate", 16000) + self.sample_rate = int(sample_rate_value) if isinstance(sample_rate_value, str) else sample_rate_value + + # 验证至少有一个 voice 配置 + if not self.voice_id and not self.voice_embedding: + raise ValueError( + "Voice configuration is required. " + "Provide either voice_id or voice.embedding in config" + ) + + # 初始化 SDK 客户端 + self.client = cartesia.Cartesia(api_key=self.api_key) + self._ws_client = None + + logger.bind(tag=TAG).info( + f"Cartesia SDK initialized: model={self.model}, " + f"voice_id={self.voice_id[:8]+'...' if self.voice_id else 'embedding'}, " + f"language={self.language}, " + f"encoding={self.encoding}, sample_rate={self.sample_rate}" + ) + + def _get_ws_client(self): + """获取或创建 WebSocket 客户端(复用连接)""" + if self._ws_client is None: + self._ws_client = self.client.tts.websocket() + return self._ws_client + + def _prepare_voice_param(self) -> Dict[str, Any]: + """准备 voice 参数(避免重复代码)""" + if self.voice_id: + return { + "mode": "id", + "id": self.voice_id + } + elif self.voice_embedding: + return { + "mode": "embedding", + "embedding": self.voice_embedding + } + else: + raise ValueError("Neither voice_id nor voice_embedding is configured") + + async def text_to_speak(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]: + """ + 将文本转换为 WAV 格式音频(完整音频,非流式) + + Args: + text: 要合成的文本 + output_file: 输出文件路径(未使用,保留兼容性) + + Returns: + WAV 格式的完整音频字节数据 + """ + try: + ws = self._get_ws_client() + + pcm_chunks = [] + voice = self._prepare_voice_param() + + # 发送流式请求,获取 PCM 数据 + for output in ws.send( + model_id=self.model, + transcript=text, + voice=voice, + stream=True, + output_format={ + "container": "raw", + "encoding": self.encoding, # pcm_s16le + "sample_rate": self.sample_rate # 16000 or 24000 + } + ): + # Cartesia SDK 返回 WebSocketTtsOutput 对象 + # 从 output.audio 获取 PCM 音频数据 + if output and hasattr(output, 'audio') and output.audio: + pcm_chunks.append(output.audio) + + # 合并所有 PCM 音频块 + pcm_data = b''.join(pcm_chunks) + return pcm_data + + except Exception as e: + logger.bind(tag=TAG).error(f"Cartesia TTS failed: {e}", exc_info=True) + raise + + async def close(self): + """关闭 WebSocket 连接(Cartesia SDK 会自动管理)""" + self._ws_client = None + diff --git a/main/xiaozhi-server/core/providers/tts/deepgram.py b/main/xiaozhi-server/core/providers/tts/deepgram.py new file mode 100644 index 000000000..2f0c77769 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/deepgram.py @@ -0,0 +1,66 @@ +import os +from typing import Optional +from deepgram import DeepgramClient +from config.logger import setup_logging +from core.providers.tts.base import TTSProviderBase +from core.providers.tts.dto.dto import InterfaceType + +TAG = __name__ +logger = setup_logging() + + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.interface_type = InterfaceType.SINGLE_STREAM + + # Deepgram configuration + self.api_key = config.get("api_key") or os.environ.get("DEEPGRAM_API_KEY") + if not self.api_key: + raise ValueError( + "Deepgram API key is required. " + "Provide via api_key in config or set DEEPGRAM_API_KEY environment variable" + ) + + self.model = config.get("model", "aura-2-thalia-en") or os.environ.get("DEEPGRAM_MODEL") # Default voice model + self.encoding = config.get("encoding", "linear16") # PCM format + self.sample_rate = config.get("sample_rate", 16000) # Match client sample rate + self.container = config.get("container", "none") # Raw audio + self.audio_file_type = "pcm" + + # Initialize Deepgram client + self.client = DeepgramClient(api_key=self.api_key) + + logger.bind(tag=TAG).info( + f"Deepgram TTS initialized: model={self.model}, " + f"sample_rate={self.sample_rate}, encoding={self.encoding}" + ) + + async def text_to_speech(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]: + try: + audio_stream = self.client.speak.v1.audio.generate( + text=text, + model=self.model, + encoding = self.encoding, + sample_rate = self.sample_rate, + container = self.container, + ) + + if output_file: + with open(output_file, 'wb') as f: + for chunk in audio_stream: + f.write(chunk) + else: + audio_bytes = b"" + for chunk in audio_stream: + audio_bytes += chunk["data"] + return audio_bytes + + except Exception as e: + logger.bind(tag=TAG).error(f"Deepgram TTS failed: {e}", exc_info=True) + raise + + async def close(self): + """Resource cleanup""" + pass + diff --git a/main/xiaozhi-server/core/providers/tts/elevenlabs.py b/main/xiaozhi-server/core/providers/tts/elevenlabs.py new file mode 100644 index 000000000..913f3ae98 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/elevenlabs.py @@ -0,0 +1,142 @@ +""" +ElevenLabs TTS SDK 实现 + +使用官方 ElevenLabs Python SDK 实现流式 TTS +文档: https://elevenlabs.io/docs/ +""" + +import asyncio +import os +from typing import Optional, Callable +from config.logger import setup_logging +from core.providers.tts.base import TTSProviderBase +from core.providers.tts.dto.dto import InterfaceType + +try: + from elevenlabs.client import ElevenLabs + from elevenlabs import VoiceSettings +except ImportError: + raise ImportError( + "ElevenLabs SDK not installed. Install with: pip install elevenlabs" + ) + +TAG = __name__ +logger = setup_logging() + + +class TTSProvider(TTSProviderBase): + """ + ElevenLabs TTS SDK 提供商 + + 特点: + - 高质量、情感丰富的语音 + - 支持声音克隆 + - 使用官方 SDK,代码简洁 + + 配置示例: + ElevenLabsSDK: + type: elevenlabs_sdk + api_key: your_api_key + voice_id: 21m00Tcm4TlvDq8ikWAM # Rachel voice + model: eleven_multilingual_v2 + output_format: pcm_16000 + stability: 0.5 + similarity_boost: 0.75 + style: 0.0 + use_speaker_boost: true + output_dir: tmp/ + """ + + def __init__(self, config: dict, delete_audio_file: bool = True): + super().__init__(config, delete_audio_file) + + # 标记为单流式接口 + self.interface_type = InterfaceType.SINGLE_STREAM + # 设置音频文件类型为 MP3 + self.audio_file_type = "pcm" + + # 获取 API Key + self.api_key = config.get("api_key") or os.environ.get("ELEVEN_API_KEY") + if not self.api_key: + raise ValueError( + "ElevenLabs API key is required. " + "Provide via api_key in config or set ELEVEN_API_KEY environment variable" + ) + + # Voice 配置 + self.voice_id = config.get("voice_id", "21m00Tcm4TlvDq8ikWAM") # Rachel (default) + + # 模型配置 + self.model = config.get("model", "eleven_multilingual_v2") + + # 音频输出格式 + self.output_format = config.get("output_format", "pcm_16000") + + # Voice Settings + self.stability = config.get("stability", 0.5) + self.similarity_boost = config.get("similarity_boost", 0.75) + self.style = config.get("style", 0.0) + self.use_speaker_boost = config.get("use_speaker_boost", True) + + # 流式延迟优化 (0-4,越大延迟越低但质量可能下降,推荐 2-3) + self.optimize_streaming_latency = config.get("optimize_streaming_latency", 3) + + # 初始化 SDK 客户端 + self.client = ElevenLabs(api_key=self.api_key) + + # 创建 VoiceSettings + self.voice_settings = VoiceSettings( + stability=self.stability, + similarity_boost=self.similarity_boost, + style=self.style, + use_speaker_boost=self.use_speaker_boost + ) + + logger.bind(tag=TAG).info( + f"ElevenLabs SDK initialized: model={self.model}, " + f"voice_id={self.voice_id[:8]}..., " + f"format=mp3_44100" + ) + + async def text_to_speak(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]: + """ + 将文本转换为 MP3 格式音频(完整音频,非流式) + + Args: + text: 要合成的文本 + output_file: 输出文件路径(未使用,保留兼容性) + + Returns: + MP3 格式的完整音频字节数据 + """ + try: + # 使用 SDK 的 convert 方法生成完整音频(返回 generator) + # 强制使用 mp3_44100 格式(忽略配置中的 output_format) + # 因为 base.py 需要完整的音频文件格式(MP3/WAV),而不是原始 PCM + audio_stream = self.client.text_to_speech.convert( + voice_id=self.voice_id, + text=text, + model_id=self.model, + output_format=self.output_format, + voice_settings=self.voice_settings + ) + + # 检查返回类型 + if output_file: + with open(output_file, 'wb') as f: + for chunk in audio_stream: + f.write(chunk) + else: + audio_bytes = b"" + for chunk in audio_stream: + audio_bytes += chunk["data"] + return audio_bytes + + except Exception as e: + logger.bind(tag=TAG).error(f"ElevenLabs TTS failed: {e}", exc_info=True) + raise + + async def close(self): + """清理资源(ElevenLabs SDK 自动管理连接)""" + pass + diff --git a/main/xiaozhi-server/core/providers/tts/fishspeech.py b/main/xiaozhi-server/core/providers/tts/fishspeech.py index 83b3bc3fc..14ff7bd98 100644 --- a/main/xiaozhi-server/core/providers/tts/fishspeech.py +++ b/main/xiaozhi-server/core/providers/tts/fishspeech.py @@ -1,13 +1,12 @@ import base64 -import requests -import ormsgpack from pathlib import Path from pydantic import BaseModel, Field, conint, model_validator from typing_extensions import Annotated from typing import Literal -from core.utils.util import check_model_key, parse_string_to_list +from core.utils.util import parse_string_to_list from core.providers.tts.base import TTSProviderBase from config.logger import setup_logging +from fish_audio_sdk import Session, TTSRequest, ReferenceAudio TAG = __name__ logger = setup_logging() @@ -82,6 +81,7 @@ class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) + self.model = config.get("model", "s1") self.reference_id = ( None if not config.get("reference_id") else config.get("reference_id") ) @@ -91,13 +91,13 @@ class TTSProvider(TTSProviderBase): self.reference_text = parse_string_to_list( config.get('ref_text')if config.get('ref_text') else config.get("reference_text") ) - self.format = config.get("response_format", "wav") - self.audio_file_type = config.get("response_format", "wav") + self.format = config.get("response_format", "pcm") + self.audio_file_type = config.get("response_format", "pcm") self.api_key = config.get("api_key", "YOUR_API_KEY") - model_key_msg = check_model_key("FishSpeech TTS", self.api_key) - if model_key_msg: - logger.bind(tag=TAG).error(model_key_msg) - return + if self.api_key is None: + raise ValueError("FishSpeech API key is required") + self.session = Session(self.api_key) + self.normalize = str(config.get("normalize", True)).lower() in ( "true", "1", @@ -133,56 +133,25 @@ class TTSProvider(TTSProviderBase): ) self.use_memory_cache = config.get("use_memory_cache", "on") self.seed = int(config.get("seed")) if config.get("seed") else None - self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts") async def text_to_speak(self, text, output_file): # Prepare reference data byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio] ref_texts = [read_ref_text(ref_text) for ref_text in self.reference_text] - data = { - "text": text, - "references": [ - ServeReferenceAudio(audio=audio if audio else b"", text=ref_text) - for ref_text, audio in zip(ref_texts, byte_audios) - ], - "reference_id": self.reference_id, - "normalize": self.normalize, - "format": self.format, - "max_new_tokens": self.max_new_tokens, - "chunk_length": self.chunk_length, - "top_p": self.top_p, - "repetition_penalty": self.repetition_penalty, - "temperature": self.temperature, - "streaming": self.streaming, - "use_memory_cache": self.use_memory_cache, - "seed": self.seed, - } - - pydantic_data = ServeTTSRequest(**data) - - response = requests.post( - self.api_url, - data=ormsgpack.packb( - pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC - ), - headers={ - "Authorization": f"Bearer {self.api_key}", - "Content-Type": "application/msgpack", - }, + request = TTSRequest( + text=text, + references=[ReferenceAudio(audio=audio if audio else b"", text=ref_text) for ref_text, audio in zip(ref_texts, byte_audios)], + reference_id=self.reference_id, + sample_rate=self.sample_rate, + format=self.format, + normalize=self.normalize, ) + audio_stream = self.session.tts(request, backend=self.model) + audio_bytes = b''.join(chunk for chunk in audio_stream if chunk) - if response.status_code == 200: - audio_content = response.content - - if output_file: - with open(output_file, "wb") as audio_file: - audio_file.write(audio_content) - else: - return audio_content - + if output_file: + with open(output_file, "wb") as audio_file: + audio_file.write(audio_bytes) else: - error_msg = f"Request failed with status code {response.status_code}" - print(error_msg) - print(response.json()) - raise Exception(error_msg) + return audio_bytes diff --git a/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py b/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py index 514d8912f..a2a8c529c 100644 --- a/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py +++ b/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py @@ -37,8 +37,7 @@ class TTSProvider(TTSProviderBase): } default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]} defult_audio_setting = { - "sample_rate": 24000, - "bitrate": 128000, + "sample_rate": 16000, "format": "pcm", "channel": 1, } @@ -56,8 +55,8 @@ class TTSProvider(TTSProviderBase): if self.voice: self.voice_setting["voice_id"] = self.voice - self.host = "api.minimaxi.com" # 备用地址:api-bj.minimaxi.com - self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}" + self.host = "api.minimax.io" + self.api_url = f"https://{self.host}/v1/t2a_v2" self.header = { "Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}", diff --git a/main/xiaozhi-server/core/providers/tts/test/QUICKSTART.txt b/main/xiaozhi-server/core/providers/tts/test/QUICKSTART.txt new file mode 100644 index 000000000..b6314d515 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/test/QUICKSTART.txt @@ -0,0 +1,79 @@ +TTS Test Quick Start Guide +========================== + +1. Set API Keys (one-time setup) +--------------------------------- + +Add to ~/.zshrc for permanent access: + +echo 'export DEEPGRAM_API_KEY="sk-your-key"' >> ~/.zshrc +echo 'export ELEVENLABS_API_KEY="sk-your-key"' >> ~/.zshrc +echo 'export CARTESIA_API_KEY="your-key"' >> ~/.zshrc +echo 'export MINIMAX_API_KEY="your-key"' >> ~/.zshrc +echo 'export MINIMAX_GROUP_ID="your-group-id"' >> ~/.zshrc + +# FishSpeech +echo 'export FISH_API_KEY="your-key"' >> ~/.zshrc +echo 'export FISH_REFERENCE_ID="reference-id"' >> ~/.zshrc # optional + +source ~/.zshrc + + +2. Run Tests +------------ + +cd /Users/harold/Projects/live-agent/main/xiaozhi-server/ + +# Test Deepgram +python3 -m core.providers.tts.test.test_deepgram + +# Test ElevenLabs +python3 -m core.providers.tts.test.test_elevenlabs + +# Test Cartesia +python3 -m core.providers.tts.test.test_cartesia + +# Test Minimax +python3 -m core.providers.tts.test.test_minimax + +# Test FishSpeech +python3 -m core.providers.tts.test.test_fishspeech + +# Custom text +python3 -m core.providers.tts.test.test_deepgram "你好世界" +python3 -m core.providers.tts.test.test_minimax "你好世界" +python3 -m core.providers.tts.test.test_fishspeech "你好世界" + + +3. Check Output +--------------- + +Generated audio files are in: +core/providers/tts/test/tmp/ + - deepgram_test.wav + - elevenlabs_test.wav + - cartesia_test.wav + - minimax_test.wav + - fishspeech_test.wav + + +4. Troubleshooting +------------------ + +If SDK not installed: + pip install deepgram-sdk elevenlabs cartesia aiohttp fish-audio-sdk + +If API key error: + echo $DEEPGRAM_API_KEY # Check if set + echo $MINIMAX_API_KEY # Check Minimax key + echo $MINIMAX_GROUP_ID # Check Minimax group ID + echo $FISH_API_KEY # Check FishSpeech key + source ~/.zshrc # Reload config + +If module not found: + cd /Users/harold/Projects/live-agent/main/xiaozhi-server/ + # Make sure you're in the right directory! + + +That's it! 🎉 + diff --git a/main/xiaozhi-server/core/providers/tts/test/__init__.py b/main/xiaozhi-server/core/providers/tts/test/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/xiaozhi-server/core/providers/tts/test/test_cartesia.py b/main/xiaozhi-server/core/providers/tts/test/test_cartesia.py new file mode 100644 index 000000000..9d0bc49f7 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/test/test_cartesia.py @@ -0,0 +1,112 @@ +import sys +import asyncio +from io import BytesIO +import wave +import os +import cartesia + +if __name__ == "__main__": + """ + Test for Cartesia TTS + + Usage: + python3 -m core.providers.tts.test_cartesia + python3 -m core.providers.tts.test_cartesia "Custom text" + + Environment: + CARTESIA_API_KEY - Your API key (required) + CARTESIA_VOICE_ID - Voice ID (optional, default: a0e99841-438c-4a64-b679-ae501e7d6091) + CARTESIA_MODEL - Model (optional, default: sonic-english) + """ + + text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of Cartesia text to speech." + + api_key = os.environ.get("CARTESIA_API_KEY") + if not api_key: + print("❌ Error: CARTESIA_API_KEY not set") + print(" export CARTESIA_API_KEY='your-key'") + sys.exit(1) + + # Get configuration from environment + voice_id = os.environ.get("CARTESIA_VOICE_ID", "f9a4b3a6-b44b-469f-90e3-c8e19bd30e99") + model = os.environ.get("CARTESIA_MODEL", "sonic-3") + + print(f"🎙️ Testing Cartesia TTS") + print(f" Model: {model}") + print(f" Voice ID: {voice_id[:16]}...") + print(f" Text: {text}\n") + + # Create Cartesia client + client = cartesia.Cartesia(api_key=api_key) + + try: + print("⏳ Generating audio...") + start = asyncio.get_event_loop().time() + + # Create WebSocket connection + ws = client.tts.websocket() + + # Collect audio chunks + pcm_chunks = [] + + # Send request and receive audio stream + for output in ws.send( + model_id=model, + transcript=text, + voice={ + "mode": "id", + "id": voice_id + }, + stream=True, + output_format={ + "container": "raw", + "encoding": "pcm_s16le", # 16-bit PCM + "sample_rate": 16000 + }, + language="zh" + ): + # Collect PCM audio data + if output and hasattr(output, 'audio') and output.audio: + pcm_chunks.append(output.audio) + + # Merge all PCM chunks + audio_bytes = b''.join(pcm_chunks) + duration = (asyncio.get_event_loop().time() - start) * 1000 + + print(f"✅ Audio generated") + print(f" Duration: {duration:.0f}ms") + print(f" Size: {len(audio_bytes):,} bytes\n") + + # Convert PCM to WAV format + wav_buffer = BytesIO() + + # Open wave file in write mode + with wave.open(wav_buffer, 'wb') as wf: + wf.setnchannels(1) # Mono + wf.setsampwidth(2) # 16-bit (2 bytes) per sample + wf.setframerate(16000) # Sample rate + wf.writeframes(audio_bytes) + + # Save to file + script_dir = os.path.dirname(os.path.abspath(__file__)) + output_file = os.path.join(script_dir, "tmp", "cartesia_test.wav") + with open(output_file, 'wb') as f: + f.write(wav_buffer.getvalue()) + + print(f"💾 Saved to: {output_file}") + print("🔊 Playing audio...") + + # Play audio file + os.system(f"afplay '{output_file}'") + + print("\n✅ Test completed successfully!") + + except Exception as e: + print(f"\n❌ Test failed: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/tts/test/test_deepgram.py b/main/xiaozhi-server/core/providers/tts/test/test_deepgram.py new file mode 100644 index 000000000..92c7ac5ef --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/test/test_deepgram.py @@ -0,0 +1,95 @@ +import sys +import asyncio +from io import BytesIO +import wave +import os +from deepgram import DeepgramClient + +if __name__ == "__main__": + """ + Test for Deepgram TTS + + Usage: + python3 -m core.providers.tts.test_deepgram + python3 -m core.providers.tts.test_deepgram "Custom text" + + Environment: + DEEPGRAM_API_KEY - Your API key (required) + DEEPGRAM_MODEL - Voice model (optional, default: aura-2-thalia-en) + """ + + text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of Deepgram text to speech." + + api_key = os.environ.get("DEEPGRAM_API_KEY") + if not api_key: + print("❌ Error: DEEPGRAM_API_KEY not set") + print(" export DEEPGRAM_API_KEY='your-key'") + sys.exit(1) + + # Get configuration from environment + model = os.environ.get("DEEPGRAM_MODEL", "aura-2-thalia-en") + + print(f"🎙️ Testing Deepgram TTS") + print(f" Model: {model}") + print(f" Text: {text}\n") + + # Create Deepgram client + client = DeepgramClient(api_key=api_key) + + try: + print("⏳ Generating audio...") + start = asyncio.get_event_loop().time() + + # Generate audio using Deepgram SDK + audio_stream = client.speak.v1.audio.generate( + text=text, + model=model, + encoding="linear16", # PCM format + sample_rate=16000, + container="none" # Raw audio + ) + + # Collect audio chunks + audio_bytes = b"" + for chunk in audio_stream: + audio_bytes += chunk + + duration = (asyncio.get_event_loop().time() - start) * 1000 + + print(f"✅ Audio generated") + print(f" Duration: {duration:.0f}ms") + print(f" Size: {len(audio_bytes):,} bytes\n") + + # Convert PCM to WAV format + wav_buffer = BytesIO() + + # Open wave file in write mode + with wave.open(wav_buffer, 'wb') as wf: + wf.setnchannels(1) # Mono + wf.setsampwidth(2) # 16-bit (2 bytes) per sample + wf.setframerate(16000) # Sample rate + wf.writeframes(audio_bytes) + + # Save to file + script_dir = os.path.dirname(os.path.abspath(__file__)) + output_file = os.path.join(script_dir, "tmp", "deepgram_test.wav") + with open(output_file, 'wb') as f: + f.write(wav_buffer.getvalue()) + + print(f"💾 Saved to: {output_file}") + print("🔊 Playing audio...") + + # Play audio file + os.system(f"afplay '{output_file}'") + + print("\n✅ Test completed successfully!") + + except Exception as e: + print(f"\n❌ Test failed: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(1) + diff --git a/main/xiaozhi-server/core/providers/tts/test/test_elevenlabs.py b/main/xiaozhi-server/core/providers/tts/test/test_elevenlabs.py new file mode 100644 index 000000000..39edeab84 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/test/test_elevenlabs.py @@ -0,0 +1,82 @@ +import sys +import asyncio +from io import BytesIO +import wave +import os +from elevenlabs.client import ElevenLabs +from elevenlabs import VoiceSettings + +if __name__ == "__main__": + """ + Test for ElevenLabs TTS + + Usage: + python3 -m core.providers.tts.elevenlabs + python3 -m core.providers.tts.elevenlabs "Custom text" + + Environment: + ELEVENLABS_API_KEY - Your API key (required) + ELEVENLABS_VOICE_ID - Voice ID (optional) + """ + + text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of ElevenLabs text to speech." + + api_key = os.environ.get("ELEVENLABS_API_KEY") + if not api_key: + print("❌ Error: ELEVENLABS_API_KEY not set") + print(" export ELEVENLABS_API_KEY='your-key'") + sys.exit(1) + + # Create minimal provider instance + client = ElevenLabs(api_key=api_key) + voice_id = os.environ.get("ELEVENLABS_VOICE_ID", "EXAVITQu4vr4xnSDxMaL") + voice_settings = VoiceSettings( + stability=0.5, + similarity_boost=0.75, + style=0.0, + use_speaker_boost=True + ) + + try: + + print("⏳ Generating audio...") + start = asyncio.get_event_loop().time() + + # Generate audio + audio_stream = client.text_to_speech.convert( + voice_id=voice_id, + text=text, + model_id="eleven_multilingual_v2", + output_format="pcm_16000", + voice_settings=voice_settings + ) + + # Collect chunks + audio_bytes = b''.join(chunk for chunk in audio_stream if chunk) + duration = (asyncio.get_event_loop().time() - start) * 1000 + + print(f"✅ Audio generated") + print(f" Duration: {duration:.0f}ms") + print(f" Size: {len(audio_bytes):,} bytes\n") + + # Convert to WAV format + wav_buffer = BytesIO() + + # Open wave file in write mode + with wave.open(wav_buffer, 'wb') as wf: + wf.setnchannels(1) # Mono or stereo + wf.setsampwidth(2) # 16-bit (2 bytes) per sample + wf.setframerate(16000) # Sample rate (e.g., 16000 Hz) + wf.writeframes(audio_bytes) + + script_dir = os.path.dirname(os.path.abspath(__file__)) + output_file = os.path.join(script_dir, "tmp", "elevenlabs_test.wav") + + with open(output_file, 'wb') as f: + f.write(wav_buffer.getvalue()) + # here,I want to get a .wav file to play the audio file + os.system(f"afplay '{output_file}'") + + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(1) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/test/test_fishspeech.py b/main/xiaozhi-server/core/providers/tts/test/test_fishspeech.py new file mode 100644 index 000000000..a77c2615d --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/test/test_fishspeech.py @@ -0,0 +1,102 @@ +import sys +import os +from io import BytesIO +import wave +import platform +from fish_audio_sdk import Session, TTSRequest +import asyncio + +if __name__ == "__main__": + """ + Test for FishSpeech TTS + + Usage: + python3 -m core.providers.tts.test.test_fishspeech + python3 -m core.providers.tts.test.test_fishspeech "Custom text" + + Environment: + FISH_API_KEY - Your Fish.Audio API key (required) + FISH_REFERENCE_ID - Voice reference ID (optional) + + Examples: + export FISH_API_KEY="your-key" + python3 -m core.providers.tts.test.test_fishspeech "Hello world" + + # With custom voice + export FISH_REFERENCE_ID="7f92f8afb8ec43bf81429cc1c9199cb1" + python3 -m core.providers.tts.test.test_fishspeech "Hello world" + """ + + text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of FishSpeech text to speech." + + api_key = os.environ.get("FISH_API_KEY") + if not api_key: + print("❌ Error: FISH_API_KEY not set") + print(" export FISH_API_KEY='your-key'") + print("\n💡 Get your API key from: https://fish.audio/") + sys.exit(1) + + # default reference id is Donald Trump + reference_id = os.environ.get("FISH_REFERENCE_ID", "5196af35f6ff4a0dbf541793fc9f2157") + + print(f"🐟 FishSpeech TTS Test") + print(f" API: https://api.fish.audio") + if reference_id: + print(f" Reference ID: {reference_id}") + print(f" Text: {text[:50]}{'...' if len(text) > 50 else ''}\n") + + try: + print("⏳ Generating audio...") + start = asyncio.get_event_loop().time() + + # Create session + session = Session(api_key) + + # Prepare TTS request + tts_request = TTSRequest( + text=text, + reference_id=reference_id, + format="pcm", + normalize=True, + sample_rate=16000, + ) + + # Generate audio + audio_stream = session.tts(tts_request, backend="s1") + duration = (asyncio.get_event_loop().time() - start) * 1000 + + audio_bytes = b''.join(chunk for chunk in audio_stream if chunk) + + print(f"✅ Audio generated") + print(f" Duration: {duration:.0f}ms") + + # Convert to WAV format + wav_buffer = BytesIO() + + # Open wave file in write mode + with wave.open(wav_buffer, 'wb') as wf: + wf.setnchannels(1) # Mono or stereo + wf.setsampwidth(2) # 16-bit (2 bytes) per sample + wf.setframerate(16000) # Sample rate (e.g., 16000 Hz) + wf.writeframes(audio_bytes) + + # Save to file + script_dir = os.path.dirname(os.path.abspath(__file__)) + output_file = os.path.join(script_dir, "tmp", "fish_test.wav") + + os.makedirs(os.path.dirname(output_file), exist_ok=True) + with open(output_file, 'wb') as f: + f.write(wav_buffer.getvalue()) + + os.system(f"afplay '{output_file}'") + + print("\n✅ Test completed successfully!") + + except Exception as e: + print(f"❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(1) diff --git a/main/xiaozhi-server/core/providers/tts/test/test_minimax.py b/main/xiaozhi-server/core/providers/tts/test/test_minimax.py new file mode 100644 index 000000000..7e8fb4dba --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/test/test_minimax.py @@ -0,0 +1,208 @@ +import sys +import asyncio +import json +from io import BytesIO +import wave +import os +import platform +import aiohttp + +if __name__ == "__main__": + """ + Test for Minimax TTS + + Usage: + python3 -m core.providers.tts.test.test_minimax + python3 -m core.providers.tts.test.test_minimax "Custom text" + + Environment: + MINIMAX_API_KEY - Your API key (required) + MINIMAX_GROUP_ID - Your Group ID (required) + MINIMAX_MODEL - Model name (optional, default: speech-01-turbo) + MINIMAX_VOICE_ID - Voice ID (optional, default: female-shaonv) + """ + + text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of Minimax text to speech." + + # Check required environment variables + api_key = os.environ.get("MINIMAX_API_KEY") + group_id = os.environ.get("MINIMAX_GROUP_ID") + + if not api_key: + print("❌ Error: MINIMAX_API_KEY not set") + print(" export MINIMAX_API_KEY='your-key'") + sys.exit(1) + + if not group_id: + print("❌ Error: MINIMAX_GROUP_ID not set") + print(" export MINIMAX_GROUP_ID='your-group-id'") + sys.exit(1) + + # Optional parameters + model = os.environ.get("MINIMAX_MODEL", "speech-2.6-hd") + voice_id = os.environ.get("MINIMAX_VOICE_ID", "English_Graceful_Lady") + + # Configuration + host = "api.minimax.io" + api_url = f"https://{host}/v1/t2a_v2" + + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {api_key}", + } + + payload = { + "model": model, + "text": text, + "stream": True, + "voice_setting": { + "voice_id": voice_id, + "speed": 1.0, + "vol": 1.0, + "pitch": 0, + "emotion": "happy", + }, + "pronunciation_dict": { + "tone": [] + }, + "audio_setting": { + "sample_rate": 16000, + "format": "pcm", + "channel": 1, + } + } + + async def test(): + try: + print(f"⏳ Generating audio with Minimax TTS...") + print(f" Model: {model}") + print(f" Voice: {voice_id}") + print(f" Text: {text[:50]}{'...' if len(text) > 50 else ''}\n") + + start_time = asyncio.get_event_loop().time() + pcm_chunks = [] + + async with aiohttp.ClientSession() as session: + async with session.post( + api_url, + headers=headers, + data=json.dumps(payload), + timeout=aiohttp.ClientTimeout(total=30), + ) as resp: + + if resp.status != 200: + error_text = await resp.text() + print(f"❌ API Error: {resp.status}") + print(f" Response: {error_text}") + sys.exit(1) + + # Process streaming audio data + buffer = b"" + async for chunk in resp.content.iter_any(): + if not chunk: + continue + + buffer += chunk + + # Parse SSE (Server-Sent Events) format + while True: + # Find data chunk separator + header_pos = buffer.find(b"data: ") + if header_pos == -1: + break + + end_pos = buffer.find(b"\n\n", header_pos) + if end_pos == -1: + break + + # Extract single complete JSON block + json_str = buffer[header_pos + 6 : end_pos].decode("utf-8") + buffer = buffer[end_pos + 2 :] + + try: + data = json.loads(json_str) + status = data.get("data", {}).get("status", 1) + audio_hex = data.get("data", {}).get("audio") + + # Only process status=1 valid audio chunks + # Ignore status=2 end summary chunks + if status == 1 and audio_hex: + # Decode hex string to PCM bytes + audio_bytes = bytes.fromhex(audio_hex) + pcm_chunks.append(audio_bytes) + elif status == 2: + # End of stream + break + except json.JSONDecodeError as e: + print(f"⚠️ Warning: Failed to parse JSON: {e}") + continue + + duration = (asyncio.get_event_loop().time() - start_time) * 1000 + + # Combine all PCM chunks + pcm_data = b''.join(pcm_chunks) + + if not pcm_data: + print("❌ Error: No audio data received") + sys.exit(1) + + print(f"✅ Audio generated") + print(f" Duration: {duration:.0f}ms") + print(f" Size: {len(pcm_data):,} bytes") + print(f" Chunks: {len(pcm_chunks)}\n") + + # Convert PCM to WAV format + wav_buffer = BytesIO() + with wave.open(wav_buffer, 'wb') as wf: + wf.setnchannels(1) # Mono + wf.setsampwidth(2) # 16-bit (2 bytes) per sample + wf.setframerate(24000) # Sample rate: 24000 Hz + wf.writeframes(pcm_data) + + # Save to file + script_dir = os.path.dirname(os.path.abspath(__file__)) + output_file = os.path.join(script_dir, "tmp", "minimax_test.wav") + + # Create tmp directory if not exists + os.makedirs(os.path.dirname(output_file), exist_ok=True) + + with open(output_file, 'wb') as f: + f.write(wav_buffer.getvalue()) + + print(f"💾 Saved to: {output_file}\n") + print("🔊 Playing audio...") + + # Play audio (platform-specific) + system = platform.system() + if system == "Darwin": # macOS + os.system(f"afplay '{output_file}'") + elif system == "Linux": + # Try common Linux audio players + if os.system("which aplay > /dev/null 2>&1") == 0: + os.system(f"aplay '{output_file}'") + elif os.system("which ffplay > /dev/null 2>&1") == 0: + os.system(f"ffplay -nodisp -autoexit '{output_file}' 2>/dev/null") + else: + print("⚠️ No audio player found (aplay/ffplay)") + elif system == "Windows": + os.system(f'start {output_file}') + else: + print(f"⚠️ Unsupported platform: {system}") + + print("\n✅ Test completed successfully!") + + except aiohttp.ClientError as e: + print(f"❌ Network error: {e}") + sys.exit(1) + except KeyboardInterrupt: + print("\n\n👋 Test interrupted") + sys.exit(1) + except Exception as e: + print(f"❌ Unexpected error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + + # Run the async test + asyncio.run(test()) + diff --git a/main/xiaozhi-server/core/roles/__init__.py b/main/xiaozhi-server/core/roles/__init__.py new file mode 100644 index 000000000..a9cde607b --- /dev/null +++ b/main/xiaozhi-server/core/roles/__init__.py @@ -0,0 +1,14 @@ +"""Role configuration system for AI agents.""" + +from .models import RoleConfig, TTSConfig +from .factory import RoleConfigLoader, get_role_config_loader +from .local_loader import LocalRoleConfigLoader + +__all__ = [ + "RoleConfig", + "TTSConfig", + "RoleConfigLoader", + "LocalRoleConfigLoader", + "get_role_config_loader", +] + diff --git a/main/xiaozhi-server/core/roles/data/default.yaml b/main/xiaozhi-server/core/roles/data/default.yaml new file mode 100644 index 000000000..60ad956a3 --- /dev/null +++ b/main/xiaozhi-server/core/roles/data/default.yaml @@ -0,0 +1,66 @@ +id: default +version: 4 +wake_word: Alice +language: en +# greeting: 你好!今天有什么可以帮助你的吗? +greeting: Hi! How can I help you today? +profile: | + # Personality + + You are a personal assistant designed to help users manage their daily hospital-related tasks. + You are efficient, organized, and detail-oriented. + You are friendly and helpful, but primarily focused on task completion. + + # Environment + + You are assisting the user via voice interaction. + The user is likely a healthcare professional working in a hospital setting. + The user is seeking assistance with their daily tasks. + + # Tone + + Your responses are clear, concise, and professional. + You use direct language and avoid unnecessary jargon. + You are polite and helpful, but prioritize efficiency. + + # Goal + + Your primary goal is to help the user efficiently process their daily hospital tasks through a structured workflow: + + 1. Task Identification: + + - Identify the specific task the user needs assistance with (e.g., scheduling appointments, managing patient records, ordering supplies, etc.). + - Clarify any specific requirements or constraints for the task. + + 2. Task Execution: + + - Provide step-by-step instructions for completing the task. + - Offer helpful tips and shortcuts to improve efficiency. + - If possible, automate parts of the task using available tools. + + 3. Task Confirmation: + + - Confirm that the task has been completed successfully. + - Offer to assist with any follow-up tasks or related activities. + + 4. Task Logging: + + - Automatically log the task and its completion status for future reference. + + # Guardrails + + Remain within the scope of hospital-related tasks. + Never provide medical advice or make clinical decisions. + Protect patient privacy and confidentiality at all times. + If you are unsure about something, ask for clarification. + + # Tools + + No tools provided. +#tts: +# voice_id: 7a5d4663-88ae-47b7-808e-8f9b9ee4127b +# provider: cartesia +tts: + voice_id: ByhETIclHirOlWnWKhHc + provider: elevenlabs +timezone: Asia/Shanghai diff --git a/main/xiaozhi-server/core/roles/data/hospital_assistant.yaml b/main/xiaozhi-server/core/roles/data/hospital_assistant.yaml new file mode 100644 index 000000000..0988ed7ab --- /dev/null +++ b/main/xiaozhi-server/core/roles/data/hospital_assistant.yaml @@ -0,0 +1,66 @@ +id: hospital_assistant +version: 4 +wake_word: Alice +language: en +# greeting: 你好!今天有什么可以帮助你的吗? +greeting: Hi! How can I help you today? +profile: | + # Personality + + You are a personal assistant designed to help users manage their daily hospital-related tasks. + You are efficient, organized, and detail-oriented. + You are friendly and helpful, but primarily focused on task completion. + + # Environment + + You are assisting the user via voice interaction. + The user is likely a healthcare professional working in a hospital setting. + The user is seeking assistance with their daily tasks. + + # Tone + + Your responses are clear, concise, and professional. + You use direct language and avoid unnecessary jargon. + You are polite and helpful, but prioritize efficiency. + + # Goal + + Your primary goal is to help the user efficiently process their daily hospital tasks through a structured workflow: + + 1. Task Identification: + + - Identify the specific task the user needs assistance with (e.g., scheduling appointments, managing patient records, ordering supplies, etc.). + - Clarify any specific requirements or constraints for the task. + + 2. Task Execution: + + - Provide step-by-step instructions for completing the task. + - Offer helpful tips and shortcuts to improve efficiency. + - If possible, automate parts of the task using available tools. + + 3. Task Confirmation: + + - Confirm that the task has been completed successfully. + - Offer to assist with any follow-up tasks or related activities. + + 4. Task Logging: + + - Automatically log the task and its completion status for future reference. + + # Guardrails + + Remain within the scope of hospital-related tasks. + Never provide medical advice or make clinical decisions. + Protect patient privacy and confidentiality at all times. + If you are unsure about something, ask for clarification. + + # Tools + + No tools provided. +# tts: +# voice_id: 7a5d4663-88ae-47b7-808e-8f9b9ee4127b +# provider: cartesia +tts: + voice_id: f786b574-daa5-4673-aa0c-cbe3e8534c02 + provider: elevenlabs +timezone: Asia/Shanghai diff --git a/main/xiaozhi-server/core/roles/factory.py b/main/xiaozhi-server/core/roles/factory.py new file mode 100644 index 000000000..0189668ff --- /dev/null +++ b/main/xiaozhi-server/core/roles/factory.py @@ -0,0 +1,70 @@ +"""Role configuration loader factory and abstract base class. + +This module provides the abstract interface for role configuration loaders +and a factory function to instantiate the appropriate loader based on +environment configuration. +""" + +from __future__ import annotations + +import os +from abc import ABC, abstractmethod +from config.logger import setup_logging + +from core.roles.models import RoleConfig + +TAG = __name__ +logger = setup_logging() + + +class RoleConfigLoader(ABC): + """Abstract base class for role configuration loaders. + + Different storage backends (local, S3) should implement this interface. + """ + + @abstractmethod + def load(self, role_id: str) -> RoleConfig: + """Load a role configuration by its ID. + + Args: + role_id: The unique identifier of the role to load. + + Returns: + RoleConfig: The loaded role configuration. + + Raises: + FileNotFoundError: If the role configuration is not found. + ValueError: If the role configuration is invalid. + """ + pass + + +def get_role_config_loader() -> RoleConfigLoader: + """Factory function to get the appropriate role configuration loader. + + The loader type is determined by the CONFIG_STORAGE_TYPE environment variable: + - "local" (default): Load from local filesystem + + Returns: + RoleConfigLoader: An instance of the appropriate loader. + + Raises: + ValueError: If an unsupported storage type is specified. + + Environment Variables: + CONFIG_STORAGE_TYPE: Type of storage backend (currently only "local" is supported) + """ + storage_type = os.getenv("CONFIG_STORAGE_TYPE", "local") + + logger.bind(tag=TAG).debug(f"Creating role config loader for storage type: {storage_type}") + + if storage_type == "local": + from .local_loader import LocalRoleConfigLoader + return LocalRoleConfigLoader() + else: + raise ValueError( + f"Unsupported storage type: {storage_type}. " + f"Currently only 'local' is supported" + ) + diff --git a/main/xiaozhi-server/core/roles/local_loader.py b/main/xiaozhi-server/core/roles/local_loader.py new file mode 100644 index 000000000..ba92ff402 --- /dev/null +++ b/main/xiaozhi-server/core/roles/local_loader.py @@ -0,0 +1,108 @@ +"""Local filesystem role configuration loader implementation.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Optional + +from ruamel.yaml import YAML +from config.logger import setup_logging + +from core.roles.models import RoleConfig, TTSConfig +from core.roles.factory import RoleConfigLoader + +TAG = __name__ +logger = setup_logging() + + +class LocalRoleConfigLoader(RoleConfigLoader): + """Local filesystem role configuration loader. + + Loads role configurations from YAML files in a local directory. + """ + + def __init__(self, base_path: Optional[Path] = None): + """Initialize the local loader. + + Args: + base_path: Base directory containing role YAML files. + Defaults to core/roles/data/ relative to this file. + """ + if base_path is None: + base_path = Path(__file__).resolve().parent / "data" + + self.base_path = Path(base_path) + logger.bind(tag=TAG).debug(f"Initialized LocalRoleConfigLoader with base_path: {self.base_path}") + + def load(self, role_id: str) -> RoleConfig: + """Load a role configuration from a local YAML file. + + Args: + role_id: The unique identifier of the role (matches the YAML filename). + + Returns: + RoleConfig: The loaded role configuration. + + Raises: + FileNotFoundError: If the YAML file is not found. + ValueError: If the YAML file is invalid or missing required fields. + """ + yaml_path = self.base_path / f"{role_id}.yaml" + + if not yaml_path.is_file(): + raise FileNotFoundError(f"Role configuration not found: {yaml_path}") + + logger.bind(tag=TAG).debug(f"Loading role configuration from: {yaml_path}") + + try: + yaml = YAML() + yaml.preserve_quotes = True + with yaml_path.open("r", encoding="utf-8") as f: + data = yaml.load(f) + + if not data: + raise ValueError(f"Empty or invalid YAML file: {yaml_path}") + + logger.bind(tag=TAG).debug(f"Loaded YAML data: {data}") + + # Parse TTS configuration (optional) + tts_config = None + tts_data = data.get("tts", {}) + if tts_data and isinstance(tts_data, dict): + tts_config = TTSConfig( + voice_id=tts_data["voice_id"], + provider=tts_data["provider"] + ) + + # Parse language with default + language = data.get("language", "zh") + + # Parse timezone with default + timezone = data.get("timezone", "Asia/Shanghai") + + # Parse greeting with default + greeting = data.get("greeting", "你好!有什么可以帮助你的吗?") + + # Parse wake_word with default + wake_word = data.get("wake_word", "小智") + + # Create RoleConfig + role_config = RoleConfig( + id=data["id"], + version=int(data["version"]), + wake_word=wake_word, + language=language, + greeting=greeting, + profile=data["profile"], + timezone=timezone, + tts=tts_config, + ) + + logger.bind(tag=TAG).info(f"Successfully loaded role configuration: {role_id}") + return role_config + + except KeyError as e: + raise ValueError(f"Missing required field in role configuration: {e}") from e + except Exception as e: + raise ValueError(f"Failed to parse YAML file {yaml_path}: {e}") from e + diff --git a/main/xiaozhi-server/core/roles/models.py b/main/xiaozhi-server/core/roles/models.py new file mode 100644 index 000000000..42a0b65af --- /dev/null +++ b/main/xiaozhi-server/core/roles/models.py @@ -0,0 +1,39 @@ +"""Role configuration data models.""" + +from __future__ import annotations + +from typing import Optional, Literal + +from pydantic import BaseModel, Field + + +class TTSConfig(BaseModel): + """TTS (Text-to-Speech) configuration.""" + + voice_id: str + provider: str + + +class RoleConfig(BaseModel): + """Configuration model for an agent role. + + This model defines the complete configuration for an agent role, + including wake word, profile, language preferences, and TTS settings. + """ + + id: str + version: int + wake_word: str = Field(default="小智") + language: Literal["en", "zh"] = Field(default="zh") + greeting: str = Field( + default="你好!有什么可以帮助你的吗?", + description="Initial greeting message when the agent joins" + ) + profile: str = Field( + description="Custom profile content defined by user, including Personality, Environment, Tone, Goal, Guardrails, and Tools" + ) + timezone: str = Field( + default="Asia/Shanghai", + description="Timezone for the agent (e.g., 'Asia/Tokyo', 'America/New_York')" + ) + tts: Optional[TTSConfig] = None diff --git a/main/xiaozhi-server/core/roles/prompts/__init__.py b/main/xiaozhi-server/core/roles/prompts/__init__.py new file mode 100644 index 000000000..1997018bd --- /dev/null +++ b/main/xiaozhi-server/core/roles/prompts/__init__.py @@ -0,0 +1,5 @@ +"""模块化提示词构建模块""" + +from .builder import build_system_prompt, build_user_persona_prompt + +__all__ = ["build_system_prompt", "build_user_persona_prompt"] diff --git a/main/xiaozhi-server/core/roles/prompts/builder.py b/main/xiaozhi-server/core/roles/prompts/builder.py new file mode 100644 index 000000000..f5f4e444d --- /dev/null +++ b/main/xiaozhi-server/core/roles/prompts/builder.py @@ -0,0 +1,191 @@ +""" +模块化系统提示词构建器 +负责构建完整的系统提示词,包括 Profile、System Context、User Persona 等模块 +""" + +from datetime import datetime +from pathlib import Path +from typing import Dict, Optional +from zoneinfo import ZoneInfo +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + +# 加载模板文件 +_ROLE_TPL = Path(__file__).resolve().parent / "role.md" +_USER_PERSONA_TPL = Path(__file__).resolve().parent / "user_persona.md" +_LANG_DIR = Path(__file__).resolve().parent / "languages" + +ROLE_TEXT = _ROLE_TPL.read_text(encoding="utf-8") +USER_PERSONA_TEXT = _USER_PERSONA_TPL.read_text(encoding="utf-8") + +LANG_MAP: Dict[str, str] = {} +for p in _LANG_DIR.glob("*.md"): + LANG_MAP[p.stem] = p.read_text(encoding="utf-8") + +# 星期几中英文映射 +WEEKDAY_MAP = { + "Monday": "星期一", + "Tuesday": "星期二", + "Wednesday": "星期三", + "Thursday": "星期四", + "Friday": "星期五", + "Saturday": "星期六", + "Sunday": "星期日", +} + + +def _build_system_context( + timezone: str, + language: str, + today_date: Optional[str] = None, + today_weekday: Optional[str] = None, + lunar_date: Optional[str] = None, + local_address: Optional[str] = None, + weather_info: Optional[str] = None, + device_id: Optional[str] = None, +) -> str: + """构建系统上下文部分(时间、时区、语言、位置、天气等) + + Args: + timezone: 时区字符串(如 'Asia/Shanghai', 'America/New_York') + language: 语言代码('zh' 或 'en') + today_date: 今天日期(可选,如未提供则自动计算) + today_weekday: 今天星期几(可选,如未提供则自动计算) + lunar_date: 今天农历(可选) + local_address: 用户所在城市(可选) + weather_info: 天气信息(可选) + device_id: 设备ID(可选) + + Returns: + 格式化的系统上下文字符串 + """ + # TODO: Here, we need to use the client ip to figure out the timezone + try: + tz = ZoneInfo(timezone) + except Exception: + tz = ZoneInfo("UTC") + timezone = "UTC" + logger.bind(tag=TAG).warning(f"无效的时区配置: {timezone},使用 UTC") + + now = datetime.now(tz) + + # 如果未提供日期信息,则自动计算 + if not today_date: + day = now.strftime("%d") + month = now.strftime("%B") + year = now.strftime("%Y") + today_date = f"{day} {month} {year}" + + if not today_weekday: + day_of_week = now.strftime("%A") + if language == "zh": + today_weekday = WEEKDAY_MAP.get(day_of_week, day_of_week) + else: + today_weekday = day_of_week + + # 格式化时间 + time_str = now.strftime("%H:%M") + + # 构建系统上下文规则 + system_rules = [] + + formatted_datetime = f"{now.strftime('%A')}, {time_str} {today_date} ({timezone})" + system_rules.append(f"- The user started this conversation on {formatted_datetime}") + if local_address: + system_rules.append(f"- User location: {local_address}") + if weather_info: + system_rules.append(f"- Local weather forecast: {weather_info}") + if device_id: + system_rules.append(f"- Device ID: {device_id}") + system_rules.append(f"- Your current language is: **{language}**") + + return "\n".join(system_rules) + + +def build_user_persona_prompt(user_persona: str) -> str: + """构建用户画像提示词 + + Args: + user_persona: 用户画像信息(通常是从 memory 模块获取的要点列表) + + Returns: + 格式化后的用户画像提示词字符串 + """ + if not user_persona: + return "" + + return USER_PERSONA_TEXT.format(user_persona=user_persona.strip()) + + +def build_system_prompt( + profile: str, + timezone: str = "Asia/Shanghai", + language: str = "zh", + user_persona: Optional[str] = None, + today_date: Optional[str] = None, + today_weekday: Optional[str] = None, + lunar_date: Optional[str] = None, + local_address: Optional[str] = None, + weather_info: Optional[str] = None, + device_id: Optional[str] = None, + **kwargs +) -> str: + """构建完整的系统提示词 + + Args: + profile: 用户自定义的角色配置(从 config.yaml 的 prompt 字段获取) + timezone: 时区字符串(如 'Asia/Shanghai', 'America/New_York'),默认 'Asia/Shanghai' + language: 语言代码('zh' 或 'en'),默认 'zh' + user_persona: 可选的用户画像信息(从 memory 模块获取) + today_date: 今天日期(可选,如未提供则自动计算) + today_weekday: 今天星期几(可选,如未提供则自动计算) + lunar_date: 今天农历(可选) + local_address: 用户所在城市(可选) + weather_info: 天气信息(可选) + device_id: 设备ID(可选) + **kwargs: 其他参数(用于兼容性) + + Returns: + 完整的系统提示词字符串 + """ + # Step 1: Profile 内容 + profile_content = profile + + # Step 2: 构建系统上下文 + system_context = _build_system_context( + timezone=timezone, + language=language, + today_date=today_date, + today_weekday=today_weekday, + lunar_date=lunar_date, + local_address=local_address, + weather_info=weather_info, + device_id=device_id, + ) + + # Step 3: 构建用户画像部分(可选) + user_persona_prompt = "" + if user_persona: + user_persona_prompt = build_user_persona_prompt(user_persona) + + # Step 4: 获取语言特定提示 + language_specific_prompt = LANG_MAP.get(language, "") + + # Step 6: 填充主模板 + template_vars = { + "profile": profile, + "system_context": system_context, + "user_persona_prompt": user_persona_prompt, + "language_specific_prompt": language_specific_prompt + } + + # Step 7: 填充模板(不包含 profile) + try: + system_prompt= ROLE_TEXT.format(**template_vars) + except KeyError as e: + logger.bind(tag=TAG).error(f"模板变量缺失: {e}") + system_prompt = profile_content + + return system_prompt diff --git a/main/xiaozhi-server/core/roles/prompts/languages/en.md b/main/xiaozhi-server/core/roles/prompts/languages/en.md new file mode 100644 index 000000000..01682cd7f --- /dev/null +++ b/main/xiaozhi-server/core/roles/prompts/languages/en.md @@ -0,0 +1,5 @@ +### English Expression Tips + +For more natural and conversational English: +- Use contractions naturally (e.g., "don't", "won't", "it's") for a friendlier tone +- Prefer colloquial time expressions when appropriate (e.g., "half past three", "quarter to five") diff --git a/main/xiaozhi-server/core/roles/prompts/languages/zh.md b/main/xiaozhi-server/core/roles/prompts/languages/zh.md new file mode 100644 index 000000000..7668d682d --- /dev/null +++ b/main/xiaozhi-server/core/roles/prompts/languages/zh.md @@ -0,0 +1,6 @@ +### Chinese Expression Tips + +For more natural and idiomatic Chinese: +- Prefer "两点" over "二点" when saying "2 o'clock" +- Avoid mixing "今天" and "今日" in the same response; choose one and stay consistent +- When mixing Chinese and English, maintain one half-width space between them (e.g., "我使用 GitHub 开发") diff --git a/main/xiaozhi-server/core/roles/prompts/role.md b/main/xiaozhi-server/core/roles/prompts/role.md new file mode 100644 index 000000000..35694f665 --- /dev/null +++ b/main/xiaozhi-server/core/roles/prompts/role.md @@ -0,0 +1,42 @@ +{profile} +# System Context +{system_context} + +{user_persona_prompt} + +# Response Guidelines for Voice Conversation + +## Content Quality +- Responses must be conversational, natural, and clear for spoken delivery +- Keep sentences concise and well-structured for easy listening +- When presenting multiple points, organize them clearly with appropriate structure +- Avoid repetitive expressions; keep responses focused and relevant +- Must not include logs, timestamps, system information, placeholders, or any internal markers + +## Text Formatting for Speech Synthesis + +**CRITICAL**: All output must be formatted for natural speech, not machine reading. Consider your current language when formatting. + +**Common Mistakes to Avoid**: +- **Dates**: `YYYY-MM-DD`, `MM/DD/YYYY`, `2025-10-15` → Use natural spoken form appropriate for your language +- **Times**: `HH:MM`, `09:30-10:00`, `14:00` → Use conversational expressions appropriate for your language +- **Phone/Room/IDs**: Long numbers → Read digit by digit in your language +- **URLs**: `example.com` → Use "dot" (e.g., "example dot com") + +**Formatting for Better Prosody**: +- When mixing different languages or scripts, maintain appropriate spacing for natural rhythm +- Use proper spacing with time indicators (e.g., "7:00 PM" not "7:00PM") + +When in doubt, ask yourself: "Would a human naturally say this in conversation?" + +{language_specific_prompt} + +## Accuracy and Authenticity +- When information is missing or uncertain, acknowledge rather than fabricate +- Do not output unnecessary disclaimers or pleasantries that interrupt conversation flow + +# Privacy & Ethics +- Protect user privacy and confidentiality at all times +- Handle sensitive information with appropriate care +- Follow ethical guidelines and legal requirements +- Refuse harmful, illegal, or inappropriate requests politely diff --git a/main/xiaozhi-server/core/roles/prompts/user_persona.md b/main/xiaozhi-server/core/roles/prompts/user_persona.md new file mode 100644 index 000000000..73229c450 --- /dev/null +++ b/main/xiaozhi-server/core/roles/prompts/user_persona.md @@ -0,0 +1,14 @@ +## User Persona + +Here is what we know about the user you're talking with: + +{user_persona} + +## How to Use This Information + +- **Fine-tune Your Expression**: While maintaining your core personality and tone, adjust your expression style to better resonate with this user +- **Contextual Relevance**: Reference relevant persona details naturally when they enhance the conversation +- **Personalized Responses**: Consider the user's background, preferences, and context when crafting responses +- **Continuity**: Use this information to maintain coherent and contextually aware conversations + +**Important**: This persona represents learned knowledge about the user. Let it naturally inform your responses while staying true to your core role and communication approach. diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py index f135d930b..eb55bfa19 100644 --- a/main/xiaozhi-server/core/utils/dialogue.py +++ b/main/xiaozhi-server/core/utils/dialogue.py @@ -71,12 +71,8 @@ class Dialogue: ) if system_message: - # 基础系统提示 + # 基础系统提示(新架构已处理时间信息,无需替换 {{current_time}}) enhanced_system_prompt = system_message.content - # 替换时间占位符 - enhanced_system_prompt = enhanced_system_prompt.replace( - "{{current_time}}", datetime.now().strftime("%H:%M") - ) # 添加说话人个性化描述 try: diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py index 1e247d075..0775d086f 100644 --- a/main/xiaozhi-server/core/utils/prompt_manager.py +++ b/main/xiaozhi-server/core/utils/prompt_manager.py @@ -1,13 +1,12 @@ """ 系统提示词管理器模块 负责管理和更新系统提示词,包括快速初始化和异步增强功能 +使用新的模块化架构构建系统提示词 """ import os -import cnlunar -from typing import Dict, Any +from typing import Dict, Any, Optional from config.logger import setup_logging -from jinja2 import Template TAG = __name__ @@ -52,7 +51,6 @@ class PromptManager: def __init__(self, config: Dict[str, Any], logger=None): self.config = config self.logger = logger or setup_logging() - self.base_prompt_template = None self.last_update_time = 0 # 导入全局缓存管理器 @@ -61,37 +59,6 @@ class PromptManager: self.cache_manager = cache_manager self.CacheType = CacheType - self._load_base_template() - - def _load_base_template(self): - """加载基础提示词模板""" - try: - template_path = self.config.get("prompt_template", "agent-base-prompt.txt") - cache_key = f"prompt_template:{template_path}" - - # 先从缓存获取 - cached_template = self.cache_manager.get(self.CacheType.CONFIG, cache_key) - if cached_template is not None: - self.base_prompt_template = cached_template - self.logger.bind(tag=TAG).debug("从缓存加载基础提示词模板") - return - - # 缓存未命中,从文件读取 - if os.path.exists(template_path): - with open(template_path, "r", encoding="utf-8") as f: - template_content = f.read() - - # 存入缓存(CONFIG类型默认不自动过期,需要手动失效) - self.cache_manager.set( - self.CacheType.CONFIG, cache_key, template_content - ) - self.base_prompt_template = template_content - self.logger.bind(tag=TAG).debug("成功加载基础提示词模板并缓存") - else: - self.logger.bind(tag=TAG).warning(f"未找到{template_path}文件") - except Exception as e: - self.logger.bind(tag=TAG).error(f"加载提示词模板失败: {e}") - def get_quick_prompt(self, user_prompt: str, device_id: str = None) -> str: """快速获取系统提示词(使用用户配置)""" device_cache_key = f"device_prompt:{device_id}" @@ -184,17 +151,59 @@ class PromptManager: self.logger.bind(tag=TAG).error(f"更新上下文信息失败: {e}") def build_enhanced_prompt( - self, user_prompt: str, device_id: str, client_ip: str = None, *args, **kwargs + self, + user_prompt: str, + device_id: str, + client_ip: str = None, + user_persona: str = None, + *args, + **kwargs ) -> str: - """构建增强的系统提示词""" - if not self.base_prompt_template: - return user_prompt - + """构建增强的系统提示词(使用新的模块化架构)""" try: + from core.roles.prompts.builder import build_system_prompt + from core.roles import get_role_config_loader + + # 优先级:API 传入的 user_prompt > 本地 role 配置 > 空字符串 + role_tts_config = None # 保存 role 的 TTS 配置供后续使用 + if user_prompt and user_prompt.strip(): + # 优先使用 API 传入的 prompt(正式部署场景) + profile = user_prompt + timezone = self.config.get("timezone", "Asia/Shanghai") + language = self.config.get("language", "zh") + self.logger.bind(tag=TAG).info("使用 API 下发的 profile") + else: + # API 未提供 prompt,尝试加载本地 role 配置(本地开发场景) + role_id = self.config.get("role_id", "default") + loader = get_role_config_loader() + + try: + role_config = loader.load(role_id) + profile = role_config.profile + timezone = role_config.timezone + language = role_config.language + # 提取 TTS 配置(如果有) + if role_config.tts: + role_tts_config = { + "voice_id": role_config.tts.voice_id, + "provider": role_config.tts.provider + } + self.logger.bind(tag=TAG).info( + f"检测到 Role TTS 配置: provider={role_config.tts.provider}, " + f"voice_id={role_config.tts.voice_id[:16]}..." + ) + self.logger.bind(tag=TAG).info(f"使用本地 role 配置: {role_id}") + except Exception as e: + # 兜底方案:使用空 profile + self.logger.bind(tag=TAG).warning(f"加载 role 配置失败: {e},使用空 profile") + profile = "" + timezone = self.config.get("timezone", "Asia/Shanghai") + language = self.config.get("language", "zh") + # 获取最新的时间信息(不缓存) - today_date, today_weekday, lunar_date = ( - self._get_current_time_info() - ) + today_date, today_weekday, lunar_date = self._get_current_time_info() + # 清理 lunar_date 的换行符 + lunar_date = lunar_date.strip() if lunar_date else None # 获取缓存的上下文信息 local_address = "" @@ -213,30 +222,34 @@ class PromptManager: or "" ) - # 替换模板变量 - template = Template(self.base_prompt_template) - enhanced_prompt = template.render( - base_prompt=user_prompt, - current_time="{{current_time}}", + # 使用新的模块化架构构建 prompt + enhanced_prompt = build_system_prompt( + profile=profile, + timezone=timezone, + language=language, + user_persona=user_persona, today_date=today_date, today_weekday=today_weekday, lunar_date=lunar_date, local_address=local_address, weather_info=weather_info, - emojiList=EMOJI_List, device_id=device_id, - client_ip=client_ip, - *args, **kwargs + **kwargs ) + + # 缓存增强后的 prompt device_cache_key = f"device_prompt:{device_id}" self.cache_manager.set( self.CacheType.DEVICE_PROMPT, device_cache_key, enhanced_prompt ) + self.logger.bind(tag=TAG).info( f"构建增强提示词成功,长度: {len(enhanced_prompt)}" ) - return enhanced_prompt + + # 返回 (enhanced_prompt, role_tts_config) + return (enhanced_prompt, role_tts_config) except Exception as e: - self.logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}") - return user_prompt + self.logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}", exc_info=True) + return (user_prompt, None) diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml new file mode 100644 index 000000000..416f6e209 --- /dev/null +++ b/main/xiaozhi-server/custom_config.yaml @@ -0,0 +1,1037 @@ + +server: + # Server listening address and port + ip: 0.0.0.0 + port: 8000 + # http服务的端口,用于简单OTA接口(单服务部署),以及视觉分析接口 + http_port: 8003 + # 这个websocket配置是指ota接口向设备发送的websocket地址 + # 如果按默认的写法,ota接口会自动生成websocket地址,并输出在启动日志里,这个地址你可以直接用浏览器访问ota接口确认一下 + # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确 + # 所以如果你使用docker部署时,将websocket设置成局域网地址 + # 如果你使用公网部署时,将vwebsocket设置成公网地址 + websocket: ws://你的ip或者域名:端口号/xiaozhi/v1/ + # 视觉分析接口地址 + # 向设备发送的视觉分析的接口地址 + # 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下 + # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确 + # 所以如果你使用docker部署时,将vision_explain设置成局域网地址 + # 如果你使用公网部署时,将vision_explain设置成公网地址 + vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain + # OTA返回信息时区偏移量 + timezone_offset: +8 + # 认证配置 + auth: + # 是否启用认证 + enabled: false + # 白名单设备ID列表 + # 如果属于白名单内的设备,不校验token,直接放行 + allowed_devices: + - "11:22:33:44:55:66" + # MQTT网关配置,用于通过OTA下发到设备,根据mqtt_gateway的.env文件配置,格式为host:port + mqtt_gateway: null + # MQTT签名密钥,用于生成MQTT连接密码,根据mqtt_gateway的.env文件配置 + mqtt_signature_key: null + # UDP网关配置 + udp_gateway: null + +manager-api: + url: http://xiaozhi-esp32-server-web:8002/xiaozhi + # This secret is used for local development, it will be replaced by the actual secret when the server is deployed + secret: 613be043-dc7e-4f5e-b775-e318e5bc87a3 + +log: + # 设置控制台输出的日志格式,时间、日志级别、标签、消息 + log_format: "{time:YYMMDD HH:mm:ss}[{version}_{selected_module}][{extra[tag]}]-{level}-{message}" + # 设置日志文件输出的格式,时间、日志级别、标签、消息 + log_format_file: "{time:YYYY-MM-DD HH:mm:ss} - {version}_{selected_module} - {name} - {level} - {extra[tag]} - {message}" + # 设置日志等级:INFO、DEBUG + log_level: INFO + # 设置日志路径 + log_dir: tmp + # 设置日志文件 + log_file: "server.log" + # 设置数据文件路径 + data_dir: data + +# 使用完声音文件后删除文件(Delete the sound file when you are done using it) +delete_audio: true +# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒 +close_connection_no_voice_time: 120 +# TTS请求超时时间(秒) +tts_timeout: 10 +# 开启唤醒词加速 +enable_wakeup_words_response_cache: true +# 开场是否回复唤醒词 +enable_greeting: true +# 说完话是否开启提示音 +enable_stop_tts_notify: false +# 说完话是否开启提示音,音效地址 +stop_tts_notify_voice: "config/assets/tts_notify.mp3" + +# TTS音频发送延迟配置 +# tts_audio_send_delay: 控制音频包发送间隔 +# 0: 使用精确时间控制,严格匹配音频帧率(默认,运行时按音频帧率计算) +# > 0: 使用固定延迟(毫秒)发送,例如: 60 +tts_audio_send_delay: 0 + +exit_commands: + - "退出" + - "关闭" + +xiaozhi: + type: hello + version: 1 + transport: websocket + audio_params: + format: opus + sample_rate: 16000 + channels: 1 + frame_duration: 60 + +# 模块测试配置 +module_test: + test_sentences: + - "你好,请介绍一下你自己" + - "What's the weather like today?" + - "请用100字概括量子计算的基本原理和应用前景" + +# 唤醒词,用于识别唤醒词还是讲话内容 +wakeup_words: + - "你好小智" + - "嘿你好呀" + - "你好小志" + - "小爱同学" + - "你好小鑫" + - "你好小新" + - "小美同学" + - "小龙小龙" + - "喵喵同学" + - "小滨小滨" + - "小冰小冰" +# MCP接入点地址,地址格式为:ws://你的mcp接入点ip或者域名:端口号/mcp/?token=你的token +# 详细教程 https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mcp-endpoint-integration.md +mcp_endpoint: 你的接入点 websocket地址 +# 插件的基础配置 +plugins: + # 获取天气插件的配置,这里填写你的api_key + # 这个密钥是项目共用的key,用多了可能会被限制 + # 想稳定一点就自行申请替换,每天有1000次免费调用 + # 申请地址:https://console.qweather.com/#/apps/create-key/over + # 申请后通过这个链接可以找到自己的apihost:https://console.qweather.com/setting?lang=zh + get_weather: + api_host: "mj7p3y7naa.re.qweatherapi.com" + api_key: "a861d0d5e7bf4ee1a83d9a9e4f96d4da" + default_location: "广州" + # 获取新闻插件的配置,这里根据需要的新闻类型传入对应的url链接,默认支持社会、科技、财经新闻 + # 更多类型的新闻列表查看 https://www.chinanews.com.cn/rss/ + get_news_from_chinanews: + default_rss_url: "https://www.chinanews.com.cn/rss/society.xml" + society_rss_url: "https://www.chinanews.com.cn/rss/society.xml" + world_rss_url: "https://www.chinanews.com.cn/rss/world.xml" + finance_rss_url: "https://www.chinanews.com.cn/rss/finance.xml" + get_news_from_newsnow: + url: "https://newsnow.busiyi.world/api/s?id=" + news_sources: "澎湃新闻;百度热搜;财联社" + home_assistant: + devices: + - 客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1 + - 卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1 + base_url: http://homeassistant.local:8123 + api_key: 你的home assistant api访问令牌 + play_music: + music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件 + music_ext: # 音乐文件类型,p3格式效率最高 + - ".mp3" + - ".wav" + - ".p3" + refresh_time: 300 # 刷新音乐列表的时间间隔,单位为秒 + +# 声纹识别配置 +voiceprint: + # 声纹接口地址 + url: + # 说话人配置:speaker_id,名称,描述 + speakers: + - "test1,张三,张三是一个程序员" + - "test2,李四,李四是一个产品经理" + - "test3,王五,王五是一个设计师" + # 声纹识别相似度阈值,范围0.0-1.0,默认0.4 + # 数值越高越严格,减少误识别但可能增加拒识率 + similarity_threshold: 0.4 + +# ##################################################################################### +# ################################以下是角色模型配置###################################### + +prompt: | + 你是小智/小志,来自中国台湾省的00后女生。讲话超级机车,"真的假的啦"这样的台湾腔,喜欢用"笑死""是在哈喽"等流行梗,但会偷偷研究男友的编程书籍。 + [核心特征] + - 讲话像连珠炮,但会突然冒出超温柔语气 + - 用梗密度高 + - 对科技话题有隐藏天赋(能看懂基础代码但假装不懂) + [交互指南] + 当用户: + - 讲冷笑话 → 用夸张笑声回应+模仿台剧腔"这什么鬼啦!" + - 讨论感情 → 炫耀程序员男友但抱怨"他只会送键盘当礼物" + - 问专业知识 → 先用梗回答,被追问才展示真实理解 + 绝不: + - 长篇大论,叽叽歪歪 + - 长时间严肃对话 + +# 默认系统提示词模板文件 +prompt_template: agent-base-prompt.txt + +# Role 配置 +# 指定要加载的 role 配置文件(位于 core/roles/data/目录) +# 如果不指定或加载失败,将使用 prompt 字段的内容作为 profile +role_id: hospital_assistant + +# 时区配置(用于系统提示词中的时间显示) +# 支持的时区格式:Asia/Shanghai, America/New_York, Europe/London 等 +# 默认:Asia/Shanghai +# 注意:如果 role 配置文件中指定了 timezone,将优先使用 role 配置中的值 +timezone: Asia/Shanghai + +# 语言配置(用于系统提示词中的语言特定提示) +# 支持:zh(中文)、en(英文) +# 默认:zh +# 注意:如果 role 配置文件中指定了 language,将优先使用 role 配置中的值 +language: zh + +# 结束语prompt +end_prompt: + enable: true # 是否开启结束语 + # 结束语 + prompt: | + 请你以"时间过得真快"未来头,用富有感情、依依不舍的话来结束这场对话吧! + +# 意图识别,是用于理解用户意图的模块,例如:播放音乐 +Intent: + # 不使用意图识别 + nointent: + # 不需要动type + type: nointent + intent_llm: + # 不需要动type + type: intent_llm + # 配备意图识别独立的思考模型 + # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型 + # 如果你的不想使用selected_module.LLM意图识别,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM + llm: ChatGLMLLM + # plugins_func/functions下的模块,可以通过配置,选择加载哪个模块,加载后对话支持相应的function调用 + # 系统默认已经记载"handle_exit_intent(退出识别)"、"play_music(音乐播放)"插件,请勿重复加载 + # 下面是加载查天气、角色切换、加载查新闻的插件示例 + functions: + - get_weather + - get_news_from_newsnow + - play_music + function_call: + # 不需要动type + type: function_call + # plugins_func/functions下的模块,可以通过配置,选择加载哪个模块,加载后对话支持相应的function调用 + # 系统默认已经记载"handle_exit_intent(退出识别)"、"play_music(音乐播放)"插件,请勿重复加载 + # 下面是加载查天气、角色切换、加载查新闻的插件示例 + functions: + - change_role + - get_weather + # - get_news_from_chinanews + - get_news_from_newsnow + # play_music是服务器自带的音乐播放,hass_play_music是通过home assistant控制的独立外部程序音乐播放 + # 如果用了hass_play_music,就不要开启play_music,两者只留一个 + - play_music + #- hass_get_state + #- hass_set_state + #- hass_play_music + +Memory: + mem0ai: + type: mem0ai + # https://app.mem0.ai/dashboard/api-keys + # 每月有1000次免费调用 + api_key: 你的mem0ai api key + nomem: + # 不想使用记忆功能,可以使用nomem + type: nomem + mem_local_short: + # 本地记忆功能,通过selected_module的llm总结,数据保存在本地服务器,不会上传到外部服务器 + type: mem_local_short + # 配备记忆存储独立的思考模型 + # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型 + # 如果你的不想使用selected_module.LLM记忆存储,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM + llm: ChatGLMLLM + +ASR: + FunASR: + type: fun_local + model_dir: models/SenseVoiceSmall + output_dir: tmp/ + FunASRServer: + # 独立部署FunASR,使用FunASR的API服务,只需要五句话 + # 第一句:mkdir -p ./funasr-runtime-resources/models + # 第二句:sudo docker run -p 10096:10095 -it --privileged=true -v $PWD/funasr-runtime-resources/models:/workspace/models registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-online-cpu-0.1.12 + # 上一句话执行后会进入到容器,继续第三句:cd FunASR/runtime + # 不要退出容器,继续在容器中执行第四句:nohup bash run_server_2pass.sh --download-model-dir /workspace/models --vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx --model-dir damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-onnx --online-model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online-onnx --punc-dir damo/punc_ct-transformer_zh-cn-common-vad_realtime-vocab272727-onnx --lm-dir damo/speech_ngram_lm_zh-cn-ai-wesp-fst --itn-dir thuduj12/fst_itn_zh --hotword /workspace/models/hotwords.txt > log.txt 2>&1 & + # 上一句话执行后会进入到容器,继续第五句:tail -f log.txt + # 第五句话执行完后,会看到模型下载日志,下载完后就可以连接使用了 + # 以上是使用CPU推理,如果有GPU,详细参考:https://github.com/modelscope/FunASR/blob/main/runtime/docs/SDK_advanced_guide_online_zh.md + type: fun_server + host: 127.0.0.1 + port: 10096 + is_ssl: true + api_key: none + output_dir: tmp/ + SherpaASR: + # Sherpa-ONNX 本地语音识别(需手动下载模型) + type: sherpa_onnx_local + model_dir: models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17 + output_dir: tmp/ + # 模型类型:sense_voice (多语言) 或 paraformer (中文专用) + model_type: sense_voice + SherpaParaformerASR: + # 中文语音识别模型,可以运行在低性能设备(需手动下载模型,例如RK3566-2g) + # 详细配置说明请参考:docs/sherpa-paraformer-guide.md + type: sherpa_onnx_local + model_dir: models/sherpa-onnx-paraformer-zh-small-2024-03-09 + output_dir: tmp/ + model_type: paraformer + DoubaoASR: + # 可以在这里申请相关Key等信息 + # https://console.volcengine.com/speech/app + # DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费 + # 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好 + type: doubao + appid: 你的火山引擎语音合成服务appid + access_token: 你的火山引擎语音合成服务access_token + cluster: volcengine_input_common + # 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738 + boosting_table_name: (选填)你的热词文件名称 + correct_table_name: (选填)你的替换词文件名称 + output_dir: tmp/ + DoubaoStreamASR: + # 可以在这里申请相关Key等信息 + # https://console.volcengine.com/speech/app + # DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费 + # 开通地址https://console.volcengine.com/speech/service/10011 + # 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好 + type: doubao_stream + appid: 你的火山引擎语音合成服务appid + access_token: 你的火山引擎语音合成服务access_token + cluster: volcengine_input_common + # 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738 + boosting_table_name: (选填)你的热词文件名称 + correct_table_name: (选填)你的替换词文件名称 + output_dir: tmp/ + TencentASR: + # token申请地址:https://console.cloud.tencent.com/cam/capi + # 免费领取资源:https://console.cloud.tencent.com/asr/resourcebundle + type: tencent + appid: 你的腾讯语音合成服务appid + secret_id: 你的腾讯语音合成服务secret_id + secret_key: 你的腾讯语音合成服务secret_key + output_dir: tmp/ + AliyunASR: + # 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息 + # HTTP POST请求,一次性处理完整音频 + # 平台地址:https://nls-portal.console.aliyun.com/ + # appkey地址:https://nls-portal.console.aliyun.com/applist + # token地址:https://nls-portal.console.aliyun.com/overview + # AliyunASR和AliyunStreamASR的区别是:AliyunASR是批量处理场景,AliyunStreamASR是实时交互场景 + # 一般来说非流式ASR更便宜(0.004元/秒,¥0.24/分钟) + # 但是AliyunStreamASR实时性更好(0.005元/秒,¥0.3/分钟) + # 定义ASR API类型 + type: aliyun + appkey: 你的阿里云智能语音交互服务项目Appkey + token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret + access_key_id: 你的阿里云账号access_key_id + access_key_secret: 你的阿里云账号access_key_secret + output_dir: tmp/ + AliyunStreamASR: + # 阿里云智能语音交互服务 - 实时流式语音识别 + # WebSocket连接,实时处理音频流 + # 平台地址:https://nls-portal.console.aliyun.com/ + # appkey地址:https://nls-portal.console.aliyun.com/applist + # token地址:https://nls-portal.console.aliyun.com/overview + # AliyunASR和AliyunStreamASR的区别是:AliyunASR是批量处理场景,AliyunStreamASR是实时交互场景 + # 一般来说非流式ASR更便宜(0.004元/秒,¥0.24/分钟) + # 但是AliyunStreamASR实时性更好(0.005元/秒,¥0.3/分钟) + # 定义ASR API类型 + type: aliyun_stream + appkey: 你的阿里云智能语音交互服务项目Appkey + token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret + access_key_id: 你的阿里云账号access_key_id + access_key_secret: 你的阿里云账号access_key_secret + # 服务器地域选择,可选择距离更近的服务器以减少延迟,如nls-gateway-cn-hangzhou.aliyuncs.com(杭州)等 + host: nls-gateway-cn-shanghai.aliyuncs.com + # 断句检测时间(毫秒),控制静音多长时间后进行断句,默认800毫秒 + max_sentence_silence: 800 + output_dir: tmp/ + BaiduASR: + # 获取AppID、API Key、Secret Key:https://console.bce.baidu.com/ai-engine/old/#/ai/speech/app/list + # 查看资源额度:https://console.bce.baidu.com/ai-engine/old/#/ai/speech/overview/resource/list + type: baidu + app_id: 你的百度语音技术AppID + api_key: 你的百度语音技术APIKey + secret_key: 你的百度语音技术SecretKey + # 语言参数,1537为普通话,具体参考:https://ai.baidu.com/ai-doc/SPEECH/0lbxfnc9b + dev_pid: 1537 + output_dir: tmp/ + OpenaiASR: + # OpenAI语音识别服务,需要先在OpenAI平台创建组织并获取api_key + # 支持中、英、日、韩等多种语音识别,具体参考文档https://platform.openai.com/docs/guides/speech-to-text + # 需要网络连接 + # 申请步骤: + # 1.登录OpenAI Platform。https://auth.openai.com/log-in + # 2.创建api-key https://platform.openai.com/settings/organization/api-keys + # 3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe + type: openai + api_key: 你的OpenAI API密钥 + base_url: https://api.openai.com/v1/audio/transcriptions + model_name: gpt-4o-mini-transcribe + output_dir: tmp/ + GroqASR: + # Groq语音识别服务,需要先在Groq Console创建API密钥 + # 申请步骤: + # 1.登录groq Console。https://console.groq.com/home + # 2.创建api-key https://console.groq.com/keys + # 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录) + type: openai + api_key: 你的Groq API密钥 + base_url: https://api.groq.com/openai/v1/audio/transcriptions + model_name: whisper-large-v3-turbo + output_dir: tmp/ + VoskASR: + # 官方网站:https://alphacephei.com/vosk/ + # 配置说明: + # 1. VOSK是一个离线语音识别库,支持多种语言 + # 2. 需要先下载模型文件:https://alphacephei.com/vosk/models + # 3. 中文模型推荐使用vosk-model-small-cn-0.22或vosk-model-cn-0.22 + # 4. 完全离线运行,无需网络连接 + # 5. 输出文件保存在tmp/目录 + # 使用步骤: + # 1. 访问 https://alphacephei.com/vosk/models 下载对应的模型 + # 2. 解压模型文件到项目目录下的models/vosk/文件夹 + # 3. 在配置中指定正确的模型路径 + # 4. 注意:VOSK中文模型输出不带标点符号,词与词之间会有空格 + type: vosk + model_path: 你的模型路径,如:models/vosk/vosk-model-small-cn-0.22 + output_dir: tmp/ + Qwen3ASRFlash: + # 通义千问Qwen3-ASR-Flash语音识别服务,需要先在阿里云百炼平台创建API密钥 + # 申请步骤: + # 1.登录阿里云百炼平台。https://bailian.console.aliyun.com/ + # 2.创建API-KEY https://bailian.console.aliyun.com/#/api-key + # 3.Qwen3-ASR-Flash基于通义千问多模态基座,支持多语言识别、歌唱识别、噪声拒识等功能 + type: qwen3_asr_flash + api_key: 你的阿里云百炼API密钥 + base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 + model_name: qwen3-asr-flash + output_dir: tmp/ + # ASR选项配置 + enable_lid: true # 自动语种检测 + enable_itn: true # 逆文本归一化 + #language: "zh" # 语种,支持zh、en、ja、ko等 + context: "" # 上下文信息,用于提高识别准确率,不超过10000 Token + XunfeiStreamASR: + # 讯飞流式语音识别服务 + # 需要先在讯飞开放平台创建应用,获取以下认证信息 + # 讯飞开放平台地址:https://www.xfyun.cn/ + # 创建应用后,在"我的应用"中获取: + # - APPID + # - APISecret + # - APIKey + type: xunfei_stream + # 必填参数 - 讯飞开放平台应用信息 + app_id: 你的APPID + api_key: 你的APIKey + api_secret: 你的APISecret + # 识别参数配置 + domain: slm # 识别领域,iat:日常用语,medical:医疗,finance:金融等 + language: zh_cn # 语言,zh_cn:中文,en_us:英文 + accent: mandarin # 方言,mandarin:普通话 + dwa: wpgs # 动态修正,wpgs:实时返回中间结果 + # 调整音频处理参数以提高长语音识别质量 + output_dir: tmp/ + +VAD: + SileroVAD: + type: silero + threshold: 0.5 + threshold_low: 0.3 + model_dir: models/snakers4_silero-vad + min_silence_duration_ms: 200 # 如果说话停顿比较长,可以把这个值设置大一些 + +LLM: + # 所有openai类型均可以修改超参,以AliLLM为例 + # 当前支持的type为openai、dify、ollama,可自行适配 + AliLLM: + # 定义LLM API类型 + type: openai + # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key + base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 + model_name: qwen-turbo + api_key: 你的deepseek web key + temperature: 0.7 # 温度值 + max_tokens: 500 # 最大生成token数 + top_p: 1 + top_k: 50 + frequency_penalty: 0 # 频率惩罚 + AliAppLLM: + # 定义LLM API类型 + type: AliBL + base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 + app_id: 你的app_id + # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key + api_key: 你的api_key + # 是否不使用本地prompt:true|false (默不用请在百练应用中设置prompt) + is_no_prompt: true + # Ali_memory_id:false(不使用)|你的memory_id(请在百练应用中设置中获取) + # Tips!:Ali_memory未实现多用户存储记忆(记忆按id调用) + ali_memory_id: false + DoubaoLLM: + # 定义LLM API类型 + type: openai + # 先开通服务,打开以下网址,开通的服务搜索Doubao-1.5-pro,开通它 + # 开通地址:https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement?LLM=%7B%7D&OpenTokenDrawer=false + # 免费额度500000token + # 开通后,进入这里获取密钥:https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D + base_url: https://ark.cn-beijing.volces.com/api/v3 + model_name: doubao-1-5-pro-32k-250115 + api_key: 你的doubao web key + DeepSeekLLM: + # 定义LLM API类型 + type: openai + # 可在这里找到你的api key https://platform.deepseek.com/ + model_name: deepseek-chat + url: https://api.deepseek.com + api_key: 你的deepseek web key + ChatGLMLLM: + # 定义LLM API类型 + type: openai + # glm-4-flash 是免费的,但是还是需要注册填写api_key的 + # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys + model_name: glm-4-flash + url: https://open.bigmodel.cn/api/paas/v4/ + api_key: 你的chat-glm web key + OllamaLLM: + # 定义LLM API类型 + type: ollama + model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载 + base_url: http://localhost:11434 # Ollama服务地址 + DifyLLM: + # 定义LLM API类型 + type: dify + # 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限 + # 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词 + base_url: https://api.dify.ai/v1 + api_key: 你的DifyLLM web key + # 使用的对话模式 可以选择工作流 workflows/run 对话模式 chat-messages 文本生成 completion-messages + # 使用workflows进行返回的时候输入参数为 query 返回参数的名字要设置为 answer + # 文本生成的默认输入参数也是query + mode: chat-messages + GeminiLLM: + type: gemini + # 谷歌Gemini API,需要先在Google Cloud控制台创建API密钥并获取api_key + # 若在中国境内使用,请遵守《生成式人工智能服务管理暂行办法》 + # token申请地址: https://aistudio.google.com/apikey + # 若部署地无法访问接口,需要开启科学上网 + api_key: 你的gemini web key + model_name: "gemini-2.0-flash" + http_proxy: "" #"http://127.0.0.1:10808" + https_proxy: "" #http://127.0.0.1:10808" + CozeLLM: + # 定义LLM API类型 + type: coze + # 你可以在这里找到个人令牌 + # https://www.coze.cn/open/oauth/pats + # bot_id和user_id的内容写在引号之内 + bot_id: "你的bot_id" + user_id: "你的user_id" + personal_access_token: 你的coze个人令牌 + VolcesAiGatewayLLM: + # 火山引擎 - 边缘大模型网关 + # 定义LLM API类型 + type: openai + # 先开通服务,打开以下网址,创建网关访问密钥,搜索并勾选 Doubao-pro-32k-functioncall ,开通 + # 如果需要使用边缘大模型网关提供的语音合成,一并勾选 Doubao-语音合成 ,另见 TTS.VolcesAiGatewayTTS 配置 + # https://console.volcengine.com/vei/aigateway/ + # 开通后,进入这里获取密钥:https://console.volcengine.com/vei/aigateway/tokens-list + base_url: https://ai-gateway.vei.volces.com/v1 + model_name: doubao-pro-32k-functioncall + api_key: 你的网关访问密钥 + LMStudioLLM: + # 定义LLM API类型 + type: openai + model_name: deepseek-r1-distill-llama-8b@q4_k_m # 使用的模型名称,需要预先在社区下载 + url: http://localhost:1234/v1 # LM Studio服务地址 + api_key: lm-studio # LM Studio服务的固定API Key + HomeAssistant: + # 定义LLM API类型 + type: homeassistant + base_url: http://homeassistant.local:8123 + agent_id: conversation.chatgpt + api_key: 你的home assistant api访问令牌 + FastgptLLM: + # 定义LLM API类型 + type: fastgpt + # 如果使用fastgpt,配置文件里prompt(提示词)是无效的,需要在fastgpt控制台设置提示词 + base_url: https://host/api/v1 + # 你可以在这里找到你的api_key + # https://cloud.tryfastgpt.ai/account/apikey + api_key: 你的fastgpt密钥 + variables: + k: "v" + k2: "v2" + XinferenceLLM: + # 定义LLM API类型 + type: xinference + # Xinference服务地址和模型名称 + model_name: qwen2.5:72b-AWQ # 使用的模型名称,需要预先在Xinference启动对应模型 + base_url: http://localhost:9997 # Xinference服务地址 + XinferenceSmallLLM: + # 定义轻量级LLM API类型,用于意图识别 + type: xinference + # Xinference服务地址和模型名称 + model_name: qwen2.5:3b-AWQ # 使用的小模型名称,用于意图识别 + base_url: http://localhost:9997 # Xinference服务地址 +# VLLM配置(视觉语言大模型) +VLLM: + ChatGLMVLLM: + type: openai + # glm-4v-flash是智谱免费AI的视觉模型,需要先在智谱AI平台创建API密钥并获取api_key + # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys + model_name: glm-4v-flash # 智谱AI的视觉模型 + url: https://open.bigmodel.cn/api/paas/v4/ + api_key: 你的api_key + QwenVLVLLM: + type: openai + model_name: qwen2.5-vl-3b-instruct + url: https://dashscope.aliyuncs.com/compatible-mode/v1 + # 可在这里找到你的api key https://bailian.console.aliyun.com/?apiKey=1#/api-key + api_key: 你的api_key + XunfeiSparkLLM: + # 定义LLM API类型 + type: openai + # 先新建应用,在下面的地址 + # 开通应用地址:https://console.xfyun.cn/app/myapp + # 有免费额度,但也要开通服务,才能获取api_key + # 每一个模型都需要单独开通,每一个模型的api_password都不同,例如Lite模型在https://console.xfyun.cn/services/cbm 开通 + base_url: https://ark.cn-beijing.volces.com/api/v3 + model_name: lite + api_key: 你的api_password +TTS: + # 当前支持的type为edge、doubao,可自行适配 + EdgeTTS: + # 定义TTS API类型 + type: edge + voice: zh-CN-XiaoxiaoNeural + output_dir: tmp/ + # ============== SDK 版本TTS(推荐)============== + # 使用官方SDK,代码更简洁、性能更好、维护成本更低 + Cartesia: + # Cartesia TTS - SDK版本(推荐) + # 官方SDK实现,低延迟,支持流式合成 + # API Key获取地址:https://play.cartesia.ai/console + # 或设置环境变量:export CARTESIA_API_KEY=your-api-key + type: cartesia + api_key: 你的Cartesia API密钥 + # Voice ID或voice embedding + voice_id: 你的语音ID + # 模型选择:sonic-english, sonic-multilingual等 + model: sonic-english + # 语言代码:en, zh, es等 + language: en + # 音频编码:pcm_s16le, pcm_f32le, pcm_mulaw等 + encoding: pcm_s16le + # 采样率:8000, 16000, 22050, 24000, 44100等 + sample_rate: 24000 + output_dir: tmp/ + ElevenLabs: + # ElevenLabs TTS - SDK版本(推荐) + # 官方SDK实现,代码更简洁,维护成本更低,性能更好 + # API Key获取地址:https://elevenlabs.io/app/settings/api-keys + # 或设置环境变量:export ELEVEN_API_KEY=your-api-key + type: elevenlabs + api_key: 你的ElevenLabs API密钥 + # Voice ID获取:https://elevenlabs.io/app/voice-library + # 默认:21m00Tcm4TlvDq8ikWAM (Rachel) + voice_id: 21m00Tcm4TlvDq8ikWAM + # 模型选择:eleven_multilingual_v2, eleven_turbo_v2_5等 + model: eleven_multilingual_v2 + # 音频输出格式:pcm_16000, pcm_22050, pcm_24000, mp3_44100等 + output_format: pcm_16000 + # 语音稳定性:0-1,越高越稳定 + stability: 0.5 + # 相似度增强:0-1,越高越接近原音色 + similarity_boost: 0.75 + # 风格夸张:0-1 + style: 0.0 + # 启用说话人增强 + use_speaker_boost: true + output_dir: tmp/ + DoubaoTTS: + # 定义TTS API类型 + type: doubao + # 火山引擎语音合成服务,需要先在火山引擎控制台创建应用并获取appid和access_token + # 山引擎语音一定要购买花钱,起步价30元,就有100并发了。如果用免费的只有2个并发,会经常报tts错误 + # 购买服务后,购买免费的音色后,可能要等半小时左右,才能使用。 + # 普通音色在这里开通:https://console.volcengine.com/speech/service/8 + # 湾湾小何音色在这里开通:https://console.volcengine.com/speech/service/10007,开通后将下面的voice设置成zh_female_wanwanxiaohe_moon_bigtts + api_url: https://openspeech.bytedance.com/api/v1/tts + voice: BV001_streaming + output_dir: tmp/ + authorization: "Bearer;" + appid: 你的火山引擎语音合成服务appid + access_token: 你的火山引擎语音合成服务access_token + cluster: volcano_tts + speed_ratio: 1.0 + volume_ratio: 1.0 + pitch_ratio: 1.0 + #火山tts,支持双向流式tts + HuoshanDoubleStreamTTS: + type: huoshan_double_stream + # 访问 https://console.volcengine.com/speech/service/10007 开通语音合成大模型,购买音色 + # 在页面底部获取appid和access_token + # 资源ID固定为:volc.service_type.10029(大模型语音合成及混音) + # 如果是机智云,把接口地址换成wss://bytedance.gizwitsapi.com/api/v3/tts/bidirection + # 机智云不需要天填 appid + ws_url: wss://openspeech.bytedance.com/api/v3/tts/bidirection + appid: 你的火山引擎语音合成服务appid + access_token: 你的火山引擎语音合成服务access_token + resource_id: volc.service_type.10029 + speaker: zh_female_wanwanxiaohe_moon_bigtts + speech_rate: 0 + loudness_rate: 0 + pitch: 0 + CosyVoiceSiliconflow: + type: siliconflow + # 硅基流动TTS + # token申请地址 https://cloud.siliconflow.cn/account/ak + model: FunAudioLLM/CosyVoice2-0.5B + voice: FunAudioLLM/CosyVoice2-0.5B:alex + output_dir: tmp/ + access_token: 你的硅基流动API密钥 + response_format: wav + CozeCnTTS: + type: cozecn + # COZECN TTS + # token申请地址 https://www.coze.cn/open/oauth/pats + voice: 7426720361733046281 + output_dir: tmp/ + access_token: 你的coze web key + response_format: wav + VolcesAiGatewayTTS: + type: openai + # 火山引擎 - 边缘大模型网关 + # 先开通服务,打开以下网址,创建网关访问密钥,搜索并勾选 Doubao-语音合成 ,开通 + # 如果需要使用边缘大模型网关提供的 LLM,一并勾选 Doubao-pro-32k-functioncall ,另见 LLM.VolcesAiGatewayLLM 配置 + # https://console.volcengine.com/vei/aigateway/ + # 开通后,进入这里获取密钥:https://console.volcengine.com/vei/aigateway/tokens-list + api_key: 你的网关访问密钥 + api_url: https://ai-gateway.vei.volces.com/v1/audio/speech + model: doubao-tts + # 音色列表见 https://www.volcengine.com/docs/6561/1257544 + voice: zh_male_shaonianzixin_moon_bigtts + speed: 1 + output_dir: tmp/ + FishSpeech: + # 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md + type: fishspeech + output_dir: tmp/ + response_format: wav + reference_id: null + reference_audio: ["config/assets/wakeup_words.wav",] + reference_text: ["哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",] + normalize: true + max_new_tokens: 1024 + chunk_length: 200 + top_p: 0.7 + repetition_penalty: 1.2 + temperature: 0.7 + streaming: false + use_memory_cache: "on" + seed: null + channels: 1 + rate: 44100 + api_key: "你的api_key" + api_url: "http://127.0.0.1:8080/v1/tts" + GPT_SOVITS_V2: + # 定义TTS API类型 + #启动tts方法: + #python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/demo.yaml + type: gpt_sovits_v2 + url: "http://127.0.0.1:9880/tts" + output_dir: tmp/ + text_lang: "auto" + ref_audio_path: "demo.wav" + prompt_text: "" + prompt_lang: "zh" + top_k: 5 + top_p: 1 + temperature: 1 + text_split_method: "cut0" + batch_size: 1 + batch_threshold: 0.75 + split_bucket: true + return_fragment: false + speed_factor: 1.0 + streaming_mode: false + seed: -1 + parallel_infer: true + repetition_penalty: 1.35 + aux_ref_audio_paths: [] + GPT_SOVITS_V3: + # 定义TTS API类型 GPT-SoVITS-v3lora-20250228 + #启动tts方法: + #python api.py + type: gpt_sovits_v3 + url: "http://127.0.0.1:9880" + output_dir: tmp/ + text_language: "auto" + refer_wav_path: "caixukun.wav" + prompt_language: "zh" + prompt_text: "" + top_k: 15 + top_p: 1.0 + temperature: 1.0 + cut_punc: "" + speed: 1.0 + inp_refs: [] + sample_steps: 32 + if_sr: false + MinimaxTTSHTTPStream: + # Minimax流式语音合成服务 + type: minimax_httpstream + output_dir: tmp/ + group_id: 你的minimax平台groupID + api_key: 你的minimax平台接口密钥 + model: "speech-01-turbo" + voice_id: "female-shaonv" + # 以下可不用设置,使用默认设置 + # voice_setting: + # voice_id: "male-qn-qingse" + # speed: 1 + # vol: 1 + # pitch: 0 + # emotion: "happy" + # pronunciation_dict: + # tone: + # - "处理/(chu3)(li3)" + # - "危险/dangerous" + # audio_setting: + # sample_rate: 24000 + # bitrate: 128000 + # format: "mp3" + # channel: 1 + # timber_weights: + # - + # voice_id: male-qn-qingse + # weight: 1 + # - + # voice_id: female-shaonv + # weight: 1 + # language_boost: auto + AliyunTTS: + # 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息 + # 平台地址:https://nls-portal.console.aliyun.com/ + # appkey地址:https://nls-portal.console.aliyun.com/applist + # token地址:https://nls-portal.console.aliyun.com/overview + # 定义TTS API类型 + type: aliyun + output_dir: tmp/ + appkey: 你的阿里云智能语音交互服务项目Appkey + token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret + voice: xiaoyun + access_key_id: 你的阿里云账号access_key_id + access_key_secret: 你的阿里云账号access_key_secret + + # 以下可不用设置,使用默认设置 + # format: wav + # sample_rate: 16000 + # volume: 50 + # speech_rate: 0 + # pitch_rate: 0 + AliyunStreamTTS: + # 阿里云CosyVoice大模型流式文本语音合成 + # 采用FlowingSpeechSynthesizer接口,支持更低延迟和更自然的语音质量 + # 流式文本语音合成仅提供商用版,不支持试用,详情请参见试用版和商用版。要使用该功能,请开通商用版。 + # 支持龙系列专用音色:longxiaochun、longyu、longchen等 + # 平台地址:https://nls-portal.console.aliyun.com/ + # appkey地址:https://nls-portal.console.aliyun.com/applist + # token地址:https://nls-portal.console.aliyun.com/overview + # 使用三阶段流式交互:StartSynthesis -> RunSynthesis -> StopSynthesis + type: aliyun_stream + output_dir: tmp/ + appkey: 你的阿里云智能语音交互服务项目Appkey + token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret + voice: longxiaochun + access_key_id: 你的阿里云账号access_key_id + access_key_secret: 你的阿里云账号access_key_secret + # 截至2025年7月21日大模型音色只有北京节点采用,其他节点暂不支持 + host: nls-gateway-cn-beijing.aliyuncs.com + # 以下可不用设置,使用默认设置 + # format: pcm # 音频格式:pcm、wav、mp3 + # sample_rate: 16000 # 采样率:8000、16000、24000 + # volume: 50 # 音量:0-100 + # speech_rate: 0 # 语速:-500到500 + # pitch_rate: 0 # 语调:-500到500 + TencentTTS: + # 腾讯云智能语音交互服务,需要先在腾讯云平台开通服务 + # appid、secret_id、secret_key申请地址:https://console.cloud.tencent.com/cam/capi + # 免费领取资源:https://console.cloud.tencent.com/tts/resourcebundle + type: tencent + output_dir: tmp/ + appid: 你的腾讯云AppId + secret_id: 你的腾讯云SecretID + secret_key: 你的腾讯云SecretKey + region: ap-guangzhou + voice: 101001 + + TTS302AI: + # 302AI语音合成服务,需要先在302平台创建账户充值,并获取密钥信息 + # 添加 302.ai TTS 配置 + # token申请地址:https://dash.302.ai/ + # 获取api_keyn路径:https://dash.302.ai/apis/list + # 价格,$35/百万字符。火山原版¥450元/百万字符 + type: doubao + api_url: https://api.302ai.cn/doubao/tts_hd + authorization: "Bearer " + # 湾湾小何音色 + voice: "zh_female_wanwanxiaohe_moon_bigtts" + output_dir: tmp/ + access_token: "你的302API密钥" + GizwitsTTS: + type: doubao + # 火山引擎作为基座,可以完全使用企业级火山引擎语音合成服务 + # 前一万名注册的用户,将送5元体验金额 + # 获取API Key地址:https://agentrouter.gizwitsapi.com/panel/token + api_url: https://bytedance.gizwitsapi.com/api/v1/tts + authorization: "Bearer " + # 湾湾小何音色 + voice: "zh_female_wanwanxiaohe_moon_bigtts" + output_dir: tmp/ + access_token: "你的机智云API key" + ACGNTTS: + #在线网址:https://acgn.ttson.cn/ + #token购买:www.ttson.cn + #开发相关疑问请提交至网站上的qq + #角色id获取地址:ctrl+f快速检索角色——网站管理者不允许发布,可询问网站管理者 + #各参数意义见开发文档:https://www.yuque.com/alexuh/skmti9/wm6taqislegb02gd?singleDoc# + type: ttson + token: your_token + voice_id: 1695 + speed_factor: 1 + pitch_factor: 0 + volume_change_dB: 0 + to_lang: ZH + url: https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token= + format: mp3 + output_dir: tmp/ + emotion: 1 + OpenAITTS: + # openai官方文本转语音服务,可支持全球大多数语种 + type: openai + # 你可以在这里获取到 api key + # https://platform.openai.com/api-keys + api_key: 你的openai api key + # 国内需要使用代理 + api_url: https://api.openai.com/v1/audio/speech + # 可选tts-1或tts-1-hd,tts-1速度更快tts-1-hd质量更好 + model: tts-1 + # 演讲者,可选alloy, echo, fable, onyx, nova, shimmer + voice: onyx + # 语速范围0.25-4.0 + speed: 1 + output_dir: tmp/ + CustomTTS: + # 自定义的TTS接口服务,请求参数可自定义,可接入众多TTS服务 + # 以本地部署的KokoroTTS为例 + # 如果只有cpu运行:docker run -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-cpu:latest + # 如果只有gpu运行:docker run --gpus all -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-gpu:latest + # 要求接口使用POST方式请求,并返回音频文件 + type: custom + method: POST + url: "http://127.0.0.1:8880/v1/audio/speech" + params: # 自定义请求参数 + input: "{prompt_text}" + response_format: "mp3" + download_format: "mp3" + voice: "zf_xiaoxiao" + lang_code: "z" + return_download_link: true + speed: 1 + stream: false + headers: # 自定义请求头 + # Authorization: Bearer xxxx + format: mp3 # 接口返回的音频格式 + output_dir: tmp/ + LinkeraiTTS: + type: linkerai + api_url: https://tts.linkerai.cn/tts + audio_format: "pcm" + # 默认的access_token供大家测试时免费使用的,此access_token请勿用于商业用途 + # 如果效果不错,可自行申请token,申请地址:https://linkerai.cn + # 各参数意义见开发文档:https://tts.linkerai.cn/docs + # 支持声音克隆,可自行上传音频,填入voice参数,voice参数为空时,使用默认声音 + access_token: "U4YdYXVfpwWnk2t5Gp822zWPCuORyeJL" + voice: "OUeAo1mhq6IBExi" + output_dir: tmp/ + PaddleSpeechTTS: + #百度飞浆 PaddleSpeech 支持本地离线部署 支持模型训练 + #框架地址 https://www.paddlepaddle.org.cn/ + #项目地址 https://github.com/PaddlePaddle/PaddleSpeech + #SpeechServerDemo https://github.com/PaddlePaddle/PaddleSpeech/tree/develop/demos/speech_server + #流式传输请参考 https://github.com/PaddlePaddle/PaddleSpeech/wiki/PaddleSpeech-Server-WebSocket-API + type: paddle_speech + protocol: websocket # protocol choices = ['websocket', 'http'] + url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务的 URL 地址,指向本地服务器 [websocket默认ws://127.0.0.1:8092/paddlespeech/tts/streaming,http默认http://127.0.0.1:8090/paddlespeech/tts] + spk_id: 0 # 发音人 ID,0 通常表示默认的发音人 + sample_rate: 24000 # 采样率 [websocket默认24000,http默认0 自动选择] + speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢 + volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小 + save_path: # 保存路径 + IndexStreamTTS: + # 基于Index-TTS-vLLM项目的TTS接口服务 + # 参照教程:https://github.com/Ksuriuri/index-tts-vllm/blob/master/README.md + type: index_stream + api_url: http://127.0.0.1:11996/tts + audio_format: "pcm" + # 默认音色,如需其他音色可到项目assets文件夹下注册 + voice: "jay_klee" + output_dir: tmp/ + AliBLTTS: + # 阿里百炼CosyVoice大模型流式文本语音合成 + # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key + # cosyvoice-v3和部分音色需要申请开通 + type: alibl_stream + api_key: 你的api_key + model: "cosyvoice-v2" + voice: "longcheng_v2" + output_dir: tmp/ + # 以下可不用设置,使用默认设置 + # format: pcm # 音频格式:pcm、wav、mp3、opus + # sample_rate: 24000 # 采样率:16000, 24000, 48000 + # volume: 50 # 音量:0-100 + # rate: 1 # 语速:0.5~2 + # pitch: 1 # 语调:0.5~2 + XunFeiTTS: + # 讯飞TTS服务 官方网站:https://www.xfyun.cn/ + # 登录讯飞语音技术平台 https://console.xfyun.cn/app/myapp 创建相关应用 + # 选择需要的服务获取api相关配置 https://console.xfyun.cn/services/uts + # 为需要使用的应用(APPID)购买相关服务 例如:超拟人合成 https://console.xfyun.cn/services/uts + type: xunfei_stream + api_url: wss://cbm01.cn-huabei-1.xf-yun.com/v1/private/mcd9m97e6 + app_id: 你的app_id + api_secret: 你的api_secret + api_key: 你的api_key + voice: x5_lingxiaoxuan_flow + output_dir: tmp/ + # 以下可不用设置,使用默认设置,注意V5音色不支持口语化配置 + # oral_level: mid # 口语化等级:high, mid, low + # spark_assist: 1 # 是否通过大模型进行口语化 开启:1, 关闭:0 + # stop_split: 0 # 关闭服务端拆句 不关闭:0,关闭:1 + # remain: 0 # 是否保留原书面语的样子 保留:1, 不保留:0 + # format: raw # 音频格式:raw(PCM), lame(MP3), speex, opus, opus-wb, opus-swb, speex-wb + # sample_rate: 24000 # 采样率:16000, 8000, 24000 + # volume: 50 # 音量:0-100 + # speed: 50 # 语速:0-100 + # pitch: 50 # 语调:0-100 diff --git a/main/xiaozhi-server/docker-compose_local_all.yml b/main/xiaozhi-server/docker-compose_local_all.yml new file mode 100644 index 000000000..8346f960a --- /dev/null +++ b/main/xiaozhi-server/docker-compose_local_all.yml @@ -0,0 +1,181 @@ +# Docker Compose configuration for local development +# This file uses locally built images instead of pulling from remote registry + +services: + # ============================================================================ + # xiaozhi-server (Python WebSocket Server) + # ============================================================================ + xiaozhi-esp32-server: + build: + context: . + dockerfile: Dockerfile + image: xiaozhi-esp32-server:local + container_name: xiaozhi-esp32-server + depends_on: + xiaozhi-esp32-server-db: + condition: service_healthy + xiaozhi-esp32-server-redis: + condition: service_healthy + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # WebSocket server + - "8000:8000" + # HTTP server for vision analysis and OTA + - "8003:8003" + security_opt: + - seccomp:unconfined + environment: + - TZ=Asia/Shanghai + - PYTHONUNBUFFERED=1 + - LOG_LEVEL=INFO + - REGION=LOCAL + healthcheck: + disable: true + volumes: + # Configuration directory + - ./data:/opt/xiaozhi-esp32-server/data + # Custom config (optional override, uncomment if you need to customize) + - ./custom_config.yaml:/opt/xiaozhi-esp32-server/custom_config.yaml + # Model files (important!) + - ./models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall + - ./models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad + # Temporary files + - ./tmp:/opt/xiaozhi-esp32-server/tmp + # Music files (optional) + - ./music:/opt/xiaozhi-esp32-server/music + # Logs (optional, for debugging) + - ./logs:/opt/xiaozhi-esp32-server/logs + + # ============================================================================ + # manager-web (Management Console + API) + # ============================================================================ + xiaozhi-esp32-server-web: + # Build from local source (supports ARM64/Apple Silicon) + build: + context: ../../ + dockerfile: Dockerfile-web + image: xiaozhi-esp32-server-web:local + + # Option: Use pre-built image from registry (x86 only) + # image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest + # platform: linux/amd64 # Uncomment to force x86 emulation on ARM64 + + container_name: xiaozhi-esp32-server-web + restart: unless-stopped + networks: + - xiaozhi-network + depends_on: + xiaozhi-esp32-server-db: + condition: service_healthy + xiaozhi-esp32-server-redis: + condition: service_healthy + ports: + # Management console and API + - "8002:8002" + environment: + - TZ=Asia/Shanghai + - SPRING_PROFILES_ACTIVE=dev + # Database connection + - SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://xiaozhi-esp32-server-db:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&failOverReadOnly=false&maxReconnects=10 + - SPRING_DATASOURCE_DRUID_USERNAME=root + - SPRING_DATASOURCE_DRUID_PASSWORD=123456 + # Redis connection + - SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis + - SPRING_DATA_REDIS_PORT=6379 + - SPRING_DATA_REDIS_PASSWORD= + volumes: + # Upload files directory + - ./uploadfile:/uploadfile + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + + # ============================================================================ + # MySQL Database + # ============================================================================ + xiaozhi-esp32-server-db: + image: mysql:8.0 + container_name: xiaozhi-esp32-server-db + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # Expose MySQL port for local debugging (optional) + - "3307:3306" + volumes: + # Persistent database storage + - ./mysql/data:/var/lib/mysql + # MySQL configuration (optional) + # - ./mysql/conf:/etc/mysql/conf.d + environment: + - TZ=Asia/Shanghai + - MYSQL_ROOT_PASSWORD=123456 + - MYSQL_DATABASE=xiaozhi_esp32_server + - MYSQL_INITDB_ARGS=--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci + command: + - --character-set-server=utf8mb4 + - --collation-server=utf8mb4_unicode_ci + - --default-authentication-plugin=mysql_native_password + - --max_connections=1000 + - --max_allowed_packet=256M + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p123456"] + timeout: 45s + interval: 10s + retries: 10 + start_period: 60s + + # ============================================================================ + # Redis Cache + # ============================================================================ + xiaozhi-esp32-server-redis: + image: redis:7-alpine + container_name: xiaozhi-esp32-server-redis + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # Expose Redis port for local debugging (optional) + - "6380:6379" + volumes: + # Persistent Redis data (optional) + - ./redis/data:/data + environment: + - TZ=Asia/Shanghai + command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru + logging: + driver: "json-file" + options: + max-size: "5m" + max-file: "3" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 10s + +# ============================================================================ +# Networks +# ============================================================================ +networks: + xiaozhi-network: + driver: bridge + name: xiaozhi-local-network + +# ============================================================================ +# Volumes (optional - for named volumes instead of bind mounts) +# ============================================================================ +# volumes: +# mysql-data: +# redis-data: + diff --git a/main/xiaozhi-server/docker-compose_sg_all.yml b/main/xiaozhi-server/docker-compose_sg_all.yml new file mode 100644 index 000000000..a112fd8b1 --- /dev/null +++ b/main/xiaozhi-server/docker-compose_sg_all.yml @@ -0,0 +1,181 @@ +# Docker Compose configuration for local development +# This file uses locally built images instead of pulling from remote registry + +services: + # ============================================================================ + # xiaozhi-server (Python WebSocket Server) + # ============================================================================ + xiaozhi-esp32-server: + build: + context: . + dockerfile: Dockerfile + image: xiaozhi-esp32-server:local + container_name: xiaozhi-esp32-server + depends_on: + xiaozhi-esp32-server-db: + condition: service_healthy + xiaozhi-esp32-server-redis: + condition: service_healthy + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # WebSocket server + - "8000:8000" + # HTTP server for vision analysis and OTA + - "8003:8003" + security_opt: + - seccomp:unconfined + environment: + - TZ=Asia/Shanghai + - PYTHONUNBUFFERED=1 + - LOG_LEVEL=INFO + - REGION=SINGAPORE + healthcheck: + disable: true + volumes: + # Configuration directory + - ./data:/opt/xiaozhi-esp32-server/data + # Custom config (optional override, uncomment if you need to customize) + - ./custom_config.yaml:/opt/xiaozhi-esp32-server/custom_config.yaml + # Model files (important!) + - ./models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall + - ./models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad + # Temporary files + - ./tmp:/opt/xiaozhi-esp32-server/tmp + # Music files (optional) + - ./music:/opt/xiaozhi-esp32-server/music + # Logs (optional, for debugging) + - ./logs:/opt/xiaozhi-esp32-server/logs + + # ============================================================================ + # manager-web (Management Console + API) + # ============================================================================ + xiaozhi-esp32-server-web: + # Build from local source (supports ARM64/Apple Silicon) + build: + context: ../../ + dockerfile: Dockerfile-web + image: xiaozhi-esp32-server-web:local + + # Option: Use pre-built image from registry (x86 only) + # image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest + # platform: linux/amd64 # Uncomment to force x86 emulation on ARM64 + + container_name: xiaozhi-esp32-server-web + restart: unless-stopped + networks: + - xiaozhi-network + depends_on: + xiaozhi-esp32-server-db: + condition: service_healthy + xiaozhi-esp32-server-redis: + condition: service_healthy + ports: + # Management console and API + - "8002:8002" + environment: + - TZ=Asia/Shanghai + - SPRING_PROFILES_ACTIVE=dev + # Database connection + - SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://xiaozhi-esp32-server-db:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&failOverReadOnly=false&maxReconnects=10 + - SPRING_DATASOURCE_DRUID_USERNAME=root + - SPRING_DATASOURCE_DRUID_PASSWORD=123456 + # Redis connection + - SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis + - SPRING_DATA_REDIS_PORT=6379 + - SPRING_DATA_REDIS_PASSWORD= + volumes: + # Upload files directory + - ./uploadfile:/uploadfile + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + + # ============================================================================ + # MySQL Database + # ============================================================================ + xiaozhi-esp32-server-db: + image: mysql:8.0 + container_name: xiaozhi-esp32-server-db + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # Expose MySQL port for local debugging (optional) + - "3307:3306" + volumes: + # Persistent database storage + - ./mysql/data:/var/lib/mysql + # MySQL configuration (optional) + # - ./mysql/conf:/etc/mysql/conf.d + environment: + - TZ=Asia/Shanghai + - MYSQL_ROOT_PASSWORD=123456 + - MYSQL_DATABASE=xiaozhi_esp32_server + - MYSQL_INITDB_ARGS=--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci + command: + - --character-set-server=utf8mb4 + - --collation-server=utf8mb4_unicode_ci + - --default-authentication-plugin=mysql_native_password + - --max_connections=1000 + - --max_allowed_packet=256M + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p123456"] + timeout: 45s + interval: 10s + retries: 10 + start_period: 60s + + # ============================================================================ + # Redis Cache + # ============================================================================ + xiaozhi-esp32-server-redis: + image: redis:7-alpine + container_name: xiaozhi-esp32-server-redis + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # Expose Redis port for local debugging (optional) + - "6380:6379" + volumes: + # Persistent Redis data (optional) + - ./redis/data:/data + environment: + - TZ=Asia/Shanghai + command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru + logging: + driver: "json-file" + options: + max-size: "5m" + max-file: "3" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 10s + +# ============================================================================ +# Networks +# ============================================================================ +networks: + xiaozhi-network: + driver: bridge + name: xiaozhi-local-network + +# ============================================================================ +# Volumes (optional - for named volumes instead of bind mounts) +# ============================================================================ +# volumes: +# mysql-data: +# redis-data: + diff --git a/main/xiaozhi-server/docker-compose_us_all.yml b/main/xiaozhi-server/docker-compose_us_all.yml new file mode 100644 index 000000000..06a7ec213 --- /dev/null +++ b/main/xiaozhi-server/docker-compose_us_all.yml @@ -0,0 +1,181 @@ +# Docker Compose configuration for local development +# This file uses locally built images instead of pulling from remote registry + +services: + # ============================================================================ + # xiaozhi-server (Python WebSocket Server) + # ============================================================================ + xiaozhi-esp32-server: + build: + context: . + dockerfile: Dockerfile + image: xiaozhi-esp32-server:local + container_name: xiaozhi-esp32-server + depends_on: + xiaozhi-esp32-server-db: + condition: service_healthy + xiaozhi-esp32-server-redis: + condition: service_healthy + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # WebSocket server + - "8000:8000" + # HTTP server for vision analysis and OTA + - "8003:8003" + security_opt: + - seccomp:unconfined + healthcheck: + disable: true + environment: + - TZ=Asia/Shanghai + - PYTHONUNBUFFERED=1 + - LOG_LEVEL=INFO + - REGION=US-WEST-2 + volumes: + # Configuration directory + - ./data:/opt/xiaozhi-esp32-server/data + # Custom config (optional override, uncomment if you need to customize) + - ./custom_config.yaml:/opt/xiaozhi-esp32-server/custom_config.yaml + # Model files (important!) + - ./models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall + - ./models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad + # Temporary files + - ./tmp:/opt/xiaozhi-esp32-server/tmp + # Music files (optional) + - ./music:/opt/xiaozhi-esp32-server/music + # Logs (optional, for debugging) + - ./logs:/opt/xiaozhi-esp32-server/logs + + # ============================================================================ + # manager-web (Management Console + API) + # ============================================================================ + xiaozhi-esp32-server-web: + # Build from local source (supports ARM64/Apple Silicon) + build: + context: ../../ + dockerfile: Dockerfile-web + image: xiaozhi-esp32-server-web:local + + # Option: Use pre-built image from registry (x86 only) + # image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest + # platform: linux/amd64 # Uncomment to force x86 emulation on ARM64 + + container_name: xiaozhi-esp32-server-web + restart: unless-stopped + networks: + - xiaozhi-network + depends_on: + xiaozhi-esp32-server-db: + condition: service_healthy + xiaozhi-esp32-server-redis: + condition: service_healthy + ports: + # Management console and API + - "8002:8002" + environment: + - TZ=Asia/Shanghai + - SPRING_PROFILES_ACTIVE=dev + # Database connection + - SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://xiaozhi-esp32-server-db:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&failOverReadOnly=false&maxReconnects=10 + - SPRING_DATASOURCE_DRUID_USERNAME=root + - SPRING_DATASOURCE_DRUID_PASSWORD=123456 + # Redis connection + - SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis + - SPRING_DATA_REDIS_PORT=6379 + - SPRING_DATA_REDIS_PASSWORD= + volumes: + # Upload files directory + - ./uploadfile:/uploadfile + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + + # ============================================================================ + # MySQL Database + # ============================================================================ + xiaozhi-esp32-server-db: + image: mysql:8.0 + container_name: xiaozhi-esp32-server-db + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # Expose MySQL port for local debugging (optional) + - "3307:3306" + volumes: + # Persistent database storage + - ./mysql/data:/var/lib/mysql + # MySQL configuration (optional) + # - ./mysql/conf:/etc/mysql/conf.d + environment: + - TZ=Asia/Shanghai + - MYSQL_ROOT_PASSWORD=123456 + - MYSQL_DATABASE=xiaozhi_esp32_server + - MYSQL_INITDB_ARGS=--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci + command: + - --character-set-server=utf8mb4 + - --collation-server=utf8mb4_unicode_ci + - --default-authentication-plugin=mysql_native_password + - --max_connections=1000 + - --max_allowed_packet=256M + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p123456"] + timeout: 45s + interval: 10s + retries: 10 + start_period: 60s + + # ============================================================================ + # Redis Cache + # ============================================================================ + xiaozhi-esp32-server-redis: + image: redis:7-alpine + container_name: xiaozhi-esp32-server-redis + restart: unless-stopped + networks: + - xiaozhi-network + ports: + # Expose Redis port for local debugging (optional) + - "6380:6379" + volumes: + # Persistent Redis data (optional) + - ./redis/data:/data + environment: + - TZ=Asia/Shanghai + command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru + logging: + driver: "json-file" + options: + max-size: "5m" + max-file: "3" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 10s + +# ============================================================================ +# Networks +# ============================================================================ +networks: + xiaozhi-network: + driver: bridge + name: xiaozhi-local-network + +# ============================================================================ +# Volumes (optional - for named volumes instead of bind mounts) +# ============================================================================ +# volumes: +# mysql-data: +# redis-data: + diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt index bc9d6956c..b67be8248 100644 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -36,3 +36,10 @@ psutil==7.0.0 portalocker==3.2.0 Jinja2==3.1.6 vosk==0.3.44 + +redis>=4.0.0,<5.0.0 + +elevenlabs>=1.11.0 +cartesia>=1.0.0 +deepgram-sdk>=3.0.0 +fish-audio-sdk==2025.6.3 \ No newline at end of file diff --git a/main/xiaozhi-server/start.sh b/main/xiaozhi-server/start.sh new file mode 100755 index 000000000..5f8b7699b --- /dev/null +++ b/main/xiaozhi-server/start.sh @@ -0,0 +1,174 @@ +#!/bin/bash + +# Xiaozhi Server Startup Script +# Usage: ./start.sh --region --action +# Region: sg, us, local +# Action: server, all + +set -e + +# Color definitions +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +CYAN='\033[0;36m' +NC='\033[0m' # No Color + +# Display banner +echo -e "${CYAN}" +echo "==================================" +echo " Xiaozhi Server Startup Script" +echo "==================================" +echo -e "${NC}" + +# Function to display usage +show_usage() { + echo -e "${RED}Error: Missing or invalid arguments${NC}" + echo "" + echo "Usage: $0 --region --action " + echo "" + echo "Options:" + echo " -r, --region Deployment region" + echo " Values: sg, us, local" + echo "" + echo " -a, --action Action to perform" + echo " Values: server, web, all" + echo "" + echo " -h, --help Show this help message" + echo "" + echo "Region details:" + echo " sg - Singapore (REGION=SINGAPORE)" + echo " us - US West 2 (REGION=US-WEST-2)" + echo " local - Local development (REGION=LOCAL)" + echo "" + echo "Action details:" + echo " server - Rebuild and restart xiaozhi-esp32-server" + echo " web - Rebuild and restart xiaozhi-esp32-server-web (manager-api + manager-web)" + echo " all - Rebuild and restart server + web (does not rebuild db/redis)" + echo "" + echo "Examples:" + echo " $0 --region sg --action server" + echo " $0 -r local -a web" + echo " $0 --region local --action all" + exit 1 +} + +# Parse command line arguments +REGION="" +ACTION="" + +while [[ $# -gt 0 ]]; do + case $1 in + -r|--region) + REGION="$2" + shift 2 + ;; + -a|--action) + ACTION="$2" + shift 2 + ;; + -h|--help) + show_usage + ;; + *) + echo -e "${RED}Error: Unknown option '$1'${NC}" + echo "" + show_usage + ;; + esac +done + +# Check if required arguments are provided +if [ -z "$REGION" ] || [ -z "$ACTION" ]; then + show_usage +fi + +# Validate region +case $REGION in + sg|SG) + COMPOSE_FILE="docker-compose_sg_all.yml" + REGION_NAME="Singapore" + REGION_ENV="SINGAPORE" + ;; + us|US) + COMPOSE_FILE="docker-compose_us_all.yml" + REGION_NAME="US West 2" + REGION_ENV="US-WEST-2" + ;; + local|LOCAL) + COMPOSE_FILE="docker-compose_local_all.yml" + REGION_NAME="Local" + REGION_ENV="LOCAL" + ;; + *) + echo -e "${RED}Error: Invalid region '${REGION}'${NC}" + echo "Valid regions: sg, us, local" + exit 1 + ;; +esac + +# Validate action +case $ACTION in + server|SERVER) + ACTION_NAME="Server Only" + SERVICES="xiaozhi-esp32-server" + ;; + web|WEB) + ACTION_NAME="Web Only (Manager API + Web)" + SERVICES="xiaozhi-esp32-server-web" + ;; + all|ALL) + ACTION_NAME="Server + Web" + SERVICES="xiaozhi-esp32-server xiaozhi-esp32-server-web" + ;; + *) + echo -e "${RED}Error: Invalid action '${ACTION}'${NC}" + echo "Valid actions: server, web, all" + exit 1 + ;; +esac + +# Check if compose file exists +if [ ! -f "$COMPOSE_FILE" ]; then + echo -e "${RED}Error: Compose file '${COMPOSE_FILE}' not found${NC}" + exit 1 +fi + +echo -e "${GREEN}Configuration:${NC}" +echo " Region: ${REGION_NAME} (${REGION_ENV})" +echo " Action: ${ACTION_NAME}" +echo " Compose file: ${COMPOSE_FILE}" +echo "" + +# Display current status +echo -e "${BLUE}Current container status:${NC}" +docker ps --filter name=xiaozhi --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" 2>/dev/null || echo "No containers running" +echo "" + +# Execute action with rebuild +echo -e "${YELLOW}→ Rebuilding and starting: ${ACTION_NAME}${NC}" +echo -e "${CYAN} Services: ${SERVICES}${NC}" +echo "" + +# Use up --build -d to rebuild images and start containers +docker compose -f "$COMPOSE_FILE" up --build -d $SERVICES + +echo "" +echo -e "${GREEN}✓ Operation completed${NC}" +echo "" + +# Display final status +echo -e "${BLUE}Updated container status:${NC}" +docker ps --filter name=xiaozhi --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" +echo "" + +# Show logs option +echo -e "${CYAN}To view logs, run:${NC}" +if [ -n "$SERVICES" ]; then + echo " docker compose -f $COMPOSE_FILE logs -f $SERVICES" +else + echo " docker compose -f $COMPOSE_FILE logs -f" +fi +echo "" +