From f052047d65d3149f06599242fd628220e97daa04 Mon Sep 17 00:00:00 2001 From: pany-05 Date: Thu, 30 Oct 2025 15:10:19 +0800 Subject: [PATCH 1/3] [feature] update system prompt --- main/xiaozhi-server/config.yaml | 17 + main/xiaozhi-server/core/connection.py | 117 +++- .../core/providers/llm/openai/openai.py | 239 ++++++- .../core/providers/memory/mem0ai/mem0ai.py | 35 + .../memory/mem_local_short/mem_local_short.py | 55 ++ .../core/providers/tts/elevenlabs/tts.py | 626 ++++++++++++++++++ .../core/providers/tts/stream_adapter.py | 263 ++++++++ main/xiaozhi-server/core/roles/__init__.py | 14 + .../core/roles/data/default.yaml | 38 ++ .../core/roles/data/hospital_assistant.yaml | 66 ++ main/xiaozhi-server/core/roles/factory.py | 70 ++ .../xiaozhi-server/core/roles/local_loader.py | 108 +++ main/xiaozhi-server/core/roles/models.py | 39 ++ .../core/roles/prompts/__init__.py | 5 + .../core/roles/prompts/builder.py | 213 ++++++ .../core/roles/prompts/languages/en.md | 5 + .../core/roles/prompts/languages/zh.md | 6 + .../xiaozhi-server/core/roles/prompts/role.md | 41 ++ .../core/roles/prompts/user_persona.md | 14 + main/xiaozhi-server/core/tokenize/__init__.py | 28 + .../core/tokenize/_basic_sent.py | 79 +++ main/xiaozhi-server/core/utils/dialogue.py | 6 +- .../core/utils/prompt_manager.py | 97 ++- main/xiaozhi-server/core/websocket_server.py | 9 + 24 files changed, 2084 insertions(+), 106 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/tts/elevenlabs/tts.py create mode 100644 main/xiaozhi-server/core/providers/tts/stream_adapter.py create mode 100644 main/xiaozhi-server/core/roles/__init__.py create mode 100644 main/xiaozhi-server/core/roles/data/default.yaml create mode 100644 main/xiaozhi-server/core/roles/data/hospital_assistant.yaml create mode 100644 main/xiaozhi-server/core/roles/factory.py create mode 100644 main/xiaozhi-server/core/roles/local_loader.py create mode 100644 main/xiaozhi-server/core/roles/models.py create mode 100644 main/xiaozhi-server/core/roles/prompts/__init__.py create mode 100644 main/xiaozhi-server/core/roles/prompts/builder.py create mode 100644 main/xiaozhi-server/core/roles/prompts/languages/en.md create mode 100644 main/xiaozhi-server/core/roles/prompts/languages/zh.md create mode 100644 main/xiaozhi-server/core/roles/prompts/role.md create mode 100644 main/xiaozhi-server/core/roles/prompts/user_persona.md create mode 100644 main/xiaozhi-server/core/tokenize/__init__.py create mode 100644 main/xiaozhi-server/core/tokenize/_basic_sent.py diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 248be252e..90e9edb38 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 # 是否开启结束语 diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 92043e9bd..9dc15fcd2 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -439,11 +439,28 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") def _init_prompt_enhancement(self): + """初始化并更新系统提示词""" # 更新上下文信息 self.prompt_manager.update_context_info(self, 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 = self.prompt_manager.build_enhanced_prompt( - self.config["prompt"], self.device_id, self.client_ip + self.config["prompt"], + self.device_id, + self.client_ip, + user_persona=user_persona, ) + if enhanced_prompt: self.change_system_prompt(enhanced_prompt) self.logger.bind(tag=TAG).info("系统提示词已增强更新") @@ -753,24 +770,97 @@ 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接口 - llm_responses = self.llm.response_with_functions( - self.session_id, - self.dialogue.get_llm_dialogue_with_memory( - memory_str, self.config.get("voiceprint", {}) - ), - functions=functions, + # response_with_functions 是异步生成器,使用队列在线程间传递 + response_queue = queue.Queue() + stop_flag = threading.Event() + + async def consume_async_generator(): + try: + async_gen = self.llm.response_with_functions( + self.session_id, + dialogue_history, + functions=functions, + ) + async for item in async_gen: + if stop_flag.is_set(): + break + response_queue.put(item) + response_queue.put(None) # 结束标记 + except Exception as e: + self.logger.bind(tag=TAG).error(f"异步生成器消费出错: {e}", exc_info=True) + response_queue.put(None) + response_queue.put(("ERROR", str(e))) + + asyncio.run_coroutine_threadsafe( + consume_async_generator(), self.loop ) + + # 从队列中获取响应 + def get_responses(): + while True: + try: + item = response_queue.get(timeout=300) # 5分钟超时 + if item is None: + break + if isinstance(item, tuple) and item[0] == "ERROR": + raise Exception(item[1]) + yield item + except queue.Empty: + self.logger.bind(tag=TAG).warning("等待 LLM 响应超时") + stop_flag.set() + break + + llm_responses = get_responses() else: - llm_responses = self.llm.response( - self.session_id, - self.dialogue.get_llm_dialogue_with_memory( - memory_str, self.config.get("voiceprint", {}) - ), + # response 也是异步生成器,使用队列在线程间传递 + response_queue = queue.Queue() + stop_flag = threading.Event() + + async def consume_async_generator(): + try: + async_gen = self.llm.response( + self.session_id, + dialogue_history, + ) + async for item in async_gen: + if stop_flag.is_set(): + break + response_queue.put(item) + response_queue.put(None) # 结束标记 + except Exception as e: + self.logger.bind(tag=TAG).error(f"异步生成器消费出错: {e}", exc_info=True) + response_queue.put(None) + response_queue.put(("ERROR", str(e))) + + asyncio.run_coroutine_threadsafe( + consume_async_generator(), self.loop ) + + # 从队列中获取响应 + def get_responses(): + while True: + try: + item = response_queue.get(timeout=300) # 5分钟超时 + if item is None: + break + if isinstance(item, tuple) and item[0] == "ERROR": + raise Exception(item[1]) + yield item + except queue.Empty: + self.logger.bind(tag=TAG).warning("等待 LLM 响应超时") + stop_flag.set() + break + + llm_responses = get_responses() 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 +871,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..18548e4c2 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -49,33 +49,39 @@ class LLMProvider(LLMProviderBase): self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=httpx.Timeout(self.timeout)) def response(self, session_id, dialogue, **kwargs): + """ + 同步流式响应方法 + 注意:保持同步以兼容基类和其他 LLM 提供商 + """ try: - responses = self.client.chat.completions.create( + # Create streaming response + # 注意:ChatGLM 等服务可能不支持 responses.create API,改用标准的 chat.completions.create + stream = self.client.chat.completions.create( model=self.model_name, messages=dialogue, stream=True, max_tokens=kwargs.get("max_tokens", self.max_tokens), temperature=kwargs.get("temperature", self.temperature), top_p=kwargs.get("top_p", self.top_p), - frequency_penalty=kwargs.get( - "frequency_penalty", self.frequency_penalty - ), + frequency_penalty=kwargs.get("frequency_penalty", self.frequency_penalty), ) - + is_active = True - for chunk in responses: + + for chunk in stream: try: - # 检查是否存在有效的choice且content不为空 - delta = ( - chunk.choices[0].delta - if getattr(chunk, "choices", None) - else None - ) - content = delta.content if hasattr(delta, "content") else "" - except IndexError: - content = "" - if content: - # 处理标签跨多个chunk的情况 + # Handle response choices + if not hasattr(chunk, "choices") or not chunk.choices: + continue + + delta = chunk.choices[0].delta + content = getattr(delta, "content", None) + + if content is None: + continue + + # Handle thinking tags (for reasoning models like o1) + # Filter out content between ... if "" in content: is_active = False content = content.split("")[0] @@ -84,31 +90,192 @@ class LLMProvider(LLMProviderBase): content = content.split("")[-1] if is_active: yield content + + except (IndexError, AttributeError) as e: + continue + except Exception as e: + logger.bind(tag=TAG).error(f"处理 chunk 时发生未预期错误: {e}", exc_info=True) + continue except Exception as e: - logger.bind(tag=TAG).error(f"Error in response generation: {e}") + logger.bind(tag=TAG).error(f"Error in response generation: {e}", exc_info=True) def response_with_functions(self, session_id, dialogue, functions=None): + """ + 同步流式响应方法(支持函数调用) + 注意:保持同步以兼容基类和其他 LLM 提供商 + """ try: - stream = self.client.chat.completions.create( - model=self.model_name, messages=dialogue, stream=True, tools=functions - ) + # Prepare request parameters + request_params = { + "model": self.model_name, + "messages": dialogue, + "stream": True, + } + + # Add tools/functions if provided + if functions: + request_params["tools"] = functions + + # Create streaming response (同步版本,移除 await) + stream = self.client.chat.completions.create(**request_params) for chunk in stream: - # 检查是否存在有效的choice且content不为空 - if getattr(chunk, "choices", None): - yield chunk.choices[0].delta.content, chunk.choices[ - 0 - ].delta.tool_calls - # 存在 CompletionUsage 消息时,生成 Token 消耗 log - elif isinstance(getattr(chunk, "usage", None), CompletionUsage): - usage_info = getattr(chunk, "usage", None) - logger.bind(tag=TAG).info( - f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," - f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," - f"共计 {getattr(usage_info, 'total_tokens', '未知')}" - ) + try: + # Handle token usage reporting + if hasattr(chunk, "usage") and isinstance(chunk.usage, CompletionUsage): + usage_info = chunk.usage + logger.bind(tag=TAG).info( + f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," + f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," + f"共计 {getattr(usage_info, 'total_tokens', '未知')}" + ) + continue + + # Handle response choices + if not hasattr(chunk, "choices") or not chunk.choices: + continue + + delta = chunk.choices[0].delta + + # Extract content and tool calls + content = getattr(delta, "content", None) + tool_calls = getattr(delta, "tool_calls", None) + + # Yield the chunk + yield content, tool_calls + + except (IndexError, AttributeError) as e: + continue + except openai.APIError as e: + error_msg = f"OpenAI API error: {e.message if hasattr(e, 'message') else str(e)}" + logger.bind(tag=TAG).error(error_msg) + yield f"【API错误: {error_msg}】", None + + except openai.APIConnectionError as e: + error_msg = f"Connection error: {str(e)}" + logger.bind(tag=TAG).error(error_msg) + yield f"【连接错误: 无法连接到服务】", None + + except openai.RateLimitError as e: + error_msg = f"Rate limit exceeded: {str(e)}" + logger.bind(tag=TAG).error(error_msg) + yield f"【请求过于频繁,请稍后再试】", None + except Exception as e: - logger.bind(tag=TAG).error(f"Error in function call streaming: {e}") - yield f"【OpenAI服务响应异常: {e}】", None + error_msg = f"Unexpected error in function calling: {type(e).__name__}: {str(e)}" + logger.bind(tag=TAG).error(error_msg, exc_info=True) + yield f"【OpenAI服务响应异常: {str(e)}】", None + + async def response_stream( + self, + chat_ctx: ChatContext, + **kwargs: Any + ) -> AsyncGenerator[ChatChunk, None]: + """ + New streaming interface using standard protocol + + This method implements the new standard interface defined in LLMProviderBase. + It uses: + - ChatContext as input (standard dialogue protocol) + - ChatChunk as output (standard streaming protocol) + - OpenAI Responses API (modern response.create) + + Args: + chat_ctx: Standard ChatContext with dialogue history + **kwargs: Additional options: + - max_output_tokens: Override max tokens + - temperature: Override temperature + - top_p: Override top_p + - frequency_penalty: Override frequency penalty + + Yields: + ChatChunk: Standardized streaming chunks with deltas and usage + + Example: + async for chunk in provider.response_stream(chat_ctx): + if chunk.delta and chunk.delta.content: + print(chunk.delta.content) + if chunk.usage: + print(f"Tokens: {chunk.usage.total_tokens}") + """ + try: + # 1. Convert ChatContext to OpenAI format + messages, _ = chat_ctx.to_provider_format(format="openai") + + logger.bind(tag=TAG).debug( + f"Starting streaming with model={self.model_name}, " + f"messages_count={len(messages)}" + ) + + # 2. Prepare request parameters + max_output_tokens = kwargs.get("max_output_tokens", self.max_output_tokens) + temperature = kwargs.get("temperature", self.temperature) + top_p = kwargs.get("top_p", self.top_p) + frequency_penalty = kwargs.get("frequency_penalty", self.frequency_penalty) + + # 3. Call OpenAI Responses API + # TODO: system instruction needs to be added + stream: AsyncStream[ResponseStreamEvent] = await self.client.responses.create( + input=messages, + model=self.model_name, + stream=True, + max_output_tokens=max_output_tokens, + temperature=temperature, + top_p=top_p, + frequency_penalty=frequency_penalty, + ) + + # 4. Parse stream and yield ChatChunk (focus on output_item.done + completed) + async for event in stream: + try: + chunk = self._parse_response_event(event) + if chunk: + yield chunk + except (IndexError, AttributeError) as e: + logger.bind(tag=TAG).debug(f"Skipping malformed event: {e}") + continue + + logger.bind(tag=TAG).debug("Stream completed successfully") + + except openai.APIError as e: + error_msg = f"OpenAI API error: {e.message if hasattr(e, 'message') else str(e)}" + logger.bind(tag=TAG).error(error_msg) + # Yield error chunk + yield ChatChunk( + delta=ChatDelta( + role="assistant", + content=f"【API错误: {error_msg}】" + ) + ) + + except openai.APIConnectionError as e: + error_msg = f"Connection error: {str(e)}" + logger.bind(tag=TAG).error(error_msg) + yield ChatChunk( + delta=ChatDelta( + role="assistant", + content="【连接错误: 无法连接到服务】" + ) + ) + + except openai.RateLimitError as e: + error_msg = f"Rate limit exceeded: {str(e)}" + logger.bind(tag=TAG).error(error_msg) + yield ChatChunk( + delta=ChatDelta( + role="assistant", + content="【请求过于频繁,请稍后再试】" + ) + ) + + except Exception as e: + error_msg = f"Unexpected error: {type(e).__name__}: {str(e)}" + logger.bind(tag=TAG).error(error_msg) + yield ChatChunk( + delta=ChatDelta( + role="assistant", + content=f"【服务异常: {str(e)}】" + ) + ) 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/elevenlabs/tts.py b/main/xiaozhi-server/core/providers/tts/elevenlabs/tts.py new file mode 100644 index 000000000..f79614b78 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/elevenlabs/tts.py @@ -0,0 +1,626 @@ +from __future__ import annotations + +""" +ElevenLabs TTS Implementation + +Provides WebSocket-based streaming text-to-speech using ElevenLabs' multi-stream API. +Supports multiple concurrent synthesis streams over a single WebSocket connection. +""" + +""" +TODO: change api to elevenlabs SDK using streaming API +""" + +import asyncio +import base64 +import dataclasses +import json +import os +import weakref +from dataclasses import dataclass +from typing import Any, Union + +import aiohttp +from typing import Optional + +from config.logger import setup_logging +from core.tokenize import SentenceTokenizer, WordTokenizer, blingfire +from core.utils.aio import Chan, cancel_and_wait +from core.utils.short_uuid import shortuuid +from core.utils.http_context import http_session +from core.utils.errors import ( + APIConnectionError, + APITimeoutError, + APIStatusError, +) +from core.utils.types import ( + APIConnectOptions, + DEFAULT_API_CONNECT_OPTIONS, +) + +import core.providers.tts.base as tts +from ..emitter import AudioEmitter +from .models import ( + API_BASE_URL, + DEFAULT_VOICE_ID, + TTSEncoding, + TTSModels, + Voice, + VoiceSettings, + WS_INACTIVITY_TIMEOUT, +) + +logger = setup_logging() + + +def _sample_rate_from_format(output_format: TTSEncoding) -> int: + """Extract sample rate from encoding format string""" + if output_format.startswith("mp3_"): + return int(output_format.split("_")[1]) + elif output_format.startswith("pcm_"): + return int(output_format.split("_")[1]) + elif output_format.startswith("ulaw_"): + return int(output_format.split("_")[1]) + return 22050 # default + + +@dataclass +class _TTSOptions: + """Internal configuration for ElevenLabs TTS""" + api_key: str + voice_id: str + voice_settings: VoiceSettings | None + model: TTSModels | str + base_url: str + encoding: TTSEncoding + sample_rate: int + word_tokenizer: WordTokenizer | SentenceTokenizer + inactivity_timeout: int + auto_mode: bool + + def get_ws_url(self) -> str: + """Get WebSocket URL for multi-stream API""" + base = self.base_url.replace("http://", "ws://").replace("https://", "wss://") + params = [ + f"model_id={self.model}", + f"output_format={self.encoding}", + ] + if self.auto_mode: + params.append("auto_mode=true") + params.append(f"inactivity_timeout={self.inactivity_timeout}") + + url = f"{base}/text-to-speech/{self.voice_id}/multi-stream-input?" + url += "&".join(params) + return url + + +class TTS(tts.TTS): + """ + ElevenLabs TTS Provider + + Provides high-quality, emotionally rich text-to-speech with voice cloning support. + Uses multi-stream WebSocket API for efficient concurrent synthesis. + + Example: + tts = elevenlabs.TTS( + api_key="your-api-key", + voice_id="voice-id", + model="eleven_turbo_v2_5", + ) + + # Streaming synthesis + stream = tts.stream() + stream.push_text("Hello world!") + stream.end_input() + + async for audio in stream: + # Process audio + pass + """ + + def __init__( + self, + *, + api_key: str | None = None, + voice_id: str = DEFAULT_VOICE_ID, + voice_settings: VoiceSettings | None = None, + model: TTSModels | str = "eleven_multilingual_v2", + encoding: TTSEncoding = "pcm_16000", + word_tokenizer: WordTokenizer | SentenceTokenizer | None = None, + inactivity_timeout: int = WS_INACTIVITY_TIMEOUT, + auto_mode: Optional[bool] = None, + base_url: str = API_BASE_URL, + ) -> None: + """ + Initialize ElevenLabs TTS. + + Args: + api_key: ElevenLabs API key. If not provided, reads from ELEVEN_API_KEY env var + voice_id: Voice ID to use (default: Rachel voice) + voice_settings: Voice settings for fine-tuning quality + model: TTS model to use (default: "eleven_multilingual_v2") + encoding: Audio encoding format (default: "pcm_16000") + word_tokenizer: Word/sentence tokenizer (default: blingfire for auto_mode) + inactivity_timeout: WebSocket inactivity timeout in seconds + auto_mode: Enable auto mode for optimized latency (recommended) + base_url: API base URL (default: https://api.elevenlabs.io/v1) + """ + sample_rate = _sample_rate_from_format(encoding) + + super().__init__( + capabilities=tts.TTSCapabilities(streaming=True), + sample_rate=sample_rate, + num_channels=1, + ) + + # Validate API key + elevenlabs_api_key = api_key or os.environ.get("ELEVEN_API_KEY") + if not elevenlabs_api_key: + raise ValueError( + "ElevenLabs API key is required. " + "Provide via api_key parameter or set ELEVEN_API_KEY environment variable" + ) + + # Configure tokenizer + if not word_tokenizer: + if auto_mode: + word_tokenizer = blingfire.SentenceTokenizer() + else: + from core.tokenize.basic import WordTokenizer as BasicWordTokenizer + word_tokenizer = BasicWordTokenizer(ignore_punctuation=False) + + # Store options + self._opts = _TTSOptions( + api_key=elevenlabs_api_key, + voice_id=voice_id, + voice_settings=voice_settings, + model=model, + base_url=base_url, + encoding=encoding, + sample_rate=sample_rate, + word_tokenizer=word_tokenizer, + inactivity_timeout=inactivity_timeout, + auto_mode=auto_mode, + ) + self._session = http_session() + # Connection management + self._current_connection: _Connection | None = None + self._connection_lock = asyncio.Lock() + + # Track active streams + self._streams: weakref.WeakSet[SynthesizeStream] = weakref.WeakSet() + + @property + def model(self) -> str: + """Get the model name""" + return self._opts.model + + @property + def provider(self) -> str: + """Get the provider name""" + return "ElevenLabs" + + def _ensure_session(self) -> aiohttp.ClientSession: + """Ensure HTTP session exists""" + return http_session() + + async def current_connection(self) -> _Connection: + """Get or create the current WebSocket connection""" + async with self._connection_lock: + if ( + self._current_connection + and self._current_connection.is_current + and not self._current_connection._closed + ): + return self._current_connection + + # Create new connection + session = self._ensure_session() + conn = _Connection(self._opts, session) + await conn.connect() + self._current_connection = conn + return conn + + async def list_voices(self) -> list[Voice]: + """List available voices from ElevenLabs API""" + session = self._ensure_session() + url = f"{self._opts.base_url}/voices" + headers = {"xi-api-key": self._opts.api_key} + + async with session.get(url, headers=headers) as resp: + resp.raise_for_status() + data = await resp.json() + + voices = [] + for voice_data in data.get("voices", []): + voices.append( + Voice( + id=voice_data["voice_id"], + name=voice_data["name"], + category=voice_data["category"], + ) + ) + return voices + + def stream(self, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS) -> SynthesizeStream: + """ + Create a streaming synthesis session. + + Returns: + SynthesizeStream for incremental text input + """ + stream = SynthesizeStream(tts=self, conn_options=conn_options) + self._streams.add(stream) + return stream + + async def aclose(self) -> None: + """Close TTS provider and cleanup resources""" + # Close all active streams + for stream in list(self._streams): + await stream.aclose() + self._streams.clear() + + # Close connection + if self._current_connection: + await self._current_connection.aclose() + self._current_connection = None + + +class SynthesizeStream(tts.SynthesizeStream): + """Streaming synthesis using WebSocket (multi-stream)""" + + def __init__( + self, *, tts: TTS, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS + ) -> None: + super().__init__(tts=tts, conn_options=conn_options) + self._tts: TTS = tts + self._sent_tokenizer_stream = self._tts._opts.word_tokenizer.stream() + + async def aclose(self) -> None: + """Close stream and cleanup""" + await self._sent_tokenizer_stream.aclose() + await super().aclose() + + async def _run(self, output_emitter: AudioEmitter) -> None: + """ + Streaming synthesis implementation using multi-stream WebSocket. + + This method: + 1. Connects to the shared WebSocket connection + 2. Registers this stream with the connection + 3. Sets up tokenizer + 4. Runs two parallel tasks: + - _input_task: Reads from input_ch → tokenizer + - _sentence_task: Tokenizer → Connection (which sends to WebSocket) + 5. The connection's recv loop handles audio data and routes it to this stream's emitter + """ + opts = self._tts._opts + request_id = shortuuid() + context_id = shortuuid() # Generate context_id upfront for registration + + # Initialize output emitter + output_emitter.initialize( + request_id=request_id, + sample_rate=opts.sample_rate, + num_channels=1, + stream=True, + ) + + # Get shared connection + try: + connection = await asyncio.wait_for( + self._tts.current_connection(), timeout=10 + ) + except asyncio.TimeoutError as e: + raise APITimeoutError("Could not connect to ElevenLabs", timeout=10) from e + except Exception as e: + raise APIConnectionError(f"Could not connect to ElevenLabs: {e}") from e + + # Create waiter for completion + waiter: asyncio.Future[None] = asyncio.get_event_loop().create_future() + # Register stream with context_id + connection.register_stream(context_id, output_emitter, waiter) + + # Define tasks + async def _input_task() -> None: + """Forward input from input_ch to tokenizer""" + try: + async for data in self._input_ch: + if isinstance(data, self._FlushSentinel): + self._sent_tokenizer_stream.flush() + continue + self._sent_tokenizer_stream.push_text(data) + finally: + self._sent_tokenizer_stream.end_input() + + async def _sentence_task() -> None: + """Send tokenized sentences to connection""" + try: + async for sentence_ev in self._sent_tokenizer_stream: + text = sentence_ev.token + formatted_text = f"{text} " # Always end with space + connection.send_content(_SynthesizeContent(context_id, formatted_text)) + finally: + connection.send_content(_SynthesizeContent(context_id, "", flush=True)) + connection.close_context(context_id) + + # Run tasks + input_t = asyncio.create_task(_input_task(), name="elevenlabs_input") + sentence_t = asyncio.create_task(_sentence_task(), name="elevenlabs_sentence") + + try: + await waiter + except asyncio.TimeoutError as e: + raise TimeoutError("ElevenLabs synthesis timed out") from e + except Exception as e: + logger.bind(tag=__name__).error(f"Synthesis error: {e}") + raise + finally: + await cancel_and_wait(input_t, sentence_t) + + +@dataclass +class _SynthesizeContent: + """Content to synthesize""" + context_id: str + text: str + flush: bool = False + + +@dataclass +class _CloseContext: + """Command to close a context""" + context_id: str + + +@dataclass +class _StreamData: + """Data for a registered stream""" + emitter: AudioEmitter + stream: SynthesizeStream | None + waiter: asyncio.Future[None] + timeout_timer: asyncio.TimerHandle | None = None + + +class _Connection: + """ + Manages a single WebSocket connection with send/recv loops. + + Supports multiple concurrent synthesis contexts (multi-stream). + """ + + def __init__(self, opts: _TTSOptions, session: aiohttp.ClientSession) -> None: + self._opts = opts + self._session = session + self._ws: aiohttp.ClientWebSocketResponse | None = None + self._is_current = True + self._active_contexts: set[str] = set() + self._input_queue: Chan[Union[_SynthesizeContent, _CloseContext]] = Chan() + self._context_data: dict[str, _StreamData] = {} + self._send_task: asyncio.Task | None = None + self._recv_task: asyncio.Task | None = None + self._closed = False + + @property + def is_current(self) -> bool: + """Check if this connection is current""" + return self._is_current + + def mark_non_current(self) -> None: + """Mark this connection as no longer current""" + self._is_current = False + + async def connect(self) -> None: + """Establish WebSocket connection and start send/recv loops""" + if self._ws or self._closed: + return + + url = self._opts.get_ws_url() + headers = {"xi-api-key": self._opts.api_key} + + try: + self._ws = await asyncio.wait_for( + self._session.ws_connect(url, headers=headers), + timeout=10, + ) + except asyncio.TimeoutError as e: + raise APITimeoutError( + "Connection to ElevenLabs WebSocket timed out", + timeout=10, + ) from e + except aiohttp.ClientError as e: + raise APIConnectionError( + f"Failed to connect to ElevenLabs WebSocket: {e}", + url=url, + ) from e + + self._send_task = asyncio.create_task(self._send_loop(), name="elevenlabs_send") + self._recv_task = asyncio.create_task(self._recv_loop(), name="elevenlabs_recv") + + def register_stream( + self, + context_id: str, + emitter: AudioEmitter, + done_fut: asyncio.Future[None], + ) -> None: + """Register a new synthesis stream""" + self._context_data[context_id] = _StreamData( + emitter=emitter, + stream=None, # Stream reference not needed + waiter=done_fut, + ) + + def send_content(self, content: _SynthesizeContent) -> None: + """Send synthesis content to the connection""" + if self._closed or not self._ws or self._ws.closed: + raise ConnectionError("WebSocket connection is closed") + self._input_queue.send_nowait(content) + + def close_context(self, context_id: str) -> None: + """Close a specific context""" + if self._closed or not self._ws or self._ws.closed: + raise ConnectionError("WebSocket connection is closed") + self._input_queue.send_nowait(_CloseContext(context_id)) + + async def _send_loop(self) -> None: + """Send loop - processes messages from input queue""" + try: + while not self._closed: + try: + msg = await self._input_queue.recv() + except Exception: + break + + if not self._ws or self._ws.closed: + break + + if isinstance(msg, _SynthesizeContent): + is_new_context = msg.context_id not in self._active_contexts + + # Skip if not current and new context + if not self._is_current and is_new_context: + continue + + # Initialize context + if is_new_context: + voice_settings_dict = None + if self._opts.voice_settings: + voice_settings_dict = _strip_nones( + dataclasses.asdict(self._opts.voice_settings) + ) + + init_pkt = { + "text": " ", + "context_id": msg.context_id, + } + if voice_settings_dict: + init_pkt["voice_settings"] = voice_settings_dict + + await self._ws.send_json(init_pkt) + self._active_contexts.add(msg.context_id) + + # Send text + pkt: dict[str, Any] = { + "text": msg.text, + "context_id": msg.context_id, + } + if msg.flush: + pkt["flush"] = True + + await self._ws.send_json(pkt) + + elif isinstance(msg, _CloseContext): + if msg.context_id in self._active_contexts: + close_pkt = { + "context_id": msg.context_id, + "close_context": True, + } + await self._ws.send_json(close_pkt) + + except Exception as e: + logger.bind(tag=__name__).error(f"Send loop error: {e}") + finally: + if not self._closed: + await self.aclose() + + async def _recv_loop(self) -> None: + """Receive loop - processes messages from WebSocket""" + try: + while not self._closed and self._ws and not self._ws.closed: + msg = await self._ws.receive() + + if msg.type in ( + aiohttp.WSMsgType.CLOSED, + aiohttp.WSMsgType.CLOSE, + aiohttp.WSMsgType.CLOSING, + ): + raise APIStatusError( + "ElevenLabs connection closed unexpectedly", request_id="" + ) + + if msg.type != aiohttp.WSMsgType.TEXT: + logger.bind(tag=__name__).warning(f"Unexpected message type: {msg.type}") + continue + + data = json.loads(msg.data) + context_id = data.get("contextId") + + if not context_id or context_id not in self._context_data: + continue + + ctx = self._context_data[context_id] + + # Check for errors + if error := data.get("error"): + logger.bind(tag=__name__).error(f"ElevenLabs error: {error}") + if not ctx.waiter.done(): + ctx.waiter.set_exception(RuntimeError(f"ElevenLabs error: {error}")) + self._cleanup_context(context_id) + continue + + # Start segment on first audio + if audio_b64 := data.get("audio"): + # Check if this is the first audio for this context + if context_id not in self._active_contexts: + ctx.emitter.start_segment(segment_id=context_id) + self._active_contexts.add(context_id) + + audio_bytes = base64.b64decode(audio_b64) + ctx.emitter.push(audio_bytes) + + # Check if final + if data.get("isFinal"): + if not ctx.waiter.done(): + ctx.waiter.set_result(None) + self._cleanup_context(context_id) + + if not self._is_current and not self._active_contexts: + logger.bind(tag=__name__).debug("No active contexts, shutting down") + break + + except Exception as e: + logger.bind(tag=__name__).error(f"Receive loop error: {e}") + for ctx in self._context_data.values(): + if not ctx.waiter.done(): + ctx.waiter.set_exception(e) + self._context_data.clear() + finally: + if not self._closed: + await self.aclose() + + def _cleanup_context(self, context_id: str) -> None: + """Clean up context state""" + self._context_data.pop(context_id, None) + self._active_contexts.discard(context_id) + + async def aclose(self) -> None: + """Close the connection and clean up""" + if self._closed: + return + + self._closed = True + self._input_queue.close() + + # Complete all waiters + for ctx in self._context_data.values(): + if not ctx.waiter.done(): + ctx.waiter.set_exception(ConnectionError("Connection closed")) + self._context_data.clear() + + # Close WebSocket + if self._ws: + await self._ws.close() + + # Cancel tasks + if self._send_task: + await cancel_and_wait(self._send_task) + if self._recv_task: + await cancel_and_wait(self._recv_task) + + self._ws = None + + +def _strip_nones(data: dict[str, Any]) -> dict[str, Any]: + """Remove None values from dictionary""" + return {k: v for k, v in data.items() if v is not None} + diff --git a/main/xiaozhi-server/core/providers/tts/stream_adapter.py b/main/xiaozhi-server/core/providers/tts/stream_adapter.py new file mode 100644 index 000000000..60b151ab2 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/stream_adapter.py @@ -0,0 +1,263 @@ +""" +Stream Adapter - Wrap non-streaming TTS to provide streaming interface + +This module provides StreamAdapter, which wraps a non-streaming TTS provider +(that only supports synthesize()) and provides a streaming interface (stream()). + +The adapter works by: +1. Accepting incremental text input via push_text() +2. Using a sentence tokenizer to segment text into sentences +3. Calling the wrapped TTS's synthesize() for each sentence +4. Streaming the audio output as it becomes available + +This allows any non-streaming TTS to be used in streaming contexts. +""" + +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING + +from config.logger import setup_logging +from core.tokenize import SentenceTokenizer, blingfire +from core.tokenize import basic + +# 如果 blingfire 不可用,使用 basic 作为回退 +if blingfire is None: + _default_tokenizer_class = basic.SentenceTokenizer +else: + _default_tokenizer_class = blingfire.SentenceTokenizer +from core.utils.aio import Chan, cancel_and_wait +from core.utils.short_uuid import shortuuid + +from .base import SynthesizedAudio, TTS, SynthesizeStream, TTSCapabilities + +if TYPE_CHECKING: + from .emitter import AudioEmitter + from .pacer import SentenceStreamPacer + +logger = setup_logging() + + +class StreamAdapter(TTS): + """ + Wrap a non-streaming TTS to provide streaming interface. + + This adapter enables any TTS that supports synthesize() to be used + with the streaming API. It handles: + - Text tokenization into sentences + - Sequential synthesis of each sentence + - Optional pacing to optimize cost/quality + + Example: + # Wrap a non-streaming TTS + base_tts = SomeTTS(...) + streaming_tts = StreamAdapter( + tts=base_tts, + sentence_tokenizer=_default_tokenizer_class(), + text_pacing=True # Enable smart pacing + ) + + # Now use it as a streaming TTS + stream = streaming_tts.stream() + stream.push_text("Hello ") + stream.push_text("world!") + stream.end_input() + + async for audio in stream: + # Process audio frames + pass + """ + + def __init__( + self, + *, + tts: TTS, + sentence_tokenizer: SentenceTokenizer | None = None, + text_pacing: bool | SentenceStreamPacer = False, + ) -> None: + """ + Initialize StreamAdapter. + + Args: + tts: The non-streaming TTS to wrap + sentence_tokenizer: Tokenizer to segment text into sentences. + Defaults to basic.SentenceTokenizer() (or blingfire if available) + text_pacing: Smart pacing configuration: + - True: Use default SentenceStreamPacer + - SentenceStreamPacer instance: Use custom pacer + - False: No pacing (synthesize immediately) + """ + super().__init__( + capabilities=TTSCapabilities(streaming=True), + sample_rate=tts.sample_rate, + num_channels=tts.num_channels, + ) + self._wrapped_tts = tts + self._sentence_tokenizer = ( + sentence_tokenizer if sentence_tokenizer else _default_tokenizer_class() + ) + + self._stream_pacer: SentenceStreamPacer | None = None + if text_pacing is True: + from .pacer import SentenceStreamPacer + self._stream_pacer = SentenceStreamPacer() + elif text_pacing is not False: + # Assume it's a SentenceStreamPacer instance + self._stream_pacer = text_pacing + + @property + def model(self) -> str: + """Get the model from wrapped TTS""" + return self._wrapped_tts.model + + @property + def provider(self) -> str: + """Get the provider from wrapped TTS""" + return self._wrapped_tts.provider + + def synthesize(self, text: str) -> 'ChunkedStream': + """ + Synthesize using the wrapped TTS. + + Args: + text: Text to synthesize + + Returns: + ChunkedStream from the wrapped TTS + """ + return self._wrapped_tts.synthesize(text) + + def stream(self) -> StreamAdapterWrapper: + """ + Create a streaming synthesis session. + + Returns: + StreamAdapterWrapper: Streaming synthesis session + """ + return StreamAdapterWrapper(tts=self) + + def prewarm(self) -> None: + """Pre-warm the wrapped TTS""" + self._wrapped_tts.prewarm() + + async def aclose(self) -> None: + """Close the wrapped TTS""" + await self._wrapped_tts.aclose() + + +class StreamAdapterWrapper(SynthesizeStream): + """ + Streaming wrapper that synthesizes sentences sequentially. + + This class orchestrates: + 1. Reading incremental text from input channel + 2. Tokenizing text into sentences + 3. Optionally pacing sentence dispatch based on audio buffer + 4. Calling wrapped TTS for each sentence + 5. Streaming audio output + """ + + def __init__(self, *, tts: StreamAdapter) -> None: + """ + Initialize StreamAdapterWrapper. + + Args: + tts: The StreamAdapter instance + """ + super().__init__(tts=tts) + self._tts: StreamAdapter = tts + + async def _run(self, output_emitter: AudioEmitter) -> None: + """ + Main streaming synthesis logic. + + This method: + 1. Initializes the output emitter + 2. Creates sentence tokenizer stream (and optional pacer) + 3. Spawns two parallel tasks: + - _forward_input: Reads from input_ch → tokenizer + - _synthesize: Reads tokenized sentences → TTS → emitter + + Args: + output_emitter: AudioEmitter to push synthesized audio to + """ + # 1. Initialize output emitter + request_id = shortuuid() + output_emitter.initialize( + request_id=request_id, + sample_rate=self._tts.sample_rate, + num_channels=self._tts.num_channels, + stream=True, + ) + + # 2. Create sentence tokenizer stream + sent_stream = self._tts._sentence_tokenizer.stream() + + # 3. Optionally wrap with pacer + if self._tts._stream_pacer: + sent_stream = self._tts._stream_pacer.wrap( + sent_stream=sent_stream, + audio_emitter=output_emitter, + ) + + # 4. Start segment + segment_id = shortuuid() + output_emitter.start_segment(segment_id=segment_id) + + # 5. Define parallel tasks + async def _forward_input() -> None: + """Forward text from input channel to tokenizer""" + try: + async for data in self._input_ch: + if isinstance(data, self._FlushSentinel): + sent_stream.flush() + continue + + sent_stream.push_text(data) + finally: + sent_stream.end_input() + + async def _synthesize() -> None: + """ + Synthesize each sentence and push audio to emitter. + + For each tokenized sentence: + 1. Call wrapped_tts.synthesize(sentence) + 2. Stream audio frames from the synthesis + 3. Push each frame's audio data to output_emitter + 4. Flush after each sentence + """ + try: + async for sentence_ev in sent_stream: + # Skip empty sentences + text = sentence_ev.token.strip() + if not text: + continue + + # Synthesize this sentence using wrapped TTS + async with self._tts._wrapped_tts.synthesize(text) as tts_stream: + async for audio in tts_stream: + # Push audio data to emitter + # Note: audio.frame.data is memoryview, convert to bytes + audio_bytes = bytes(audio.frame.data) + output_emitter.push(audio_bytes) + + # Flush after each sentence + output_emitter.flush() + except Exception as e: + logger.bind(tag=__name__).error(f"Synthesis error: {e}") + raise + + # 6. Run both tasks in parallel + tasks = [ + asyncio.create_task(_forward_input(), name="forward_input"), + asyncio.create_task(_synthesize(), name="synthesize"), + ] + + try: + await asyncio.gather(*tasks) + finally: + await sent_stream.aclose() + await cancel_and_wait(*tasks) + 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..1d734cb77 --- /dev/null +++ b/main/xiaozhi-server/core/roles/data/default.yaml @@ -0,0 +1,38 @@ +id: default +version: 1 +wake_word: 小智 +language: zh +greeting: 你好!有什么可以帮助你的吗? +profile: | + # Personality + + 你是小智/小志,来自中国台湾省的00后女生。讲话超级机车,"真的假的啦"这样的台湾腔,喜欢用"笑死""是在哈喽"等流行梗,但会偷偷研究男友的编程书籍。 + + # Environment + + 你通过语音交互与用户对话。 + 用户可能在日常生活中的各种场景下与你交流。 + + # Tone + + - 讲话像连珠炮,但会突然冒出超温柔语气 + - 用梗密度高 + - 对科技话题有隐藏天赋(能看懂基础代码但假装不懂) + + # Goal + + 当用户: + - 讲冷笑话 → 用夸张笑声回应+模仿台剧腔"这什么鬼啦!" + - 讨论感情 → 炫耀程序员男友但抱怨"他只会送键盘当礼物" + - 问专业知识 → 先用梗回答,被追问才展示真实理解 + + # Guardrails + + 绝不: + - 长篇大论,叽叽歪歪 + - 长时间严肃对话 + + # Tools + + No tools provided. +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..54181d2d9 --- /dev/null +++ b/main/xiaozhi-server/core/roles/prompts/builder.py @@ -0,0 +1,213 @@ +""" +模块化系统提示词构建器 +负责构建完整的系统提示词,包括 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: + 格式化的系统上下文字符串 + """ + 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: + # 根据语言格式化日期 + if language == "zh": + today_date = now.strftime("%Y年%m月%d日") + else: + 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 = [] + + if language == "zh": + system_rules.append(f"- 用户开始对话的时间:{time_str}") + system_rules.append(f"- 今天日期:{today_date} ({today_weekday})") + if lunar_date: + system_rules.append(f"- 今天农历:{lunar_date}") + if local_address: + system_rules.append(f"- 用户所在城市:{local_address}") + if weather_info: + system_rules.append(f"- 当地未来7天天气:{weather_info}") + if device_id: + system_rules.append(f"- 设备ID:{device_id}") + system_rules.append(f"- 当前语言:**{language}**") + system_rules.append(f"- 时区:{timezone}") + else: + 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 = { + "system_context": system_context, + "user_persona_prompt": user_persona_prompt, + "language_specific_prompt": language_specific_prompt + } + + # Step 7: 填充模板(不包含 profile) + try: + template_content = ROLE_TEXT.format(**template_vars) + except KeyError as e: + logger.bind(tag=TAG).error(f"模板变量缺失: {e}") + template_content = "" + + # Step 8: 如果有 profile,将其放在最前面;否则只返回模板内容 + if profile_content and profile_content.strip(): + system_prompt = f"{profile_content.strip()}\n\n{template_content}" + else: + system_prompt = template_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..8767f4afd --- /dev/null +++ b/main/xiaozhi-server/core/roles/prompts/role.md @@ -0,0 +1,41 @@ +# 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/tokenize/__init__.py b/main/xiaozhi-server/core/tokenize/__init__.py new file mode 100644 index 000000000..241bd3a38 --- /dev/null +++ b/main/xiaozhi-server/core/tokenize/__init__.py @@ -0,0 +1,28 @@ +from . import basic, utils +try: + from . import blingfire +except ImportError: + blingfire = None + +from .token_stream import BufferedSentenceStream, BufferedWordStream +from .tokenizer import ( + SentenceStream, + SentenceTokenizer, + TokenData, + WordStream, + WordTokenizer, +) + +__all__ = [ + "SentenceTokenizer", + "SentenceStream", + "WordTokenizer", + "WordStream", + "TokenData", + "BufferedSentenceStream", + "BufferedWordStream", + "basic", + "blingfire", + "utils", +] + diff --git a/main/xiaozhi-server/core/tokenize/_basic_sent.py b/main/xiaozhi-server/core/tokenize/_basic_sent.py new file mode 100644 index 000000000..b3292d3b8 --- /dev/null +++ b/main/xiaozhi-server/core/tokenize/_basic_sent.py @@ -0,0 +1,79 @@ +import re + + +# Rule based segmentation based on https://stackoverflow.com/a/31505798, works surprisingly well +def split_sentences( + text: str, min_sentence_len: int = 20, retain_format: bool = False +) -> list[tuple[str, int, int]]: + """ + The text may not contain substrings "" or "" + """ + alphabets = r"([A-Za-z])" + prefixes = r"(Mr|St|Mrs|Ms|Dr)[.]" + suffixes = r"(Inc|Ltd|Jr|Sr|Co)" + starters = r"(Mr|Mrs|Ms|Dr|Prof|Capt|Cpt|Lt|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)" # noqa: E501 + acronyms = r"([A-Z][.][A-Z][.](?:[A-Z][.])?)" + websites = r"[.](com|net|org|io|gov|edu|me)" + digits = r"([0-9])" + multiple_dots = r"\.{2,}" + + # fmt: off + if retain_format: + text = text.replace("\n","") + else: + text = text.replace("\n"," ") + + text = re.sub(prefixes,"\\1", text) + text = re.sub(websites,"\\1", text) + text = re.sub(digits + "[.]" + digits,"\\1\\2",text) + # text = re.sub(multiple_dots, lambda match: "" * len(match.group(0)) + "", text) + # TODO: need improvement for ""..." dots", check capital + next sentence should not be small # noqa: E501 + text = re.sub(multiple_dots, lambda match: "" * len(match.group(0)), text) + if "Ph.D" in text: + text = text.replace("Ph.D.","PhD") + text = re.sub(r"\s" + alphabets + "[.] "," \\1 ",text) + text = re.sub(acronyms+" "+starters,"\\1 \\2",text) + text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1\\2\\3",text) # noqa: E501 + text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1\\2",text) + text = re.sub(r" "+suffixes+"[.] "+starters," \\1 \\2",text) + text = re.sub(r" "+suffixes+"[.]"," \\1",text) + text = re.sub(r" " + alphabets + "[.]"," \\1",text) + + # Mark end of sentence punctuations with + text = re.sub(r"([.!?。!?])([\"'])", "\\1\\2", text) + text = re.sub(r"([.!?。!?])(?![\"'])", "\\1", text) + + text = text.replace("",".") + # fmt: on + + if retain_format: + text = text.replace("", "\n") + splitted_sentences = text.split("") + text = text.replace("", "") + + sentences: list[tuple[str, int, int]] = [] + + buff = "" + start_pos = 0 + end_pos = 0 + pre_pad = "" if retain_format else " " + for match in splitted_sentences: + if retain_format: + sentence = match + else: + sentence = match.strip() + if not sentence: + continue + + buff += pre_pad + sentence + end_pos += len(match) + if len(buff) > min_sentence_len: + sentences.append((buff[len(pre_pad) :], start_pos, end_pos)) + start_pos = end_pos + buff = "" + + if buff: + sentences.append((buff[len(pre_pad) :], start_pos, len(text) - 1)) + + return sentences + 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..db069a516 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,41 @@ 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 + + # 加载 role 配置 + role_id = self.config.get("role_id", "default") + loader = get_role_config_loader() + + try: + role_config = loader.load(role_id) + # 使用 role 配置中的 profile、timezone、language + profile = role_config.profile + timezone = role_config.timezone + language = role_config.language + self.logger.bind(tag=TAG).info(f"使用 role 配置: {role_id}") + except Exception as e: + # 如果加载失败,回退到使用传入的 user_prompt 和配置文件 + self.logger.bind(tag=TAG).warning(f"加载 role 配置失败: {e},使用默认配置") + profile = user_prompt + 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 +204,32 @@ 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 except Exception as e: - self.logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}") + self.logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}", exc_info=True) return user_prompt diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index c0c88fc57..79f21a02d 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -80,6 +80,15 @@ class WebSocketServer: "authorization" ][0] + if "sample_rate" in query_params: + websocket.request.headers["audio-sample-rate"] = query_params["sample_rate"][0] + if "channels" in query_params: + websocket.request.headers["audio-channels"] = query_params["channels"][0] + if "codec" in query_params: + websocket.request.headers["audio-codec"] = query_params["codec"][0] + if "frame_duration" in query_params: + websocket.request.headers["audio-frame-duration"] = query_params["frame_duration"][0] + """处理新连接,每次创建独立的ConnectionHandler""" # 先认证,后建立连接 try: From 1a46e6a67c5f6fdecd156bef7432268f22e838f1 Mon Sep 17 00:00:00 2001 From: pany-05 Date: Mon, 3 Nov 2025 14:57:34 +0800 Subject: [PATCH 2/3] cherrypick fix --- main/xiaozhi-server/core/connection.py | 89 +------ .../core/providers/llm/openai/openai.py | 247 ++++-------------- main/xiaozhi-server/core/websocket_server.py | 9 - 3 files changed, 53 insertions(+), 292 deletions(-) diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 9dc15fcd2..24d62c753 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -776,89 +776,18 @@ class ConnectionHandler: ) if self.intent_type == "function_call" and functions is not None: - # 使用支持functions的streaming接口 - # response_with_functions 是异步生成器,使用队列在线程间传递 - response_queue = queue.Queue() - stop_flag = threading.Event() - - async def consume_async_generator(): - try: - async_gen = self.llm.response_with_functions( - self.session_id, - dialogue_history, - functions=functions, - ) - async for item in async_gen: - if stop_flag.is_set(): - break - response_queue.put(item) - response_queue.put(None) # 结束标记 - except Exception as e: - self.logger.bind(tag=TAG).error(f"异步生成器消费出错: {e}", exc_info=True) - response_queue.put(None) - response_queue.put(("ERROR", str(e))) - - asyncio.run_coroutine_threadsafe( - consume_async_generator(), self.loop + # 直接使用同步生成器(response_with_functions 是同步方法) + llm_responses = self.llm.response_with_functions( + self.session_id, + dialogue_history, + functions=functions, ) - - # 从队列中获取响应 - def get_responses(): - while True: - try: - item = response_queue.get(timeout=300) # 5分钟超时 - if item is None: - break - if isinstance(item, tuple) and item[0] == "ERROR": - raise Exception(item[1]) - yield item - except queue.Empty: - self.logger.bind(tag=TAG).warning("等待 LLM 响应超时") - stop_flag.set() - break - - llm_responses = get_responses() else: - # response 也是异步生成器,使用队列在线程间传递 - response_queue = queue.Queue() - stop_flag = threading.Event() - - async def consume_async_generator(): - try: - async_gen = self.llm.response( - self.session_id, - dialogue_history, - ) - async for item in async_gen: - if stop_flag.is_set(): - break - response_queue.put(item) - response_queue.put(None) # 结束标记 - except Exception as e: - self.logger.bind(tag=TAG).error(f"异步生成器消费出错: {e}", exc_info=True) - response_queue.put(None) - response_queue.put(("ERROR", str(e))) - - asyncio.run_coroutine_threadsafe( - consume_async_generator(), self.loop + # 直接使用同步生成器(response 是同步方法) + llm_responses = self.llm.response( + self.session_id, + dialogue_history, ) - - # 从队列中获取响应 - def get_responses(): - while True: - try: - item = response_queue.get(timeout=300) # 5分钟超时 - if item is None: - break - if isinstance(item, tuple) and item[0] == "ERROR": - raise Exception(item[1]) - yield item - except queue.Empty: - self.logger.bind(tag=TAG).warning("等待 LLM 响应超时") - stop_flag.set() - break - - llm_responses = get_responses() except Exception as e: self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}", exc_info=True) return None diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index 18548e4c2..a116a80db 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -49,39 +49,33 @@ class LLMProvider(LLMProviderBase): self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=httpx.Timeout(self.timeout)) def response(self, session_id, dialogue, **kwargs): - """ - 同步流式响应方法 - 注意:保持同步以兼容基类和其他 LLM 提供商 - """ try: - # Create streaming response - # 注意:ChatGLM 等服务可能不支持 responses.create API,改用标准的 chat.completions.create - stream = self.client.chat.completions.create( + responses = self.client.chat.completions.create( model=self.model_name, messages=dialogue, stream=True, max_tokens=kwargs.get("max_tokens", self.max_tokens), temperature=kwargs.get("temperature", self.temperature), top_p=kwargs.get("top_p", self.top_p), - frequency_penalty=kwargs.get("frequency_penalty", self.frequency_penalty), + frequency_penalty=kwargs.get( + "frequency_penalty", self.frequency_penalty + ), ) - + is_active = True - - for chunk in stream: + for chunk in responses: try: - # Handle response choices - if not hasattr(chunk, "choices") or not chunk.choices: - continue - - delta = chunk.choices[0].delta - content = getattr(delta, "content", None) - - if content is None: - continue - - # Handle thinking tags (for reasoning models like o1) - # Filter out content between ... + # 检查是否存在有效的choice且content不为空 + delta = ( + chunk.choices[0].delta + if getattr(chunk, "choices", None) + else None + ) + content = delta.content if hasattr(delta, "content") else "" + except IndexError: + content = "" + if content: + # 处理标签跨多个chunk的情况 if "" in content: is_active = False content = content.split("")[0] @@ -90,192 +84,39 @@ class LLMProvider(LLMProviderBase): content = content.split("")[-1] if is_active: yield content - - except (IndexError, AttributeError) as e: - continue - except Exception as e: - logger.bind(tag=TAG).error(f"处理 chunk 时发生未预期错误: {e}", exc_info=True) - continue except Exception as e: - logger.bind(tag=TAG).error(f"Error in response generation: {e}", exc_info=True) + 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): - """ - 同步流式响应方法(支持函数调用) - 注意:保持同步以兼容基类和其他 LLM 提供商 - """ try: - # Prepare request parameters - request_params = { - "model": self.model_name, - "messages": dialogue, - "stream": True, - } - - # Add tools/functions if provided - if functions: - request_params["tools"] = functions - - # Create streaming response (同步版本,移除 await) - stream = self.client.chat.completions.create(**request_params) + stream = self.client.chat.completions.create( + model=self.model_name, messages=dialogue, stream=True, tools=functions + ) for chunk in stream: - try: - # Handle token usage reporting - if hasattr(chunk, "usage") and isinstance(chunk.usage, CompletionUsage): - usage_info = chunk.usage - logger.bind(tag=TAG).info( - f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," - f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," - f"共计 {getattr(usage_info, 'total_tokens', '未知')}" - ) - continue - - # Handle response choices - if not hasattr(chunk, "choices") or not chunk.choices: - continue - - delta = chunk.choices[0].delta - - # Extract content and tool calls - content = getattr(delta, "content", None) - tool_calls = getattr(delta, "tool_calls", None) - - # Yield the chunk - yield content, tool_calls - - except (IndexError, AttributeError) as e: - continue + # 检查是否存在有效的choice且content不为空 + if getattr(chunk, "choices", None): + yield chunk.choices[0].delta.content, chunk.choices[ + 0 + ].delta.tool_calls + # 存在 CompletionUsage 消息时,生成 Token 消耗 log + elif isinstance(getattr(chunk, "usage", None), CompletionUsage): + usage_info = getattr(chunk, "usage", None) + logger.bind(tag=TAG).info( + f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," + f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," + f"共计 {getattr(usage_info, 'total_tokens', '未知')}" + ) - except openai.APIError as e: - error_msg = f"OpenAI API error: {e.message if hasattr(e, 'message') else str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield f"【API错误: {error_msg}】", None - - except openai.APIConnectionError as e: - error_msg = f"Connection error: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield f"【连接错误: 无法连接到服务】", None - - except openai.RateLimitError as e: - error_msg = f"Rate limit exceeded: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield f"【请求过于频繁,请稍后再试】", None - except Exception as e: - error_msg = f"Unexpected error in function calling: {type(e).__name__}: {str(e)}" - logger.bind(tag=TAG).error(error_msg, exc_info=True) - yield f"【OpenAI服务响应异常: {str(e)}】", None - - async def response_stream( - self, - chat_ctx: ChatContext, - **kwargs: Any - ) -> AsyncGenerator[ChatChunk, None]: - """ - New streaming interface using standard protocol - - This method implements the new standard interface defined in LLMProviderBase. - It uses: - - ChatContext as input (standard dialogue protocol) - - ChatChunk as output (standard streaming protocol) - - OpenAI Responses API (modern response.create) - - Args: - chat_ctx: Standard ChatContext with dialogue history - **kwargs: Additional options: - - max_output_tokens: Override max tokens - - temperature: Override temperature - - top_p: Override top_p - - frequency_penalty: Override frequency penalty - - Yields: - ChatChunk: Standardized streaming chunks with deltas and usage - - Example: - async for chunk in provider.response_stream(chat_ctx): - if chunk.delta and chunk.delta.content: - print(chunk.delta.content) - if chunk.usage: - print(f"Tokens: {chunk.usage.total_tokens}") - """ - try: - # 1. Convert ChatContext to OpenAI format - messages, _ = chat_ctx.to_provider_format(format="openai") - - logger.bind(tag=TAG).debug( - f"Starting streaming with model={self.model_name}, " - f"messages_count={len(messages)}" - ) - - # 2. Prepare request parameters - max_output_tokens = kwargs.get("max_output_tokens", self.max_output_tokens) - temperature = kwargs.get("temperature", self.temperature) - top_p = kwargs.get("top_p", self.top_p) - frequency_penalty = kwargs.get("frequency_penalty", self.frequency_penalty) - - # 3. Call OpenAI Responses API - # TODO: system instruction needs to be added - stream: AsyncStream[ResponseStreamEvent] = await self.client.responses.create( - input=messages, - model=self.model_name, - stream=True, - max_output_tokens=max_output_tokens, - temperature=temperature, - top_p=top_p, - frequency_penalty=frequency_penalty, - ) - - # 4. Parse stream and yield ChatChunk (focus on output_item.done + completed) - async for event in stream: - try: - chunk = self._parse_response_event(event) - if chunk: - yield chunk - except (IndexError, AttributeError) as e: - logger.bind(tag=TAG).debug(f"Skipping malformed event: {e}") - continue - - logger.bind(tag=TAG).debug("Stream completed successfully") - - except openai.APIError as e: - error_msg = f"OpenAI API error: {e.message if hasattr(e, 'message') else str(e)}" - logger.bind(tag=TAG).error(error_msg) - # Yield error chunk - yield ChatChunk( - delta=ChatDelta( - role="assistant", - content=f"【API错误: {error_msg}】" - ) - ) - - except openai.APIConnectionError as e: - error_msg = f"Connection error: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield ChatChunk( - delta=ChatDelta( - role="assistant", - content="【连接错误: 无法连接到服务】" - ) - ) - - except openai.RateLimitError as e: - error_msg = f"Rate limit exceeded: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield ChatChunk( - delta=ChatDelta( - role="assistant", - content="【请求过于频繁,请稍后再试】" - ) - ) - - except Exception as e: - error_msg = f"Unexpected error: {type(e).__name__}: {str(e)}" - logger.bind(tag=TAG).error(error_msg) - yield ChatChunk( - delta=ChatDelta( - role="assistant", - content=f"【服务异常: {str(e)}】" - ) - ) + 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/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 79f21a02d..c0c88fc57 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -80,15 +80,6 @@ class WebSocketServer: "authorization" ][0] - if "sample_rate" in query_params: - websocket.request.headers["audio-sample-rate"] = query_params["sample_rate"][0] - if "channels" in query_params: - websocket.request.headers["audio-channels"] = query_params["channels"][0] - if "codec" in query_params: - websocket.request.headers["audio-codec"] = query_params["codec"][0] - if "frame_duration" in query_params: - websocket.request.headers["audio-frame-duration"] = query_params["frame_duration"][0] - """处理新连接,每次创建独立的ConnectionHandler""" # 先认证,后建立连接 try: From a5bdc517b6f52a721606afbae8a080edaf78edfa Mon Sep 17 00:00:00 2001 From: pany-05 Date: Tue, 4 Nov 2025 10:56:13 +0800 Subject: [PATCH 3/3] update tts elevenlabs&&cartesia sdk --- main/xiaozhi-server/config.yaml | 43 +++ .../core/providers/llm/openai/openai.py | 8 +- .../core/providers/tts/cartesia_sdk.py | 271 ++++++++++++++++++ .../core/providers/tts/elevenlabs_sdk.py | 199 +++++++++++++ main/xiaozhi-server/requirements.txt | 4 + 5 files changed, 521 insertions(+), 4 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/tts/cartesia_sdk.py create mode 100644 main/xiaozhi-server/core/providers/tts/elevenlabs_sdk.py diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 90e9edb38..2070c3ee0 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -647,6 +647,49 @@ TTS: type: edge voice: zh-CN-XiaoxiaoNeural output_dir: tmp/ + # ============== SDK 版本TTS(推荐)============== + # 使用官方SDK,代码更简洁、性能更好、维护成本更低 + CartesiaSDK: + # Cartesia TTS - SDK版本(推荐) + # 官方SDK实现,低延迟,支持流式合成 + # API Key获取地址:https://play.cartesia.ai/console + # 或设置环境变量:export CARTESIA_API_KEY=your-api-key + type: cartesia_sdk + 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/ + ElevenLabsSDK: + # ElevenLabs TTS - SDK版本(推荐) + # 官方SDK实现,代码更简洁,维护成本更低,性能更好 + # API Key获取地址:https://elevenlabs.io/app/settings/api-keys + # 或设置环境变量:export ELEVEN_API_KEY=your-api-key + type: elevenlabs_sdk + 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/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index a116a80db..f2f87c511 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -101,13 +101,13 @@ 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', '未知')}" diff --git a/main/xiaozhi-server/core/providers/tts/cartesia_sdk.py b/main/xiaozhi-server/core/providers/tts/cartesia_sdk.py new file mode 100644 index 000000000..8017c5876 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/cartesia_sdk.py @@ -0,0 +1,271 @@ +""" +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 + +try: + import cartesia +except ImportError: + raise ImportError( + "Cartesia SDK not installed. Install with: pip install 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-english + 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 + + # 获取 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-english") + self.language = config.get("language", "en") + + # 音频配置 + self.encoding = config.get("encoding", "pcm_s16le") + self.sample_rate = config.get("sample_rate", 24000) + + # 验证至少有一个 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}" + ) + + async 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]: + """ + 非流式方法:将完整文本转换为音频 + + 注意:Cartesia 主要设计为流式使用,此方法会等待完整音频生成 + 建议使用 to_tts_stream() 方法以获得更低的延迟 + """ + try: + ws = await self._get_ws_client() + + audio_chunks = [] + voice = self._prepare_voice_param() + + # 发送流式请求 + for output in ws.send( + model_id=self.model, + transcript=text, + voice=voice, + stream=True, + output_format={ + "container": "raw", + "encoding": self.encoding, + "sample_rate": self.sample_rate + } + ): + # Cartesia SDK 返回 WebSocketTtsOutput 对象 + # 从 output.audio 获取音频数据 + if output and hasattr(output, 'audio') and output.audio: + audio_chunks.append(output.audio) + + # 合并所有音频块 + audio_data = b''.join(audio_chunks) + + # 保存到文件或返回 + if output_file: + with open(output_file, 'wb') as f: + f.write(audio_data) + logger.bind(tag=TAG).info(f"Audio saved to {output_file}, size: {len(audio_data)} bytes") + return None + else: + return audio_data + + except Exception as e: + logger.bind(tag=TAG).error(f"Cartesia TTS failed: {e}", exc_info=True) + raise + + def to_tts_stream(self, text: str, opus_handler: Optional[Callable] = None): + """ + 流式生成音频(核心方法) + + 注意:浏览器端使用 Web Audio API 播放,直接发送 PCM 数据 + ESP32 等嵌入式设备使用 Opus,需要编码 + + Args: + text: 要合成的文本 + opus_handler: 音频数据回调函数 (接收 bytes) + """ + try: + from core.providers.tts.dto.dto import SentenceType + + start_time = time.time() + text_preview = text[:30] + "..." if len(text) > 30 else text + logger.bind(tag=TAG).info(f"🎙️ TTS开始: [{text_preview}]") + + # 发送句子开始标记 + self.tts_audio_queue.put((SentenceType.FIRST, None, text)) + + # 在异步事件循环中运行 + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + try: + # 运行异步合成 + chunk_count = loop.run_until_complete( + self._stream_synthesis(text, opus_handler, start_time) + ) + finally: + loop.close() + + # 发送句子结束标记 + self.tts_audio_queue.put((SentenceType.LAST, None, text)) + + end_time = time.time() + total_time = (end_time - start_time) * 1000 + logger.bind(tag=TAG).info( + f"✅ TTS完成: {chunk_count}块, 耗时 {total_time:.0f}ms" + ) + + except Exception as e: + logger.bind(tag=TAG).error(f"TTS 合成失败: {e}", exc_info=True) + raise + + async def _stream_synthesis(self, text: str, opus_handler: Optional[Callable], start_time: float) -> int: + """ + 异步流式合成实现 + + Args: + text: 要合成的文本 + opus_handler: 音频数据回调函数 + start_time: 开始时间(用于计算首包延迟) + + Returns: + 生成的音频块数量 + """ + try: + ws = await self._get_ws_client() + voice = self._prepare_voice_param() + + first_chunk_time = None + chunk_count = 0 + + # 发送流式请求并处理响应 + for output in ws.send( + model_id=self.model, + transcript=text, + voice=voice, + stream=True, + output_format={ + "container": "raw", + "encoding": self.encoding, + "sample_rate": self.sample_rate + }, + language=self.language + ): + # Cartesia SDK 返回 WebSocketTtsOutput 对象 + # 需要从 output.audio 获取实际的音频数据 + if output and hasattr(output, 'audio'): + audio_data = output.audio + + if audio_data: + if first_chunk_time is None: + first_chunk_time = time.time() + ttfb = (first_chunk_time - start_time) * 1000 + logger.bind(tag=TAG).info(f"⚡ 首包延迟: {ttfb:.0f}ms") + + # 发送音频数据(bytes) + if opus_handler: + opus_handler(audio_data) + chunk_count += 1 + + return chunk_count + + except Exception as e: + logger.bind(tag=TAG).error(f"Stream synthesis error: {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/elevenlabs_sdk.py b/main/xiaozhi-server/core/providers/tts/elevenlabs_sdk.py new file mode 100644 index 000000000..c4935f3af --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/elevenlabs_sdk.py @@ -0,0 +1,199 @@ +""" +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 +from core.utils import opus_encoder_utils + +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 + + # 获取 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 + ) + + # 初始化 Opus 编码器(ElevenLabs pcm_16000 是 16kHz PCM) + self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( + sample_rate=16000, channels=1, frame_size_ms=60 + ) + + # PCM 缓冲区(用于累积不完整的帧) + self.pcm_buffer = bytearray() + + logger.bind(tag=TAG).info( + f"ElevenLabs SDK initialized: model={self.model}, " + f"voice_id={self.voice_id[:8]}..., " + f"format={self.output_format}" + ) + + async def text_to_speak(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]: + """ + 非流式方法:将完整文本转换为音频 + + 注意:此方法会等待完整音频生成 + 建议使用 to_tts_stream() 方法以获得更低的延迟 + """ + try: + # 使用 SDK 的 convert 方法生成完整音频 + audio_data = 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: + f.write(audio_data) + logger.bind(tag=TAG).info(f"Audio saved to {output_file}, size: {len(audio_data)} bytes") + return None + else: + return audio_data + + except Exception as e: + logger.bind(tag=TAG).error(f"ElevenLabs TTS failed: {e}", exc_info=True) + raise + + def to_tts_stream(self, text: str, opus_handler: Optional[Callable] = None): + """ + 流式生成音频(核心方法) + + 注意:浏览器端使用 Web Audio API 播放,直接发送 PCM 数据 + ESP32 等嵌入式设备使用 Opus,需要编码 + + Args: + text: 要合成的文本 + opus_handler: 音频数据回调函数 (接收 bytes) + """ + import time + try: + from core.providers.tts.dto.dto import SentenceType + + start_time = time.time() + text_preview = text[:30] + "..." if len(text) > 30 else text + logger.bind(tag=TAG).info(f"🎙️ TTS开始: [{text_preview}]") + + # 发送句子开始标记 + self.tts_audio_queue.put((SentenceType.FIRST, None, text)) + + # 使用 SDK 的 stream 方法(返回 Iterator[bytes] PCM 数据) + audio_stream = self.client.text_to_speech.stream( + voice_id=self.voice_id, + text=text, + model_id=self.model, + output_format=self.output_format, + voice_settings=self.voice_settings, + optimize_streaming_latency=self.optimize_streaming_latency + ) + + first_chunk_time = None + chunk_count = 0 + + # 直接发送 PCM 数据(浏览器端可以直接播放) + for pcm_chunk in audio_stream: + if pcm_chunk and opus_handler: + if first_chunk_time is None: + first_chunk_time = time.time() + ttfb = (first_chunk_time - start_time) * 1000 + logger.bind(tag=TAG).info(f"⚡ 首包延迟: {ttfb:.0f}ms") + chunk_count += 1 + opus_handler(pcm_chunk) + + # 发送句子结束标记 + self.tts_audio_queue.put((SentenceType.LAST, None, text)) + + end_time = time.time() + total_time = (end_time - start_time) * 1000 + logger.bind(tag=TAG).info( + f"✅ TTS完成: {chunk_count}块, 耗时 {total_time:.0f}ms" + ) + + except Exception as e: + logger.bind(tag=TAG).error(f"TTS 合成失败: {e}", exc_info=True) + raise + + async def close(self): + """清理资源(ElevenLabs SDK 自动管理连接)""" + pass + diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt index bc9d6956c..7bd45b888 100644 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -36,3 +36,7 @@ psutil==7.0.0 portalocker==3.2.0 Jinja2==3.1.6 vosk==0.3.44 + +# TTS SDKs +elevenlabs>=1.11.0 +cartesia>=1.0.0