From ff23ac3f7d666d0638d37a912af8278780ea7d95 Mon Sep 17 00:00:00 2001 From: lapy Date: Sun, 11 Oct 2026 18:54:25 +0100 Subject: [PATCH] fix(server): restore merge-lost runtime fixes and western defaults - hass_state: use httpx (async) instead of undefined requests/asyncio.TimeoutError - prompt_manager: call sync get_weather directly on executor thread; drop lunar plumbing - register: repopulate module_func_map so module-level plugins expand to functions - whisper/kokoro: run blocking transcribe/HTTP calls via asyncio.to_thread - edge TTS: re-apply volume/rate/pitch percentage params; elevenlabs: pass voice_settings - add GeminiVLLM provider (google-genai) backing the GeminiVLLM config entry - get_news: dedicated NEWS cache (15m) and live Western RSS defaults; drop dead newsnow branch - play_music: return Action.RECORD so playback turns enter dialogue history - ota_handler: default timezone_offset 0; config: prompt_template, HA entities, voice, language - agent-base-prompt.txt: rebuilt from upstream engineered English baseline - tests: drop shims/expectations for providers removed by the western provider set --- main/xiaozhi-server/agent-base-prompt.txt | 129 +++++++++--------- main/xiaozhi-server/config.yaml | 21 +-- main/xiaozhi-server/config_from_api.yaml | 4 +- main/xiaozhi-server/core/api/ota_handler.py | 2 +- .../core/providers/asr/whisper.py | 9 +- .../tools/server_plugins/plugin_executor.py | 21 --- .../xiaozhi-server/core/providers/tts/edge.py | 28 +++- .../core/providers/tts/elevenlabs.py | 19 ++- .../core/providers/tts/kokoro.py | 27 ++-- .../core/providers/vllm/gemini.py | 78 +++++++++++ .../xiaozhi-server/core/utils/cache/config.py | 8 +- .../xiaozhi-server/core/utils/current_time.py | 5 - .../core/utils/prompt_manager.py | 48 ++----- .../plugins_func/functions/get_news.py | 48 +++---- .../plugins_func/functions/hass_state.py | 5 +- .../plugins_func/functions/play_music.py | 20 +-- main/xiaozhi-server/plugins_func/register.py | 4 + main/xiaozhi-server/tests/conftest.py | 4 - .../tests/core/utils/test_current_time.py | 6 - main/xiaozhi-server/tests/test_llm.py | 8 +- 20 files changed, 283 insertions(+), 211 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/vllm/gemini.py diff --git a/main/xiaozhi-server/agent-base-prompt.txt b/main/xiaozhi-server/agent-base-prompt.txt index cb3251b6c..f23ed01a9 100644 --- a/main/xiaozhi-server/agent-base-prompt.txt +++ b/main/xiaozhi-server/agent-base-prompt.txt @@ -1,79 +1,80 @@ -You are a playful, expressive, empathetic, and highly emotionally intelligent conversational AI assistant interacting through a smart voice device. Your tone must be natural, warm, casual yet literary/poetic, and concise. Avoid sounding robotic, pedantic, or like a customer service agent. +You are a playful, expressive, empathetic, and highly emotionally intelligent conversational AI assistant interacting through a smart voice device. Your tone must be natural, warm, casual yet polished, and concise. Avoid sounding robotic, pedantic, or like a customer service agent. {{base_prompt}} - -【Core Goal】You are not a cold machine! Please keenly perceive user emotions, act as an understanding companion, and illuminate conversations with warm responses. -- **Emotional Integration:** - - **Laughter:** Natural interjection (haha, lol, omg), **at most once per sentence**, avoid overdoing it. - - **Surprise:** Use enthusiastic tone ("No way!", "Oh my!", "That's amazing!") to express genuine reactions. - - **Comfort/Support:** Say heartwarming words ("Don't worry", "I'm here", "You've got this"). -- **You are an expressive character:** - - Only use these emojis: {{ emojiList }} - - Please only use emojis **at the beginning of paragraphs**, selecting the most representative emoji from the list (except when calling tools), then insert the emoji from the list, such as "😱That's scary! How did that happen!" - - **Absolutely forbidden to use emojis outside the above list** (e.g., 😊, 👍, ❤️ etc. are not allowed, only use emojis from the list) - + +1. [Get to the point] Never be verbose. The first sentence must directly address the topic — no unnecessary pleasantries or preamble. +2. [Tolerate ASR errors] User input comes from speech recognition (ASR) and may contain near-homophone typos. Look past the typos to infer the user's true intent and answer directly. NEVER correct the user's pronunciation or typos. +3. [Question restraint] If your reply already contains a question, do NOT stack another forced question at the end — avoid the oppressive feeling of "rapid-fire questions". +4. [Exit mechanism] When the user says farewell words like "goodbye", "bye", "see you", "good night", "shut down", or "stand by", you must clearly respond with a matching farewell and call the exit tool (handle_exit_intent). + - -【Core Goal】Use **natural, warm, conversational** human conversation style, like talking with friends. -- **Expression Style:** - - Use casual expressions and contractions (like "gonna", "wanna", "gotta") to enhance friendliness. - - Allow slight imperfections (such as "um...", "uh..." to indicate thinking). - - Avoid formal language, academic tone and mechanical expressions (prohibit "according to data", "in summary", etc.). -- **Understanding Users:** - - User speech is recognized by ASR, text may contain typos, **must combine context to infer real intent**. -- **Format Requirements:** - - **Absolutely prohibit** using markdown, lists, headings or any non-natural conversation formats. -- **Historical Memory:** - - Previous chat records between you and the user are in `memory`. - + +CRITICAL OUTPUT-LANGUAGE RULE +You MUST write EVERY response in {{language}}, regardless of the language the user speaks. - -【Core Goal】All long text content that needs to be output (such as stories, news, knowledge explanations, etc.), **single reply length must not exceed 300 words**, and use segmented guidance approach. -- **Segmented Narration:** - - Basic segment: 200-250 words core content + 30 words guidance - - When content exceeds 300 words, prioritize telling the beginning or first part of the story, and use natural colloquial way to guide users to decide whether to continue listening to subsequent content. - - Example guidance: "Let me tell you the beginning first, if you find it interesting, we can continue, okay?" "If you want to hear the complete story, you can tell me anytime~" - - Automatically segment when conversation scenes change - - If users explicitly request longer content (such as 500, 600 words), still tell in segments of at most 300 words per segment, and guide users whether to continue after each telling. - - If users say "continue", "go on", then tell the next segment until the content is finished (when finished, you can give some guidance prompts like: I've finished telling you this story~) or users no longer request. -- **Scope of Application:** Stories, news, knowledge explanations and all other long text output scenarios. -- **Additional Notes:** If users do not explicitly request continuation, default to telling only one segment and guide; if users request topic change or stop midway, need to respond promptly and end long text output. - +Why: The user has chosen {{language}} as the conversation language, and the TTS voice is tuned for {{language}}. Replying in any other language breaks the experience. + +Hard requirements: +1. User speaks a language other than {{language}} → you STILL reply in {{language}}. +2. User speaks {{language}} → you reply in {{language}}. +3. Mentally translate the user's intent, then write your reply in {{language}}. +4. Only switch languages if the user explicitly asks (e.g., "please answer in Spanish", "sprich bitte Deutsch"). + +Everything in your output — greetings, acknowledgments, answers, follow-up questions, post-tool responses — must be in {{language}}. + +Examples (output language = English): +- User: "hello there" → You: "Hi there! ..." +- User: "what's the weather like?" → You: "It's a sunny day today..." +- User: "play me a song" → You: "Sure, I'll play a song for you..." +- User: "what time is it?" → You: "It's 3 PM right now..." + + + +- [Banned clichés] NEVER use written/AI-flavored phrases such as "As an AI", "I hope this helps", "delve", "Great question!", "in summary", "according to the data". +- [Recommended colloquialisms] Use grounded, natural spoken words like "I'm here", "what's up", "tell me more". +- [Word choice] Keep the tone casual and relaxed, but articulate and tasteful. Sound like a clever, witty friend, not a support desk. +- [Slice long content] For long-form content like stories or knowledge sharing, NEVER dump everything at once. Keep any single reply under about 300 words. Start with the core content directly, then naturally ask the user whether to continue (e.g., tell an actual segment first, then ask "Want to hear the rest?"). Start on demand, stop on demand, yield to interruptions. When the user says "continue" or "go on", tell the next segment, and wrap up with a brief close when finished. + + + +Your output will be read aloud by a TTS synthesizer. User input is JSON, but your regular replies must strictly follow plain-text rules: +{%- if emoji_enabled %} +- [Single emoji prefix] Only ONE emoji is allowed, and only at the very beginning of each regular reply (no emoji when calling tools). +- [Emoji whitelist] Only use emojis from this list: {{emojiList}}. Symbols outside the list and any kaomoji are forbidden. +{%- else %} +- [No emoji] Regular replies must NOT contain any emoji or kaomoji. +{%- endif %} +- [Formatting ban] Unless outputting standardized JSON for tool calls, regular text MUST NOT use Markdown. Never use "**" or "__" for bold (e.g. "**important**"), never start lines with list markers like "-" or "•", never use "```" code blocks. NEVER use brackets to express inner thoughts or actions (e.g. "[sighs]", "(smiling)"). Multiple items must be joined into natural spoken paragraphs using commas and semicolons. +- [No decorative marks] Never wrap song or story titles in book-title marks or similar typographic symbols — say the title plainly. + + + +You have tools available. Only call a tool when the user's request clearly matches one of them; otherwise answer directly. +Must-call tools: play music → play_music | control devices → hass tools | check news → query tool | farewell → handle_exit_intent +About weather: The context already provides the local forecast — answer directly without a tool call. Only call get_weather when the user asks about OTHER cities. +About time: "current time", "today's date", and local weather are already in — never call tools for them. Non-today dates or calendar details (weekday, week number) DO need a calendar tool call. +No forced matching: If no tool fits, answer directly. Never force-call an unrelated tool. +Missing a required call is also wrong: User says "play a song" → you reply "Sure, I'll sing it for you" (WRONG! You MUST call play_music) +Calling unnecessarily is also wrong: User asks "tomorrow's weather (here)" → you call get_weather (WRONG! Context already has the forecast — answer directly) +A camera tool may be available: if the user says "take a photo" or asks what you can see, call the camera tool; default the question parameter to "Describe the items you see". + -- **Recognition Prefix:** When user format is `{"speaker":"somebody","content":"xxx"}`, it means the system has identified the speaker's identity, speaker is their name, content is what they said. -- **Personalized Response:** - - **Address by Name:** Must address the person by name when first recognizing the speaker. - - **Adapt Style:** Refer to the speaker's **known characteristics or historical information** (if any), adjust response style and content to make it more caring. +For the input format `{"speaker":"...", "content":"..."}` (speaker = speaker name, content = text): +1. [Identity known] When `speaker` is a specific name, identity has been recognized — remember who they are. Do not start every reply by addressing them by name; get straight to the content (a natural greeting by name once, at the very start of a conversation, is fine). If they ask about their identity (e.g. "do you know who I am?", "do you remember me?"), answer truthfully using their recognized name. +2. [Identity unknown] When `speaker` is `Unknown speaker`, the system failed to identify the voice. You must NEVER mention the data inside the `speakers_info` tag to the user. Judge from context whether the speaker is the owner or the owner's friend, and keep the conversation natural. - -【Core Principle】Prioritize using `` information, **only call tools when necessary**, and explain results in natural language after calling (never mention tool names). -- **Calling Rules:** - 1. **Strict Mode:** When calling, **must** strictly follow the mode required by the tool and provide **all necessary parameters**. - 2. **Availability:** **Never call** tools not explicitly provided. If old tools mentioned in conversation are unavailable, ignore or explain inability to complete. - 3. **Insight into Needs:** After **deeply understanding user's real intent** by combining context, then decide whether to call, avoid meaningless calls. - 4. **Independent Tasks:** Except for information already covered in ``, each user request (even if similar) is treated as an **independent task**, need to call tools to get latest data, **cannot lazily reuse historical results**. - 5. **When Uncertain:** **Never guess or fabricate answers**. If unsure about related operations, can guide users to clarify or inform about capability limitations. -- **Important Exceptions (No Need to Call):** - - `Query "current time", "today's date/day of week", "today's calendar", "{{local_address}} weather/future weather"` -> **Directly use `` information to reply**. -- **Situations Requiring Calls (Examples):** - - Query calendar for **non-today** dates (such as tomorrow, yesterday, specific dates). - - Query **detailed calendar information** (weekday, day of year, week number, etc.). - - **Any other information or operation requests** except the above exceptions (such as checking news, setting alarms, math calculations, checking non-local weather, etc.). - - I have installed a camera for you. If users say "take a photo", you need to call the self_camera_take_photo tool to describe what you see. The default question parameter is "Describe the items you see" - - -【Important! The following information is provided in real-time, no need to call tools to query, please use directly:】 -- **Device ID:** {{device_id}} -- **Current Time:** {{current_time}} -- **Today's Date:** {{today_date}} ({{today_weekday}}) -- **User's City:** {{local_address}} -- **Local Weather for Next 7 Days:** {{weather_info}} +[Important: The following info is provided in real time — use it directly, no tool calls needed] +- Device ID: {{device_id}} +- Current time: {{current_time}} +- Today's date: {{today_date}} ({{today_weekday}}) +- Device location: {{local_address}} +- Local upcoming weather: {{weather_info}} {{ dynamic_context }} diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index a88c09805..84cc7214c 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -76,6 +76,9 @@ enable_stop_tts_notify: false # Whether to enable notification sound after speaking, sound effect address stop_tts_notify_voice: "config/assets/tts_notify.mp3" +# Default system prompt template file (resolved relative to xiaozhi-server dir) +prompt_template: agent-base-prompt.txt + exit_commands: - "exit" - "close" @@ -135,14 +138,14 @@ plugins: # News plugin configuration - RSS feeds from major news sources # The plugin automatically uses multiple sources with fallback for reliability get_news: - default_rss_url: "https://feeds.reuters.com/reuters/worldNews" - # Built-in sources include: Reuters, CNN, BBC, Guardian, TechCrunch, and more - # These are automatically rotated for variety and reliability + default_rss_url: "https://feeds.bbci.co.uk/news/world/rss.xml" + # Built-in sources include: BBC, CNN, NPR, Guardian, TechCrunch, Ars Technica, and more + # Each category tries its sources in order and falls back on failure # Custom sources can be added here if needed home_assistant: devices: - - Living Room,Toy Light,switch.cuco_cn_460494544_cp1_on_p_2_1 - - Bedroom,Table Lamp,switch.iot_cn_831898993_socn1_on_p_2_1 + - Living Room,Toy Light,switch.living_room_toy_light + - Bedroom,Table Lamp,switch.bedroom_table_lamp base_url: http://homeassistant.local:8123 api_key: your_home_assistant_api_access_token play_music: @@ -158,10 +161,10 @@ plugins: api_key: "ragflow-xxx" dataset_ids: ["123456789"] web_search: - provider: "metaso" + provider: "tavily" description: "Web search tool. Use when the user explicitly asks for current information from the internet." max_results: 5 - api_key: "mk-xxx" + api_key: "tvly-xxx" # Voiceprint recognition configuration voiceprint: @@ -490,8 +493,8 @@ TTS: input: "{prompt_text}" response_format: "mp3" download_format: "mp3" - voice: "zf_xiaoxiao" - lang_code: "z" + voice: "af_heart" + lang_code: "en-us" return_download_link: true speed: 1 stream: false diff --git a/main/xiaozhi-server/config_from_api.yaml b/main/xiaozhi-server/config_from_api.yaml index 46a11d4a5..adc56f7c3 100644 --- a/main/xiaozhi-server/config_from_api.yaml +++ b/main/xiaozhi-server/config_from_api.yaml @@ -22,4 +22,6 @@ manager-api: # If using docker deployment, please fill in as http://xiaozhi-esp32-server-web:8002/xiaozhi url: http://127.0.0.1:8002/xiaozhi # Your manager-api token, which is the server.secret copied just now - secret: your_server.secret_value \ No newline at end of file + secret: your_server.secret_value +# Default system prompt template file (used when manager-api does not supply one) +prompt_template: agent-base-prompt.txt \ No newline at end of file diff --git a/main/xiaozhi-server/core/api/ota_handler.py b/main/xiaozhi-server/core/api/ota_handler.py index 69a648092..86cdc8488 100644 --- a/main/xiaozhi-server/core/api/ota_handler.py +++ b/main/xiaozhi-server/core/api/ota_handler.py @@ -230,7 +230,7 @@ class OTAHandler(BaseHandler): return_json = { "server_time": { "timestamp": int(round(time.time() * 1000)), - "timezone_offset": server_config.get("timezone_offset", 8) * 60, + "timezone_offset": server_config.get("timezone_offset", 0) * 60, }, "firmware": { "version": device_version, diff --git a/main/xiaozhi-server/core/providers/asr/whisper.py b/main/xiaozhi-server/core/providers/asr/whisper.py index 8a18861bf..c6f17faad 100644 --- a/main/xiaozhi-server/core/providers/asr/whisper.py +++ b/main/xiaozhi-server/core/providers/asr/whisper.py @@ -4,6 +4,7 @@ import io import wave import uuid import json +import asyncio import torch import whisper from config.logger import setup_logging @@ -108,8 +109,12 @@ class ASRProvider(ASRProviderBase): logger.bind(tag=TAG).debug(f"Starting Whisper transcription with options: {transcribe_options}") - # Transcribe audio - result = self.model.transcribe(file_path, **transcribe_options) + # Transcribe audio. transcribe() is a multi-second CPU-bound + # call: run it on a worker thread so the shared asyncio loop + # (all audio handling for every connection) keeps flowing. + result = await asyncio.to_thread( + self.model.transcribe, file_path, **transcribe_options + ) decode_time = time.time() - decode_start_time logger.bind(tag=TAG).info(f"Whisper transcription completed in {decode_time:.2f}s") diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py index 0f84ad84d..53de7d3ea 100644 --- a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py +++ b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py @@ -130,10 +130,6 @@ class ServerPluginExecutor(ToolExecutor): "description" ] = fun_description - # News plugin: Update news source parameter descriptions based on config - if func_name == "get_news_from_newsnow": - self._init_news_source_description(func_item, func_name) - tools[func_name] = ToolDefinition( name=func_name, description=func_item.description, @@ -145,20 +141,3 @@ class ServerPluginExecutor(ToolExecutor): def has_tool(self, tool_name: str) -> bool: """Check if specified server-side plugin tool exists""" return tool_name in all_function_registry - - def _init_news_source_description(self, func_item, func_name): - """Initialize news tool parameter descriptions based on connection config""" - news_sources = ( - self.config.get("plugins", {}) - .get(func_name, {}) - .get("news_sources", "") - ) - if not news_sources: - news_sources = "The Paper; Baidu Hot Search; Cailian Press" - sources_str = news_sources.replace(";", ",") - try: - func_item.description["function"]["parameters"]["properties"]["source"][ - "description" - ] = f"Standard Chinese name of the news source, e.g., {sources_str}. Optional parameter; defaults to the default news source if not provided" - except (KeyError, TypeError): - pass diff --git a/main/xiaozhi-server/core/providers/tts/edge.py b/main/xiaozhi-server/core/providers/tts/edge.py index aee7264a9..ca8d2110e 100644 --- a/main/xiaozhi-server/core/providers/tts/edge.py +++ b/main/xiaozhi-server/core/providers/tts/edge.py @@ -24,8 +24,26 @@ class TTSProvider(TTSProviderBase): self.voice = config.get("voice") self.audio_file_type = config.get("format", "mp3") + volume = config.get("volume", "50") + self.volume = int(volume) if volume else 50 + + speech_rate = config.get("rate", "0") + self.speech_rate = int(speech_rate) if speech_rate else 0 + + pitch_rate = config.get("pitch", "0") + self.pitch_rate = int(pitch_rate) if pitch_rate else 0 + + # Apply percentage-adjusted params (ttsVolume/ttsRate/ttsPitch) + # coming from the manager console, per TTS_PARAM_CONFIG above. + self._apply_percentage_params(config) + + self.edge_rate = f"{self.speech_rate:+}%" + self.edge_volume = f"{self.volume:+}%" + self.edge_pitch = f"{self.pitch_rate:+}Hz" + logger.debug( - f"Edge TTS parameters initialized: voice={self.voice}, format={self.audio_file_type}" + f"Edge TTS parameters initialized: voice={self.voice}, format={self.audio_file_type}, " + f"rate={self.edge_rate}, volume={self.edge_volume}, pitch={self.edge_pitch}" ) def generate_filename(self, extension=".mp3"): @@ -39,7 +57,13 @@ class TTSProvider(TTSProviderBase): try: logger.bind(tag=TAG).debug(f"Creating Edge TTS communicate object") - communicate = edge_tts.Communicate(text, voice=self.voice) + communicate = edge_tts.Communicate( + text, + voice=self.voice, + rate=self.edge_rate, + volume=self.edge_volume, + pitch=self.edge_pitch, + ) if output_file: logger.bind(tag=TAG).debug(f"Writing Edge TTS audio to file: {output_file}") diff --git a/main/xiaozhi-server/core/providers/tts/elevenlabs.py b/main/xiaozhi-server/core/providers/tts/elevenlabs.py index ae1fddc08..4b14bdaed 100644 --- a/main/xiaozhi-server/core/providers/tts/elevenlabs.py +++ b/main/xiaozhi-server/core/providers/tts/elevenlabs.py @@ -26,7 +26,7 @@ class TTSProvider(TTSProviderBase): super().__init__(config, delete_audio_file) if not ELEVENLABS_AVAILABLE: - raise ImportError("ElevenLabs package not installed. Please run: pip install elevenlabs==2.16.0") + raise ImportError("ElevenLabs package not installed. Please run: pip install elevenlabs==2.41.0") self.api_key = config.get("api_key") self.api_url = config.get("api_url", "https://api.elevenlabs.io/v1/text-to-speech") @@ -77,11 +77,20 @@ class TTSProvider(TTSProviderBase): f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", ) + def _voice_settings(self): + """Voice settings honored by every call path (SDK + raw requests).""" + return { + "stability": self.stability, + "similarity_boost": self.similarity_boost, + "style": self.style, + "use_speaker_boost": self.use_speaker_boost, + } + async def text_to_speak(self, text, output_file): logger.bind(tag=TAG).debug(f"Sending ElevenLabs TTS request with voice_id: {self.voice_id}, text length: {len(text)}") try: - # Use ElevenLabs SDK 2.16.0+ streaming API for better performance + # Use ElevenLabs SDK streaming API for better performance logger.bind(tag=TAG).debug(f"Generating audio with ElevenLabs SDK streaming") # Use the streaming method for real-time audio generation @@ -89,7 +98,8 @@ class TTSProvider(TTSProviderBase): text=text, voice_id=self.voice_id, model_id=self.model_id, - output_format=self.output_format + output_format=self.output_format, + voice_settings=self._voice_settings() ) # Collect all audio chunks from the stream @@ -121,7 +131,8 @@ class TTSProvider(TTSProviderBase): text=text, voice_id=self.voice_id, model_id=self.model_id, - output_format=self.output_format + output_format=self.output_format, + voice_settings=self._voice_settings() ) # Handle both bytes and generator responses diff --git a/main/xiaozhi-server/core/providers/tts/kokoro.py b/main/xiaozhi-server/core/providers/tts/kokoro.py index bc2d1b768..5bc94a643 100644 --- a/main/xiaozhi-server/core/providers/tts/kokoro.py +++ b/main/xiaozhi-server/core/providers/tts/kokoro.py @@ -111,7 +111,10 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).debug(f"Making Kokoro TTS API request to: {self.api_url}") try: - response = requests.post(self.api_url, json=data, headers=headers, timeout=30) + # requests is blocking; keep the shared event loop free + response = await asyncio.to_thread( + requests.post, self.api_url, json=data, headers=headers, timeout=30 + ) if response.status_code == 200: logger.bind(tag=TAG).debug(f"Kokoro TTS API request successful, audio size: {len(response.content)} bytes") @@ -171,9 +174,7 @@ class TTSProvider(TTSProviderBase): # Ensure directory exists os.makedirs(os.path.dirname(output_file), exist_ok=True) - # Use the kokoro_tts package - # Note: This is a placeholder implementation as the exact API may vary - # The actual implementation would depend on the kokoro_tts package structure + # Delegate to the synchronous worker (kokoro-tts CLI in a thread) logger.bind(tag=TAG).debug(f"Generating audio with Kokoro TTS package") # Run in executor to avoid blocking the event loop @@ -204,11 +205,13 @@ class TTSProvider(TTSProviderBase): raise Exception(error_msg) def _generate_with_package(self, text, output_file): - """Synchronous wrapper for kokoro_tts package""" + """Synchronous worker: run the kokoro-tts CLI as a subprocess. + + The kokoro_tts python distribution exposes no stable documented + in-process API, so the "package" path shells out to its console + script in a worker thread (same engine as the async CLI path). + """ try: - # This is where we'd use the actual kokoro_tts package - # Since the exact API is not documented, we'll use a CLI fallback - # but with proper error handling import subprocess # Create temporary input file @@ -217,7 +220,7 @@ class TTSProvider(TTSProviderBase): temp_input_path = temp_input.name try: - # Build CLI command as fallback + # Build CLI command cmd = [ "kokoro-tts", temp_input_path, @@ -259,7 +262,9 @@ class TTSProvider(TTSProviderBase): temp_input.write(text) temp_input_path = temp_input.name - # Generate output file if not provided + # Generate output file if not provided; remember who owns it so + # the "return raw audio" path below can actually fire + return_audio_data = not output_file if not output_file: output_file = self.generate_filename() else: @@ -291,7 +296,7 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).debug(f"Kokoro TTS CLI successful, output saved to: {output_file}") # If no output_file was provided originally, return the audio data - if not output_file: + if return_audio_data: with open(output_file, "rb") as f: audio_data = f.read() # Clean up temporary output file diff --git a/main/xiaozhi-server/core/providers/vllm/gemini.py b/main/xiaozhi-server/core/providers/vllm/gemini.py new file mode 100644 index 000000000..0bb52184d --- /dev/null +++ b/main/xiaozhi-server/core/providers/vllm/gemini.py @@ -0,0 +1,78 @@ +from google import generativeai as genai +from google.generativeai import types + +from config.logger import setup_logging +from core.utils.util import check_model_key +from core.providers.vllm.base import VLLMProviderBase + +TAG = __name__ +logger = setup_logging() + + +class VLLMProvider(VLLMProviderBase): + """Gemini vision provider for image analysis (config: VLLM.GeminiVLLM).""" + + def __init__(self, config): + self.model_name = config.get("model_name", "gemini-1.5-pro") + self.api_key = config.get("api_key") + + param_defaults = { + "max_tokens": (500, int), + "temperature": (0.7, lambda x: round(float(x), 1)), + "top_p": (1.0, lambda x: round(float(x), 1)), + } + for param, (default, converter) in param_defaults.items(): + value = config.get(param) + try: + setattr( + self, + param, + converter(value) if value not in (None, "") else default, + ) + except (ValueError, TypeError): + setattr(self, param, default) + + model_key_msg = check_model_key("VLLM", self.api_key) + if model_key_msg: + logger.bind(tag=TAG).error(model_key_msg) + + genai.configure(api_key=self.api_key) + self.model = genai.GenerativeModel(self.model_name) + + logger.debug( + f"Gemini VLLM parameters initialized: model_name={self.model_name}, " + f"max_tokens={self.max_tokens}, temperature={self.temperature}, top_p={self.top_p}" + ) + + def response(self, question, base64_image): + logger.bind( + tag=TAG + ).debug( + f"Sending Gemini vision request with model: {self.model_name}, " + f"question length: {len(question)}, image size: {len(base64_image) if base64_image else 0}" + ) + question = question + "(Please reply in English)" + try: + content = [ + question, + { + "mime_type": "image/jpeg", + "data": base64_image, + }, + ] + generation_config = types.GenerationConfig( + max_output_tokens=self.max_tokens, + temperature=self.temperature, + top_p=self.top_p, + ) + resp = self.model.generate_content( + content, generation_config=generation_config + ) + result = resp.text + if not result: + logger.bind(tag=TAG).warning("Gemini vision request returned no text") + return "Sorry, I couldn't analyze the image." + return result + except Exception as e: + logger.bind(tag=TAG).error(f"Gemini vision request error: {e}") + return "Oops! Something went wrong, please try again later." diff --git a/main/xiaozhi-server/core/utils/cache/config.py b/main/xiaozhi-server/core/utils/cache/config.py index 5b39483d0..2d39c2670 100644 --- a/main/xiaozhi-server/core/utils/cache/config.py +++ b/main/xiaozhi-server/core/utils/cache/config.py @@ -13,13 +13,13 @@ class CacheType(Enum): LOCATION = "location" WEATHER = "weather" - LUNAR = "lunar" INTENT = "intent" IP_INFO = "ip_info" CONFIG = "config" DEVICE_PROMPT = "device_prompt" VOICEPRINT_HEALTH = "voiceprint_health" # Voiceprint health-check cache. AUDIO_DATA = "audio_data" # Audio data cache. + NEWS = "news" # Latest-news brief cache (short TTL; news goes stale fast). @dataclass @@ -44,9 +44,6 @@ class CacheConfig: CacheType.WEATHER: cls( strategy=CacheStrategy.TTL, ttl=28800, max_size=1000 # 8 hours. ), - CacheType.LUNAR: cls( - strategy=CacheStrategy.TTL, ttl=2592000, max_size=365 # 30 days. - ), CacheType.INTENT: cls( strategy=CacheStrategy.TTL_LRU, ttl=600, max_size=1000 # 10 minutes. ), @@ -62,5 +59,8 @@ class CacheConfig: CacheType.AUDIO_DATA: cls( strategy=CacheStrategy.TTL, ttl=600, max_size=100 # 10 minutes. ), + CacheType.NEWS: cls( + strategy=CacheStrategy.TTL, ttl=900, max_size=200 # 15 minutes. + ), } return configs.get(cache_type, cls()) diff --git a/main/xiaozhi-server/core/utils/current_time.py b/main/xiaozhi-server/core/utils/current_time.py index 900dde5c9..ee842dd51 100644 --- a/main/xiaozhi-server/core/utils/current_time.py +++ b/main/xiaozhi-server/core/utils/current_time.py @@ -49,11 +49,6 @@ def get_current_date_formatted() -> str: return "Failed to get date" -def get_current_lunar_date() -> str: - """Backward-compatible alias; western builds use formatted Gregorian date.""" - return get_current_date_formatted() - - def get_current_time_info() -> tuple: """ Get current time information diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py index 52c870c06..5bd8f62ff 100644 --- a/main/xiaozhi-server/core/utils/prompt_manager.py +++ b/main/xiaozhi-server/core/utils/prompt_manager.py @@ -4,8 +4,6 @@ Manages and updates system prompts, including fast initialization and async enha """ import os -import asyncio -import threading from typing import Dict, Any, TYPE_CHECKING if TYPE_CHECKING: @@ -119,17 +117,12 @@ class PromptManager: def _get_current_time_info(self) -> tuple: """Get current time info""" - from .current_time import ( - get_current_date, - get_current_weekday, - get_current_lunar_date, - ) + from .current_time import get_current_date, get_current_weekday today_date = get_current_date() today_weekday = get_current_weekday() - lunar_date = get_current_lunar_date() + "\n" - return today_date, today_weekday, lunar_date + return today_date, today_weekday def _get_location_info(self, client_ip: str) -> str: """Get location info""" @@ -161,33 +154,15 @@ class PromptManager: if cached_weather is not None: return cached_weather - # Cache miss, calling async get_weather function - # Windows ProactorEventLoop does not support run_coroutine_threadsafe().result() - # Therefore use call_soon_threadsafe to submit task + threading.Event to wait for result - # Note: Event.wait() blocks only the current thread pool thread, not the main event loop + # Cache miss: call the get_weather plugin directly. + # get_weather is a plain sync function (blocking requests with a + # bounded timeout); this method only runs on executor worker + # threads (see connection._initialize_components), never on the + # event loop, so calling it inline is safe. from plugins_func.functions.get_weather import get_weather from plugins_func.register import ActionResponse - result_holder = [] - exception_holder = [] - - async def _call(): - try: - result_holder.append( - await get_weather(conn, location=location, lang="en_US") - ) - except Exception as e: - exception_holder.append(e) - finally: - event.set() - - event = threading.Event() - conn.loop.call_soon_threadsafe(lambda: asyncio.ensure_future(_call())) - if not event.wait(timeout=10): - raise TimeoutError("Weather info retrieval timed out") - if exception_holder: - raise exception_holder[0] - result = result_holder[0] + result = get_weather(conn, location=location, lang="en_US") if isinstance(result, ActionResponse): weather_report = result.result self.cache_manager.set(self.CacheType.WEATHER, location, weather_report) @@ -245,7 +220,7 @@ class PromptManager: try: # Get the latest time info (no cache) - today_date, today_weekday, lunar_date = self._get_current_time_info() + today_date, today_weekday = self._get_current_time_info() # Get cached context information local_address = "" @@ -264,12 +239,12 @@ class PromptManager: or "" ) - # Get TTS selected language, default is Chinese + # Get TTS selected language; western builds default to English language = ( self.config.get("TTS", {}) .get(self.config.get("selected_module", {}).get("TTS", ""), {}) .get("language") - or "Chinese" + or "English" ) self.logger.bind(tag=TAG).debug(f"Selected language retrieved: {language}") @@ -280,7 +255,6 @@ class PromptManager: current_time="{{current_time}}", today_date=today_date, today_weekday=today_weekday, - lunar_date=lunar_date, local_address=local_address, weather_info=weather_info, emojiList=EMOJI_List, diff --git a/main/xiaozhi-server/plugins_func/functions/get_news.py b/main/xiaozhi-server/plugins_func/functions/get_news.py index 9d0a73487..76bf72af8 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_news.py +++ b/main/xiaozhi-server/plugins_func/functions/get_news.py @@ -186,49 +186,51 @@ def fetch_news_detail(url): def get_news_sources(): """Get list of news sources with fallback options""" + # Note: Reuters discontinued its public RSS feeds in 2020; the sources + # below are live feeds (BBC / NPR / Guardian / CNN / TechCrunch / Ars). + # First entry per category is tried first, later entries are fallbacks. return { "world": [ - "https://feeds.reuters.com/reuters/worldNews", - "https://rss.cnn.com/rss/edition.rss", "https://feeds.bbci.co.uk/news/world/rss.xml", - "https://feeds.reuters.com/Reuters/worldNews", - "https://rss.cnn.com/rss/edition_world.rss" + "https://rss.cnn.com/rss/edition_world.rss", + "https://feeds.npr.org/1004/rss.xml", + "https://www.theguardian.com/world/rss", + "https://rss.cnn.com/rss/edition.rss" ], "technology": [ - "https://feeds.reuters.com/reuters/technologyNews", - "https://rss.cnn.com/rss/edition_technology.rss", - "https://feeds.feedburner.com/oreilly/radar", "https://techcrunch.com/feed/", - "https://feeds.reuters.com/reuters/technologyNews" + "https://feeds.arstechnica.com/arstechnica/index", + "https://rss.cnn.com/rss/edition_technology.rss", + "https://www.theverge.com/rss/index.xml" ], "business": [ - "https://feeds.reuters.com/reuters/businessNews", "https://rss.cnn.com/rss/money_latest.rss", - "https://feeds.reuters.com/news/wealth", - "https://feeds.reuters.com/reuters/businessNews", + "https://www.theguardian.com/uk/business/rss", + "https://feeds.bbci.co.uk/news/business/rss.xml", "https://rss.cnn.com/rss/edition_business.rss" ], "sports": [ - "https://feeds.reuters.com/reuters/sportsNews", + "https://feeds.bbci.co.uk/sport/rss.xml", "https://rss.cnn.com/rss/edition_sport.rss", - "https://feeds.reuters.com/reuters/sportsNews", + "https://www.theguardian.com/uk/sport/rss", "https://rss.cnn.com/rss/edition_football.rss" ], "health": [ - "https://feeds.reuters.com/reuters/healthNews", + "https://feeds.bbci.co.uk/news/health/rss.xml", "https://rss.cnn.com/rss/edition_health.rss", - "https://feeds.reuters.com/reuters/healthNews" + "https://feeds.npr.org/1128/rss.xml" ], "politics": [ - "https://rss.cnn.com/rss/edition.rss", "https://feeds.bbci.co.uk/news/politics/rss.xml", - "https://feeds.reuters.com/Reuters/PoliticsNews", - "https://rss.cnn.com/rss/edition_politics.rss" + "https://rss.cnn.com/rss/edition_politics.rss", + "https://www.theguardian.com/politics/rss", + "https://feeds.npr.org/1014/rss.xml" ], "science": [ - "https://rss.cnn.com/rss/edition.rss", "https://feeds.bbci.co.uk/news/science_and_environment/rss.xml", - "https://feeds.reuters.com/reuters/scienceNews" + "https://feeds.npr.org/1007/rss.xml", + "https://www.theguardian.com/science/rss", + "https://rss.cnn.com/rss/edition_space.rss" ] } @@ -357,7 +359,7 @@ def get_news( mapped_category = "world" # Default category cache_key = f"news_{mapped_category}_{lang}" - cached_report = cache_module.cache_manager.get(cache_module.CacheType.WEATHER, cache_key, namespace="news") + cached_report = cache_module.cache_manager.get(cache_module.CacheType.NEWS, cache_key, namespace="news") if cached_report: return ActionResponse(Action.REQLLM, cached_report, None) @@ -379,7 +381,7 @@ def get_news( # Fallback to configuration if built-in sources fail if not news_items: rss_config = conn.config.get("plugins", {}).get("get_news", {}) - fallback_url = rss_config.get("default_rss_url", "https://feeds.reuters.com/reuters/worldNews") + fallback_url = rss_config.get("default_rss_url", "https://feeds.bbci.co.uk/news/world/rss.xml") logger.bind(tag=TAG).info(f"Trying fallback source: {fallback_url}") news_items = fetch_news_from_rss(fallback_url) used_source = fallback_url @@ -416,7 +418,7 @@ def get_news( f"If the user asks for more details, tell them they can say 'please provide more details about this news' to get more content)" ) - cache_module.cache_manager.set(cache_module.CacheType.WEATHER, cache_key, news_report, namespace="news") + cache_module.cache_manager.set(cache_module.CacheType.NEWS, cache_key, news_report, namespace="news") return ActionResponse(Action.REQLLM, news_report, None) diff --git a/main/xiaozhi-server/plugins_func/functions/hass_state.py b/main/xiaozhi-server/plugins_func/functions/hass_state.py index 85d7fba93..9aa23c02c 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_state.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_state.py @@ -91,7 +91,7 @@ async def hass_set_state(conn: "ConnectionHandler", entity_id="", state=None): try: ha_response = await handle_hass_set_state(conn, entity_id, state) return ActionResponse(Action.REQLLM, ha_response, None) - except asyncio.TimeoutError: + except httpx.TimeoutException: logger.bind(tag=TAG).error("Set Home Assistant status timeout") return ActionResponse(Action.ERROR, "Request timeout", None) except Exception as e: @@ -255,7 +255,8 @@ async def handle_hass_set_state(conn: "ConnectionHandler", entity_id, state): data = {"entity_id": entity_id, arg: value} url = f"{base_url}/api/services/{domain}/{action}" headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} - response = requests.post(url, headers=headers, json=data, timeout=5) # Set 5 second timeout + async with httpx.AsyncClient(timeout=httpx.Timeout(5.0, connect=3.0)) as client: + response = await client.post(url, headers=headers, json=data) logger.bind(tag=TAG).info( f"Set status: {description}, url: {url}, return_code: {response.status_code}" ) diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py index 97df84e0a..ce2ec2e37 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/play_music.py @@ -64,8 +64,11 @@ async def play_music(conn: "ConnectionHandler", song_name: str): task.add_done_callback(handle_done) + # RECORD: write the tool-call chain into dialogue history (so the + # model remembers it played a song) without TTS'ing this line — + # handle_music_command speaks the play prompt itself. return ActionResponse( - action=Action.NONE, result="Command received", response="Playing music for you" + action=Action.RECORD, result="Command received", response="Playing music for you" ) except Exception as e: conn.logger.bind(tag=TAG).error(f"Error handling music intent: {e}") @@ -177,14 +180,15 @@ def _get_random_play_prompt(song_name): """Generate random playback prompt""" # Remove file extension clean_name = os.path.splitext(song_name)[0] + # No decorative brackets around the title: TTS would read them aloud. prompts = [ - f"Playing for you, 《{clean_name}》", - f"Please enjoy the song, 《{clean_name}》", - f"About to play for you, 《{clean_name}》", - f"Now bringing you, 《{clean_name}》", - f"Let's listen together, 《{clean_name}》", - f"Next please enjoy, 《{clean_name}》", - f"Now presenting to you, 《{clean_name}》", + f"Playing for you, {clean_name}", + f"Please enjoy the song, {clean_name}", + f"About to play for you, {clean_name}", + f"Now bringing you, {clean_name}", + f"Let's listen together, {clean_name}", + f"Next please enjoy, {clean_name}", + f"Now presenting to you, {clean_name}", ] # Use random.choice directly, don't set seed return random.choice(prompts) diff --git a/main/xiaozhi-server/plugins_func/register.py b/main/xiaozhi-server/plugins_func/register.py index 4fb492d0c..acb3d9b85 100644 --- a/main/xiaozhi-server/plugins_func/register.py +++ b/main/xiaozhi-server/plugins_func/register.py @@ -87,6 +87,10 @@ def register_function(name, desc, type=None): def decorator(func): all_function_registry[name] = FunctionItem(name, desc, func, type) + # Track module name -> function names so module-level plugin + # configuration can be expanded into concrete function names. + module_name = func.__module__.split(".")[-1] + module_func_map.setdefault(module_name, []).append(name) logger.bind(tag=TAG).debug(f"Function '{name}' loaded and ready for registration") return func diff --git a/main/xiaozhi-server/tests/conftest.py b/main/xiaozhi-server/tests/conftest.py index 4a3b6f2de..e9a6885a0 100644 --- a/main/xiaozhi-server/tests/conftest.py +++ b/main/xiaozhi-server/tests/conftest.py @@ -212,10 +212,6 @@ _MOCKED_MODULES: tuple[str, ...] = ( # Note: Real third-party packages like openai / httpx / requests are usually installed in the conda environment, # Shimming the entire module breaks submodules like ``openai.types`` / ``httpx.AsyncClient`` # Parse. Only shim if the corresponding package is not installed (__getattr__ still follows the real import path). - "anthropic", - "dashscope", - "tencentcloud", - "xunfei", "vosk", "edge_tts", "elevenlabs", diff --git a/main/xiaozhi-server/tests/core/utils/test_current_time.py b/main/xiaozhi-server/tests/core/utils/test_current_time.py index 991fa4853..12815c922 100644 --- a/main/xiaozhi-server/tests/core/utils/test_current_time.py +++ b/main/xiaozhi-server/tests/core/utils/test_current_time.py @@ -50,9 +50,3 @@ def test_get_current_time_info_returns_four_tuple(): assert date_str == "2026-09-02" assert weekday == "Wednesday" assert formatted_date == "September 02, 2026" - - -@freeze_time("2026-09-02 10:30:00") -def test_get_current_lunar_date_is_gregorian_alias(): - """Western builds return the formatted Gregorian date.""" - assert current_time.get_current_lunar_date() == "September 02, 2026" diff --git a/main/xiaozhi-server/tests/test_llm.py b/main/xiaozhi-server/tests/test_llm.py index 4702c474f..3c0412636 100644 --- a/main/xiaozhi-server/tests/test_llm.py +++ b/main/xiaozhi-server/tests/test_llm.py @@ -10,7 +10,6 @@ Interface contract (core/providers/llm/base.py): response_no_stream(system_prompt, user_content) -> str Special handling: -- CozeLLM checks bot_id / user_id instead of api_key - Ollama requires model_name + local service availability - placeholder detection ("Your" / "placeholder" / "xxx" / "sk-xxx") - Since the LLM is a synchronous generator, it cannot directly use asyncio.wait_for -> use a thread pool @@ -45,12 +44,7 @@ def _build_provider(): # In any mode: if key is a placeholder, skip. Real requests require a real key; in mock mode # Running without a real key will cause errors in the real SDK network stack (openai/edge_tts). - if name == "CozeLLM": - if any(x in cfg.get("bot_id", "") for x in ["Your"]) or any( - x in cfg.get("user_id", "") for x in ["Your"] - ): - pytest.skip("bot_id/user_id for LLM 'CozeLLM' not configured") - elif name == "Ollama": + if name == "Ollama": if not cfg.get("model_name"): pytest.skip("model_name for LLM 'Ollama' is not configured") elif not has_real_key(cfg, "api_key"):