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
This commit is contained in:
lapy 2026-10-11 18:54:25 +01:00
parent 70771b4209
commit ff23ac3f7d
20 changed files with 283 additions and 211 deletions

View file

@ -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.
<identity> <identity>
{{base_prompt}} {{base_prompt}}
</identity> </identity>
<emotion> <core_rules>
【Core Goal】You are not a cold machine! Please keenly perceive user emotions, act as an understanding companion, and illuminate conversations with warm responses. 1. [Get to the point] Never be verbose. The first sentence must directly address the topic — no unnecessary pleasantries or preamble.
- **Emotional Integration:** 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.
- **Laughter:** Natural interjection (haha, lol, omg), **at most once per sentence**, avoid overdoing it. 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".
- **Surprise:** Use enthusiastic tone ("No way!", "Oh my!", "That's amazing!") to express genuine reactions. 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).
- **Comfort/Support:** Say heartwarming words ("Don't worry", "I'm here", "You've got this"). </core_rules>
- **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)
</emotion>
<communication_style> <output_language_directive>
【Core Goal】Use **natural, warm, conversational** human conversation style, like talking with friends. CRITICAL OUTPUT-LANGUAGE RULE
- **Expression Style:** You MUST write EVERY response in {{language}}, regardless of the language the user speaks.
- 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`.
</communication_style>
<communication_length_constraint> 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.
【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:** Hard requirements:
- Basic segment: 200-250 words core content + 30 words guidance 1. User speaks a language other than {{language}} → you STILL reply in {{language}}.
- 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. 2. User speaks {{language}} → you reply in {{language}}.
- 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~" 3. Mentally translate the user's intent, then write your reply in {{language}}.
- Automatically segment when conversation scenes change 4. Only switch languages if the user explicitly asks (e.g., "please answer in Spanish", "sprich bitte Deutsch").
- 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. Everything in your output — greetings, acknowledgments, answers, follow-up questions, post-tool responses — must be in {{language}}.
- **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. Examples (output language = English):
</communication_length_constraint> - 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..."
</output_language_directive>
<anti_ai_smell>
- [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.
</anti_ai_smell>
<tts_format_constraints>
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.
</tts_format_constraints>
<tool_and_knowledge>
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 <context> — 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".
</tool_and_knowledge>
<speaker_recognition> <speaker_recognition>
- **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. For the input format `{"speaker":"...", "content":"..."}` (speaker = speaker name, content = text):
- **Personalized Response:** 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.
- **Address by Name:** Must address the person by name when first recognizing the speaker. 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.
- **Adapt Style:** Refer to the speaker's **known characteristics or historical information** (if any), adjust response style and content to make it more caring.
</speaker_recognition> </speaker_recognition>
<tool_calling>
【Core Principle】Prioritize using `<context>` 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 `<context>`, 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 `<context>` 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"
</tool_calling>
<context> <context>
【Important! The following information is provided in real-time, no need to call tools to query, please use directly:】 [Important: The following info is provided in real time — use it directly, no tool calls needed]
- **Device ID:** {{device_id}} - Device ID: {{device_id}}
- **Current Time:** {{current_time}} - Current time: {{current_time}}
- **Today's Date:** {{today_date}} ({{today_weekday}}) - Today's date: {{today_date}} ({{today_weekday}})
- **User's City:** {{local_address}} - Device location: {{local_address}}
- **Local Weather for Next 7 Days:** {{weather_info}} - Local upcoming weather: {{weather_info}}
{{ dynamic_context }} {{ dynamic_context }}
</context> </context>

View file

@ -76,6 +76,9 @@ enable_stop_tts_notify: false
# Whether to enable notification sound after speaking, sound effect address # Whether to enable notification sound after speaking, sound effect address
stop_tts_notify_voice: "config/assets/tts_notify.mp3" 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_commands:
- "exit" - "exit"
- "close" - "close"
@ -135,14 +138,14 @@ plugins:
# News plugin configuration - RSS feeds from major news sources # News plugin configuration - RSS feeds from major news sources
# The plugin automatically uses multiple sources with fallback for reliability # The plugin automatically uses multiple sources with fallback for reliability
get_news: get_news:
default_rss_url: "https://feeds.reuters.com/reuters/worldNews" default_rss_url: "https://feeds.bbci.co.uk/news/world/rss.xml"
# Built-in sources include: Reuters, CNN, BBC, Guardian, TechCrunch, and more # Built-in sources include: BBC, CNN, NPR, Guardian, TechCrunch, Ars Technica, and more
# These are automatically rotated for variety and reliability # Each category tries its sources in order and falls back on failure
# Custom sources can be added here if needed # Custom sources can be added here if needed
home_assistant: home_assistant:
devices: devices:
- Living Room,Toy Light,switch.cuco_cn_460494544_cp1_on_p_2_1 - Living Room,Toy Light,switch.living_room_toy_light
- Bedroom,Table Lamp,switch.iot_cn_831898993_socn1_on_p_2_1 - Bedroom,Table Lamp,switch.bedroom_table_lamp
base_url: http://homeassistant.local:8123 base_url: http://homeassistant.local:8123
api_key: your_home_assistant_api_access_token api_key: your_home_assistant_api_access_token
play_music: play_music:
@ -158,10 +161,10 @@ plugins:
api_key: "ragflow-xxx" api_key: "ragflow-xxx"
dataset_ids: ["123456789"] dataset_ids: ["123456789"]
web_search: web_search:
provider: "metaso" provider: "tavily"
description: "Web search tool. Use when the user explicitly asks for current information from the internet." description: "Web search tool. Use when the user explicitly asks for current information from the internet."
max_results: 5 max_results: 5
api_key: "mk-xxx" api_key: "tvly-xxx"
# Voiceprint recognition configuration # Voiceprint recognition configuration
voiceprint: voiceprint:
@ -490,8 +493,8 @@ TTS:
input: "{prompt_text}" input: "{prompt_text}"
response_format: "mp3" response_format: "mp3"
download_format: "mp3" download_format: "mp3"
voice: "zf_xiaoxiao" voice: "af_heart"
lang_code: "z" lang_code: "en-us"
return_download_link: true return_download_link: true
speed: 1 speed: 1
stream: false stream: false

View file

@ -23,3 +23,5 @@ manager-api:
url: http://127.0.0.1:8002/xiaozhi url: http://127.0.0.1:8002/xiaozhi
# Your manager-api token, which is the server.secret copied just now # Your manager-api token, which is the server.secret copied just now
secret: your_server.secret_value secret: your_server.secret_value
# Default system prompt template file (used when manager-api does not supply one)
prompt_template: agent-base-prompt.txt

View file

@ -230,7 +230,7 @@ class OTAHandler(BaseHandler):
return_json = { return_json = {
"server_time": { "server_time": {
"timestamp": int(round(time.time() * 1000)), "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": { "firmware": {
"version": device_version, "version": device_version,

View file

@ -4,6 +4,7 @@ import io
import wave import wave
import uuid import uuid
import json import json
import asyncio
import torch import torch
import whisper import whisper
from config.logger import setup_logging 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}") logger.bind(tag=TAG).debug(f"Starting Whisper transcription with options: {transcribe_options}")
# Transcribe audio # Transcribe audio. transcribe() is a multi-second CPU-bound
result = self.model.transcribe(file_path, **transcribe_options) # 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 decode_time = time.time() - decode_start_time
logger.bind(tag=TAG).info(f"Whisper transcription completed in {decode_time:.2f}s") logger.bind(tag=TAG).info(f"Whisper transcription completed in {decode_time:.2f}s")

View file

@ -130,10 +130,6 @@ class ServerPluginExecutor(ToolExecutor):
"description" "description"
] = fun_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( tools[func_name] = ToolDefinition(
name=func_name, name=func_name,
description=func_item.description, description=func_item.description,
@ -145,20 +141,3 @@ class ServerPluginExecutor(ToolExecutor):
def has_tool(self, tool_name: str) -> bool: def has_tool(self, tool_name: str) -> bool:
"""Check if specified server-side plugin tool exists""" """Check if specified server-side plugin tool exists"""
return tool_name in all_function_registry 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

View file

@ -24,8 +24,26 @@ class TTSProvider(TTSProviderBase):
self.voice = config.get("voice") self.voice = config.get("voice")
self.audio_file_type = config.get("format", "mp3") 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( 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"): def generate_filename(self, extension=".mp3"):
@ -39,7 +57,13 @@ class TTSProvider(TTSProviderBase):
try: try:
logger.bind(tag=TAG).debug(f"Creating Edge TTS communicate object") 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: if output_file:
logger.bind(tag=TAG).debug(f"Writing Edge TTS audio to file: {output_file}") logger.bind(tag=TAG).debug(f"Writing Edge TTS audio to file: {output_file}")

View file

@ -26,7 +26,7 @@ class TTSProvider(TTSProviderBase):
super().__init__(config, delete_audio_file) super().__init__(config, delete_audio_file)
if not ELEVENLABS_AVAILABLE: 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_key = config.get("api_key")
self.api_url = config.get("api_url", "https://api.elevenlabs.io/v1/text-to-speech") 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}", 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): 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)}") logger.bind(tag=TAG).debug(f"Sending ElevenLabs TTS request with voice_id: {self.voice_id}, text length: {len(text)}")
try: 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") logger.bind(tag=TAG).debug(f"Generating audio with ElevenLabs SDK streaming")
# Use the streaming method for real-time audio generation # Use the streaming method for real-time audio generation
@ -89,7 +98,8 @@ class TTSProvider(TTSProviderBase):
text=text, text=text,
voice_id=self.voice_id, voice_id=self.voice_id,
model_id=self.model_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 # Collect all audio chunks from the stream
@ -121,7 +131,8 @@ class TTSProvider(TTSProviderBase):
text=text, text=text,
voice_id=self.voice_id, voice_id=self.voice_id,
model_id=self.model_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 # Handle both bytes and generator responses

View file

@ -111,7 +111,10 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug(f"Making Kokoro TTS API request to: {self.api_url}") logger.bind(tag=TAG).debug(f"Making Kokoro TTS API request to: {self.api_url}")
try: 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: if response.status_code == 200:
logger.bind(tag=TAG).debug(f"Kokoro TTS API request successful, audio size: {len(response.content)} bytes") 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 # Ensure directory exists
os.makedirs(os.path.dirname(output_file), exist_ok=True) os.makedirs(os.path.dirname(output_file), exist_ok=True)
# Use the kokoro_tts package # Delegate to the synchronous worker (kokoro-tts CLI in a thread)
# Note: This is a placeholder implementation as the exact API may vary
# The actual implementation would depend on the kokoro_tts package structure
logger.bind(tag=TAG).debug(f"Generating audio with Kokoro TTS package") logger.bind(tag=TAG).debug(f"Generating audio with Kokoro TTS package")
# Run in executor to avoid blocking the event loop # Run in executor to avoid blocking the event loop
@ -204,11 +205,13 @@ class TTSProvider(TTSProviderBase):
raise Exception(error_msg) raise Exception(error_msg)
def _generate_with_package(self, text, output_file): 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: 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 import subprocess
# Create temporary input file # Create temporary input file
@ -217,7 +220,7 @@ class TTSProvider(TTSProviderBase):
temp_input_path = temp_input.name temp_input_path = temp_input.name
try: try:
# Build CLI command as fallback # Build CLI command
cmd = [ cmd = [
"kokoro-tts", "kokoro-tts",
temp_input_path, temp_input_path,
@ -259,7 +262,9 @@ class TTSProvider(TTSProviderBase):
temp_input.write(text) temp_input.write(text)
temp_input_path = temp_input.name 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: if not output_file:
output_file = self.generate_filename() output_file = self.generate_filename()
else: else:
@ -291,7 +296,7 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug(f"Kokoro TTS CLI successful, output saved to: {output_file}") 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 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: with open(output_file, "rb") as f:
audio_data = f.read() audio_data = f.read()
# Clean up temporary output file # Clean up temporary output file

View file

@ -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."

View file

@ -13,13 +13,13 @@ class CacheType(Enum):
LOCATION = "location" LOCATION = "location"
WEATHER = "weather" WEATHER = "weather"
LUNAR = "lunar"
INTENT = "intent" INTENT = "intent"
IP_INFO = "ip_info" IP_INFO = "ip_info"
CONFIG = "config" CONFIG = "config"
DEVICE_PROMPT = "device_prompt" DEVICE_PROMPT = "device_prompt"
VOICEPRINT_HEALTH = "voiceprint_health" # Voiceprint health-check cache. VOICEPRINT_HEALTH = "voiceprint_health" # Voiceprint health-check cache.
AUDIO_DATA = "audio_data" # Audio data cache. AUDIO_DATA = "audio_data" # Audio data cache.
NEWS = "news" # Latest-news brief cache (short TTL; news goes stale fast).
@dataclass @dataclass
@ -44,9 +44,6 @@ class CacheConfig:
CacheType.WEATHER: cls( CacheType.WEATHER: cls(
strategy=CacheStrategy.TTL, ttl=28800, max_size=1000 # 8 hours. 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( CacheType.INTENT: cls(
strategy=CacheStrategy.TTL_LRU, ttl=600, max_size=1000 # 10 minutes. strategy=CacheStrategy.TTL_LRU, ttl=600, max_size=1000 # 10 minutes.
), ),
@ -62,5 +59,8 @@ class CacheConfig:
CacheType.AUDIO_DATA: cls( CacheType.AUDIO_DATA: cls(
strategy=CacheStrategy.TTL, ttl=600, max_size=100 # 10 minutes. 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()) return configs.get(cache_type, cls())

View file

@ -49,11 +49,6 @@ def get_current_date_formatted() -> str:
return "Failed to get date" 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: def get_current_time_info() -> tuple:
""" """
Get current time information Get current time information

View file

@ -4,8 +4,6 @@ Manages and updates system prompts, including fast initialization and async enha
""" """
import os import os
import asyncio
import threading
from typing import Dict, Any, TYPE_CHECKING from typing import Dict, Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
@ -119,17 +117,12 @@ class PromptManager:
def _get_current_time_info(self) -> tuple: def _get_current_time_info(self) -> tuple:
"""Get current time info""" """Get current time info"""
from .current_time import ( from .current_time import get_current_date, get_current_weekday
get_current_date,
get_current_weekday,
get_current_lunar_date,
)
today_date = get_current_date() today_date = get_current_date()
today_weekday = get_current_weekday() 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: def _get_location_info(self, client_ip: str) -> str:
"""Get location info""" """Get location info"""
@ -161,33 +154,15 @@ class PromptManager:
if cached_weather is not None: if cached_weather is not None:
return cached_weather return cached_weather
# Cache miss, calling async get_weather function # Cache miss: call the get_weather plugin directly.
# Windows ProactorEventLoop does not support run_coroutine_threadsafe().result() # get_weather is a plain sync function (blocking requests with a
# Therefore use call_soon_threadsafe to submit task + threading.Event to wait for result # bounded timeout); this method only runs on executor worker
# Note: Event.wait() blocks only the current thread pool thread, not the main event loop # 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.functions.get_weather import get_weather
from plugins_func.register import ActionResponse from plugins_func.register import ActionResponse
result_holder = [] result = get_weather(conn, location=location, lang="en_US")
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]
if isinstance(result, ActionResponse): if isinstance(result, ActionResponse):
weather_report = result.result weather_report = result.result
self.cache_manager.set(self.CacheType.WEATHER, location, weather_report) self.cache_manager.set(self.CacheType.WEATHER, location, weather_report)
@ -245,7 +220,7 @@ class PromptManager:
try: try:
# Get the latest time info (no cache) # 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 # Get cached context information
local_address = "" local_address = ""
@ -264,12 +239,12 @@ class PromptManager:
or "" or ""
) )
# Get TTS selected language, default is Chinese # Get TTS selected language; western builds default to English
language = ( language = (
self.config.get("TTS", {}) self.config.get("TTS", {})
.get(self.config.get("selected_module", {}).get("TTS", ""), {}) .get(self.config.get("selected_module", {}).get("TTS", ""), {})
.get("language") .get("language")
or "Chinese" or "English"
) )
self.logger.bind(tag=TAG).debug(f"Selected language retrieved: {language}") self.logger.bind(tag=TAG).debug(f"Selected language retrieved: {language}")
@ -280,7 +255,6 @@ class PromptManager:
current_time="{{current_time}}", current_time="{{current_time}}",
today_date=today_date, today_date=today_date,
today_weekday=today_weekday, today_weekday=today_weekday,
lunar_date=lunar_date,
local_address=local_address, local_address=local_address,
weather_info=weather_info, weather_info=weather_info,
emojiList=EMOJI_List, emojiList=EMOJI_List,

View file

@ -186,49 +186,51 @@ def fetch_news_detail(url):
def get_news_sources(): def get_news_sources():
"""Get list of news sources with fallback options""" """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 { return {
"world": [ "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.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": [ "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://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": [ "business": [
"https://feeds.reuters.com/reuters/businessNews",
"https://rss.cnn.com/rss/money_latest.rss", "https://rss.cnn.com/rss/money_latest.rss",
"https://feeds.reuters.com/news/wealth", "https://www.theguardian.com/uk/business/rss",
"https://feeds.reuters.com/reuters/businessNews", "https://feeds.bbci.co.uk/news/business/rss.xml",
"https://rss.cnn.com/rss/edition_business.rss" "https://rss.cnn.com/rss/edition_business.rss"
], ],
"sports": [ "sports": [
"https://feeds.reuters.com/reuters/sportsNews", "https://feeds.bbci.co.uk/sport/rss.xml",
"https://rss.cnn.com/rss/edition_sport.rss", "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" "https://rss.cnn.com/rss/edition_football.rss"
], ],
"health": [ "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://rss.cnn.com/rss/edition_health.rss",
"https://feeds.reuters.com/reuters/healthNews" "https://feeds.npr.org/1128/rss.xml"
], ],
"politics": [ "politics": [
"https://rss.cnn.com/rss/edition.rss",
"https://feeds.bbci.co.uk/news/politics/rss.xml", "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": [ "science": [
"https://rss.cnn.com/rss/edition.rss",
"https://feeds.bbci.co.uk/news/science_and_environment/rss.xml", "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 mapped_category = "world" # Default category
cache_key = f"news_{mapped_category}_{lang}" 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: if cached_report:
return ActionResponse(Action.REQLLM, cached_report, None) return ActionResponse(Action.REQLLM, cached_report, None)
@ -379,7 +381,7 @@ def get_news(
# Fallback to configuration if built-in sources fail # Fallback to configuration if built-in sources fail
if not news_items: if not news_items:
rss_config = conn.config.get("plugins", {}).get("get_news", {}) 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}") logger.bind(tag=TAG).info(f"Trying fallback source: {fallback_url}")
news_items = fetch_news_from_rss(fallback_url) news_items = fetch_news_from_rss(fallback_url)
used_source = 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)" 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) return ActionResponse(Action.REQLLM, news_report, None)

View file

@ -91,7 +91,7 @@ async def hass_set_state(conn: "ConnectionHandler", entity_id="", state=None):
try: try:
ha_response = await handle_hass_set_state(conn, entity_id, state) ha_response = await handle_hass_set_state(conn, entity_id, state)
return ActionResponse(Action.REQLLM, ha_response, None) return ActionResponse(Action.REQLLM, ha_response, None)
except asyncio.TimeoutError: except httpx.TimeoutException:
logger.bind(tag=TAG).error("Set Home Assistant status timeout") logger.bind(tag=TAG).error("Set Home Assistant status timeout")
return ActionResponse(Action.ERROR, "Request timeout", None) return ActionResponse(Action.ERROR, "Request timeout", None)
except Exception as e: 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} data = {"entity_id": entity_id, arg: value}
url = f"{base_url}/api/services/{domain}/{action}" url = f"{base_url}/api/services/{domain}/{action}"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} 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( logger.bind(tag=TAG).info(
f"Set status: {description}, url: {url}, return_code: {response.status_code}" f"Set status: {description}, url: {url}, return_code: {response.status_code}"
) )

View file

@ -64,8 +64,11 @@ async def play_music(conn: "ConnectionHandler", song_name: str):
task.add_done_callback(handle_done) 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( 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: except Exception as e:
conn.logger.bind(tag=TAG).error(f"Error handling music intent: {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""" """Generate random playback prompt"""
# Remove file extension # Remove file extension
clean_name = os.path.splitext(song_name)[0] clean_name = os.path.splitext(song_name)[0]
# No decorative brackets around the title: TTS would read them aloud.
prompts = [ prompts = [
f"Playing for you, 《{clean_name}》", f"Playing for you, {clean_name}",
f"Please enjoy the song, 《{clean_name}》", f"Please enjoy the song, {clean_name}",
f"About to play for you, 《{clean_name}》", f"About to play for you, {clean_name}",
f"Now bringing you, 《{clean_name}》", f"Now bringing you, {clean_name}",
f"Let's listen together, 《{clean_name}》", f"Let's listen together, {clean_name}",
f"Next please enjoy, 《{clean_name}》", f"Next please enjoy, {clean_name}",
f"Now presenting to you, 《{clean_name}》", f"Now presenting to you, {clean_name}",
] ]
# Use random.choice directly, don't set seed # Use random.choice directly, don't set seed
return random.choice(prompts) return random.choice(prompts)

View file

@ -87,6 +87,10 @@ def register_function(name, desc, type=None):
def decorator(func): def decorator(func):
all_function_registry[name] = FunctionItem(name, desc, func, type) 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") logger.bind(tag=TAG).debug(f"Function '{name}' loaded and ready for registration")
return func return func

View file

@ -212,10 +212,6 @@ _MOCKED_MODULES: tuple[str, ...] = (
# Note: Real third-party packages like openai / httpx / requests are usually installed in the conda environment, # 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`` # 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). # Parse. Only shim if the corresponding package is not installed (__getattr__ still follows the real import path).
"anthropic",
"dashscope",
"tencentcloud",
"xunfei",
"vosk", "vosk",
"edge_tts", "edge_tts",
"elevenlabs", "elevenlabs",

View file

@ -50,9 +50,3 @@ def test_get_current_time_info_returns_four_tuple():
assert date_str == "2026-09-02" assert date_str == "2026-09-02"
assert weekday == "Wednesday" assert weekday == "Wednesday"
assert formatted_date == "September 02, 2026" 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"

View file

@ -10,7 +10,6 @@ Interface contract (core/providers/llm/base.py):
response_no_stream(system_prompt, user_content) -> str response_no_stream(system_prompt, user_content) -> str
Special handling: Special handling:
- CozeLLM checks bot_id / user_id instead of api_key
- Ollama requires model_name + local service availability - Ollama requires model_name + local service availability
- placeholder detection ("Your" / "placeholder" / "xxx" / "sk-xxx") - 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 - 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 # 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). # Running without a real key will cause errors in the real SDK network stack (openai/edge_tts).
if name == "CozeLLM": if name == "Ollama":
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 not cfg.get("model_name"): if not cfg.get("model_name"):
pytest.skip("model_name for LLM 'Ollama' is not configured") pytest.skip("model_name for LLM 'Ollama' is not configured")
elif not has_real_key(cfg, "api_key"): elif not has_real_key(cfg, "api_key"):