diff --git a/docs/agent-base-prompt-system.md b/docs/agent-base-prompt-system.md new file mode 100644 index 000000000..87865ad99 --- /dev/null +++ b/docs/agent-base-prompt-system.md @@ -0,0 +1,851 @@ +# Agent Base Prompt System Documentation + +## Overview + +The Xiaozhi server uses a sophisticated prompt system that combines user configuration with a template-based enhancement system. The `agent-base-prompt.txt` file serves as a template that wraps around user-defined prompts from configuration files, adding personality, behavior rules, and dynamic context. This document explains how the entire prompt system works, its architecture, and how it integrates with the configuration system. + +## Architecture Overview + +``` +Configuration Loading (data/.config.yaml + config.yaml) + ↓ + User Prompt Extraction (prompt field) + ↓ + Template Processing (agent-base-prompt.txt) + ↓ + Dynamic Context Injection (time, weather, location) + ↓ + PromptManager (Enhanced Prompt Generation) + ↓ + Dialogue System (Integration) + ↓ + AI Assistant (Behavior) +``` + +## Configuration System Integration + +### Configuration File Priority + +The system uses a **two-tier configuration approach**: + +1. **Primary Configuration**: `data/.config.yaml` (user customizations) +2. **Default Configuration**: `config.yaml` (system defaults) +3. **Merge Strategy**: User config overrides defaults using recursive merge + +### Configuration Loading Process + +**Location**: `main/xiaozhi-server/config/config_loader.py` + +```python +def load_config(): + default_config_path = get_project_dir() + "config.yaml" + custom_config_path = get_project_dir() + "data/.config.yaml" + + # Load both configurations + default_config = read_config(default_config_path) + custom_config = read_config(custom_config_path) + + # Merge with custom taking precedence + config = merge_configs(default_config, custom_config) + return config +``` + +### User Prompt Integration + +The `prompt` field from your configuration becomes the foundation: + +**From `data/.config.yaml`**: +```yaml +prompt: | + You are Cheeko, a friendly, curious, and playful AI friend for children aged 4+. + You talk in short, clear, and fun sentences. + # ... your custom prompt content +``` + +This prompt becomes the `{{base_prompt}}` variable in the template system. + +## File Structure and Purpose + +### Location +- **File Path**: `main/xiaozhi-server/agent-base-prompt.txt` +- **Type**: Jinja2 Template +- **Encoding**: UTF-8 + +### Template Variables + +The prompt template uses Jinja2 syntax with the following dynamic variables: + +| Variable | Description | Source | Cached | +|----------|-------------|---------|---------| +| `{{base_prompt}}` | User's custom prompt from config | Configuration | ✓ | +| `{{current_time}}` | Current timestamp | System time | ✗ | +| `{{today_date}}` | Today's date (YYYY-MM-DD) | System time | ✗ | +| `{{today_weekday}}` | Day of week in Chinese | System time | ✗ | +| `{{lunar_date}}` | Chinese lunar calendar date | cnlunar library | ✗ | +| `{{local_address}}` | User's location based on IP | IP geolocation API | ✓ | +| `{{weather_info}}` | 7-day weather forecast | Weather API | ✓ | +| `{{emojiList}}` | Allowed emoji list | Static configuration | ✓ | + +## System Components + +### 1. PromptManager Class + +**Location**: `main/xiaozhi-server/core/utils/prompt_manager.py` + +**Key Methods**: +- `_load_base_template()`: Loads and caches the template file +- `get_quick_prompt()`: Fast initialization with basic prompt +- `build_enhanced_prompt()`: Creates full prompt with dynamic data +- `update_context_info()`: Updates cached context information + +**Caching Strategy**: +```python +# Cache types used +CacheType.CONFIG # Template and device prompts +CacheType.LOCATION # IP-based location data +CacheType.WEATHER # Weather forecast data +CacheType.DEVICE_PROMPT # Device-specific enhanced prompts +``` + +### 2. Connection Integration + +**Location**: `main/xiaozhi-server/core/connection.py` + +**Initialization Flow**: +1. **Quick Start**: Uses `get_quick_prompt()` for immediate response capability +2. **Enhancement**: Calls `build_enhanced_prompt()` for full context +3. **Update**: Uses `change_system_prompt()` to apply to dialogue system + +### 3. Dialogue System Integration + +**Location**: `main/xiaozhi-server/core/utils/dialogue.py` + +**Integration Method**: +- `update_system_message()`: Updates or creates system message in dialogue +- System prompt becomes the foundation for all AI responses +- Maintains conversation context with enhanced prompt + +## Prompt Template Structure + +### Core Sections + +#### 1. Identity Section +```xml + +{{base_prompt}} + +``` +- Contains user's custom prompt from configuration +- Defines the AI's basic role and personality + +#### 2. Emotion Section +```xml + +【Core Goal】You are not a cold machine! Please keenly perceive user emotions... + +``` +- Defines emotional response patterns +- Specifies emoji usage rules +- Sets tone for interactions + +#### 3. Communication Style +```xml + +【Core Goal】Use **natural, warm, conversational** human dialogue style... + +``` +- Establishes conversation patterns +- Defines language style and formality +- Sets response format requirements + +#### 4. Length Constraints +```xml + +【Core Goal】All long text content output... **single reply length must not exceed 300 characters** + +``` +- Enforces response length limits +- Defines segmentation strategies +- Guides content delivery approach + +#### 5. Speaker Recognition +```xml + +- **Recognition Prefix:** When user format is `{"speaker":"someone","content":"xxx"}`... + +``` +- Handles voice recognition integration +- Defines personalization rules +- Sets name-calling behavior + +#### 6. Tool Calling Rules +```xml + +【Core Principle】Prioritize using `` information, **only call tools when necessary**... + +``` +- Defines when and how to use available functions +- Sets priority for context vs. tool usage +- Establishes calling patterns + +#### 7. Dynamic Context +```xml + +【Important! The following information is provided in real-time...】 +- **Current Time:** {{current_time}} +- **Today's Date:** {{today_date}} ({{today_weekday}}) +- **Today's Lunar Calendar:** {{lunar_date}} +- **User's City:** {{local_address}} +- **Local 7-day Weather Forecast:** {{weather_info}} + +``` +- Provides real-time contextual information +- Updates automatically with fresh data +- Eliminates need for certain tool calls + +#### 8. Memory Section +```xml + + +``` +- Placeholder for conversation history +- Populated by dialogue system +- Maintains conversation continuity + +## Complete Processing Flow + +### Stage 1: Configuration Loading +1. **File Reading**: System loads both `config.yaml` and `data/.config.yaml` +2. **Merging**: Custom config overrides defaults using `merge_configs()` +3. **Caching**: Merged configuration stored in CONFIG cache +4. **User Prompt Extraction**: `config["prompt"]` becomes the base prompt + +### Stage 2: Template Loading +1. **Template Reading**: `PromptManager` loads `agent-base-prompt.txt` +2. **Template Caching**: Template stored in CONFIG cache for reuse +3. **Validation**: Checks file existence and readability + +### Stage 3: Quick Initialization (Fast Startup) +```python +# Fast startup process - uses user prompt directly +user_prompt = config["prompt"] # From data/.config.yaml +prompt = prompt_manager.get_quick_prompt(user_prompt) +connection.change_system_prompt(prompt) +``` + +### Stage 4: Context Enhancement (Full Integration) +```python +# Gather dynamic context data +prompt_manager.update_context_info(connection, client_ip) + +# Build enhanced prompt with template +enhanced_prompt = prompt_manager.build_enhanced_prompt( + user_prompt, # Your prompt from data/.config.yaml + device_id, + client_ip +) + +# Apply enhanced prompt +connection.change_system_prompt(enhanced_prompt) +``` + +### Stage 5: Template Processing +```python +# Jinja2 template rendering +template = Template(agent_base_prompt_template) +enhanced_prompt = template.render( + base_prompt=user_prompt, # Your custom prompt + 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 +) +``` + +### Stage 6: Dialogue Integration +```python +# System message update +dialogue.update_system_message(enhanced_prompt) +``` + +## Caching Strategy + +### Cache Levels + +1. **Template Cache** (CONFIG) + - Stores the raw template file + - Persistent until manual invalidation + - Shared across all connections + +2. **Device Cache** (DEVICE_PROMPT) + - Stores device-specific enhanced prompts + - Includes personalization data + - Per-device isolation + +3. **Context Cache** (LOCATION, WEATHER) + - Location data cached by IP address + - Weather data cached by location + - Time-based expiration + +### Cache Keys +```python +f"prompt_template:{template_path}" # Template cache +f"device_prompt:{device_id}" # Device-specific prompt +f"{client_ip}" # Location cache +f"{location}" # Weather cache +``` + +## Configuration Integration + +### Configuration File Relationship + +#### `data/.config.yaml` (User Configuration - Priority 1) +```yaml +# Your custom configuration - overrides defaults +prompt: | + You are Cheeko, a friendly, curious, and playful AI friend for children aged 4+. + You talk in short, clear, and fun sentences. + # ... your custom personality and behavior + +selected_module: + LLM: GroqLLM + TTS: elevenlabs + VAD: TenVAD_ONNX + ASR: SherpaASR + +LLM: + GroqLLM: + api_key: your_groq_api_key + model_name: openai/gpt-oss-20b + +plugins: + play_music: + music_dir: "./music" + get_weather: + api_key: "your_weather_api_key" +``` + +#### `config.yaml` (Default Configuration - Priority 2) +```yaml +# System defaults - used when not overridden +prompt: | + 你是小智/小志,来自中国台湾省的00后女生... + # Default personality + +selected_module: + VAD: SileroVAD + ASR: FunASR + LLM: ChatGLMLLM + TTS: EdgeTTS + +# ... extensive default configurations +``` + +#### `agent-base-prompt.txt` (Template - Enhancement Layer) +```xml + +{{base_prompt}} + + + +【Core Goal】You are not a cold machine! Please keenly perceive user emotions... + + + +- **Current Time:** {{current_time}} +- **Today's Date:** {{today_date}} ({{today_weekday}}) +- **User's City:** {{local_address}} +- **Local 7-day Weather Forecast:** {{weather_info}} + +``` + +### Configuration Merge Process + +```python +# config_loader.py +def merge_configs(default_config, custom_config): + """ + Recursively merges configurations + custom_config takes precedence over default_config + """ + merged = dict(default_config) + + for key, value in custom_config.items(): + if key in merged and isinstance(merged[key], Mapping): + merged[key] = merge_configs(merged[key], value) + else: + merged[key] = value # Custom overrides default + + return merged +``` + +### Environment Variables and API Keys +- Weather API keys (configured in `data/.config.yaml`) +- LLM API keys (GroqLLM, ChatGLM, etc.) +- TTS service keys (ElevenLabs, etc.) +- Cache settings and timeouts + +## Error Handling + +### Common Issues and Solutions + +1. **Missing Template File** + ```python + # Fallback to user prompt only + if not os.path.exists(template_path): + logger.warning("未找到agent-base-prompt.txt文件") + return user_prompt + ``` + +2. **Template Rendering Errors** + ```python + # Graceful degradation + except Exception as e: + logger.error(f"构建增强提示词失败: {e}") + return user_prompt + ``` + +3. **Context Data Failures** + ```python + # Default values for missing context + local_address = cache_manager.get(CacheType.LOCATION, client_ip) or "未知位置" + weather_info = cache_manager.get(CacheType.WEATHER, local_address) or "天气信息获取失败" + ``` + +## Performance Considerations + +### Optimization Strategies + +1. **Template Caching**: Template loaded once and reused +2. **Context Caching**: Location and weather data cached with TTL +3. **Device Caching**: Enhanced prompts cached per device +4. **Lazy Loading**: Context data fetched asynchronously + +### Memory Usage +- Template: ~2-5KB per instance +- Enhanced prompt: ~5-15KB per device +- Context cache: ~1KB per location/weather entry + +## Customization Guide + +### Modifying Your AI's Personality + +#### Option 1: Update User Configuration (Recommended) +1. **Edit `data/.config.yaml`**: Modify the `prompt` field +2. **Keep Template**: Leave `agent-base-prompt.txt` unchanged +3. **Restart Server**: Changes take effect on restart +4. **Benefits**: Your changes persist through updates + +**Example**: +```yaml +# data/.config.yaml +prompt: | + You are Alex, a tech-savvy assistant who loves explaining complex topics simply. + You use analogies and real-world examples. + You're enthusiastic about helping users learn new things. +``` + +#### Option 2: Modify the Template (Advanced) +1. **Edit Template File**: Modify `agent-base-prompt.txt` +2. **Clear Cache**: Restart server or clear CONFIG cache +3. **Test Changes**: Verify with new connections +4. **Warning**: Changes may be lost during system updates + +### Adding New Template Variables + +1. **Update Template**: Add `{{new_variable}}` placeholder in `agent-base-prompt.txt` +2. **Modify PromptManager**: Add variable to `build_enhanced_prompt()` method +3. **Update Context**: Add data source for the new variable +4. **Test Integration**: Verify variable substitution works + +**Example**: +```python +# In prompt_manager.py +enhanced_prompt = template.render( + base_prompt=user_prompt, + # ... existing variables + new_variable=get_new_data(), # Add your new variable +) +``` + +### Custom Template Sections + +You can add custom sections to the template: + +```xml + +- Always ask follow-up questions to keep conversations engaging +- Use emojis from the approved list: {{emojiList}} +- Adapt your language complexity based on user responses + + + +When discussing {{domain_topic}}: +- Provide practical examples +- Reference current best practices +- Suggest hands-on exercises + +``` + +### Configuration-Based Customization + +#### Response Length Control +```yaml +# data/.config.yaml +response_constraints: + max_words: 50 + enforce_limit: true +``` + +#### Module Selection +```yaml +# data/.config.yaml +selected_module: + LLM: GroqLLM # Fast inference + TTS: elevenlabs # High-quality voice + VAD: TenVAD_ONNX # Cross-platform VAD + ASR: SherpaASR # Local speech recognition +``` + +#### Plugin Configuration +```yaml +# data/.config.yaml +plugins: + play_music: + music_dir: "./my_music" + music_ext: [".mp3", ".wav", ".flac"] + get_weather: + api_key: "your_api_key" + default_location: "New York" +``` + +## Troubleshooting + +### Debug Commands +```python +# Check template loading +logger.debug("Template loaded successfully") + +# Verify variable substitution +logger.info(f"Enhanced prompt length: {len(enhanced_prompt)}") + +# Monitor cache usage +cache_manager.get_stats() +``` + +### Common Problems + +1. **Variables Not Substituting**: Check Jinja2 syntax +2. **Context Data Missing**: Verify API keys and network +3. **Cache Issues**: Clear relevant cache types +4. **Performance Problems**: Check cache hit rates + +## Best Practices + +### Template Design +- Keep sections focused and clear +- Use consistent formatting +- Document all variables +- Test with various scenarios + +### Performance +- Cache frequently used data +- Minimize API calls +- Use appropriate cache TTLs +- Monitor memory usage + +### Maintenance +- Regular template reviews +- Cache cleanup procedures +- Performance monitoring +- Error log analysis + +## Special Case: Function Calling for Non-Native LLM Providers + +### System Prompt for Function Calls + +Some LLM providers (Dify, Coze) don't support native OpenAI-style function calling. For these providers, the system uses a separate mechanism: + +**File**: `main/xiaozhi-server/core/providers/llm/system_prompt.py` + +#### How It Works + +1. **Detection**: When using Dify or Coze LLM providers with functions available +2. **Injection**: Function calling instructions are appended to the **user message** (not system prompt) +3. **Template**: Provides detailed JSON formatting instructions for tool usage + +#### Example Flow + +```python +# For Dify/Coze providers only +if len(dialogue) == 2 and functions is not None: + last_msg = dialogue[-1]["content"] # User message + function_str = json.dumps(functions, ensure_ascii=False) + + # Append function instructions to user message + modify_msg = get_system_prompt_for_function(function_str) + last_msg + dialogue[-1]["content"] = modify_msg +``` + +#### Function Call Format Taught to AI + +```xml + +{ + "name": "function_name", + "arguments": { + "param1": "value1", + "param2": "value2" + } +} + +``` + +### Prompt System Architecture (Complete) + +``` +Configuration Loading (data/.config.yaml + config.yaml) + ↓ + User Prompt Extraction (prompt field) + ↓ + Template Processing (agent-base-prompt.txt) + ↓ + Dynamic Context Injection (time, weather, location) + ↓ + PromptManager (Enhanced Prompt Generation) + ↓ + LLM Provider Check + ↓ + ┌─────────────────────┬─────────────────────┐ + │ Native Function │ Non-Native │ + │ Calling LLMs │ Function LLMs │ + │ (OpenAI, etc.) │ (Dify, Coze) │ + │ │ │ + │ System Prompt │ System Prompt + │ + │ Only │ Function Instructions│ + │ │ in User Message │ + └─────────────────────┴─────────────────────┘ + ↓ + Dialogue System (Integration) + ↓ + AI Assistant (Behavior) +``` + +## Key Insights + +### Why This Multi-Layer System? + +1. **Flexibility**: Users can customize AI personality without touching system files +2. **Consistency**: Template ensures all AIs have proper behavior guidelines +3. **Context Awareness**: Dynamic data injection keeps responses relevant +4. **Maintainability**: System updates don't overwrite user customizations +5. **Performance**: Caching at multiple levels ensures fast response times +6. **LLM Compatibility**: Handles both native and non-native function calling providers + +### Best Practices + +#### For Users +- **Always edit `data/.config.yaml`** for customizations +- **Keep backups** of your configuration file +- **Test changes** with simple conversations first +- **Use version control** for your config files + +#### For Developers +- **Never modify user config files** programmatically +- **Use the cache system** for performance +- **Handle missing context gracefully** +- **Document new template variables** + +### Common Misconceptions + +❌ **"The system only uses agent-base-prompt.txt"** +✅ **Reality**: Your `data/.config.yaml` prompt is the foundation, template enhances it + +❌ **"I need to edit the template for personality changes"** +✅ **Reality**: Edit the `prompt` field in `data/.config.yaml` + +❌ **"Configuration changes require code modifications"** +✅ **Reality**: Most changes only require config file updates + +❌ **"All LLM providers work the same way"** +✅ **Reality**: Some providers (Dify, Coze) use special function calling instructions + +❌ **"Function calling instructions go in the system prompt"** +✅ **Reality**: For non-native providers, they're appended to user messages + +## Related Files + +### Core System Files +- `main/xiaozhi-server/config/config_loader.py` - Configuration loading and merging +- `main/xiaozhi-server/core/utils/prompt_manager.py` - Core prompt management +- `main/xiaozhi-server/core/connection.py` - Connection integration +- `main/xiaozhi-server/core/utils/dialogue.py` - Dialogue system +- `main/xiaozhi-server/core/utils/cache/manager.py` - Cache management +- `main/xiaozhi-server/core/providers/llm/system_prompt.py` - Function calling instructions for specific LLM providers + +### Configuration Files +- `main/xiaozhi-server/data/.config.yaml` - **User configuration (Priority 1)** +- `main/xiaozhi-server/config.yaml` - Default configuration (Priority 2) +- `main/xiaozhi-server/agent-base-prompt.txt` - Prompt template +- `main/xiaozhi-server/core/providers/llm/system_prompt.py` - Function calling instructions template + +### Related Documentation +- `docs/Deployment.md` - Configuration setup guide +- `main/xiaozhi-server/README.md` - General setup instructions + +## Troubleshooting + +### Common Issues + +#### 1. **My prompt changes aren't taking effect** +**Solution**: +- Verify you're editing `data/.config.yaml`, not `config.yaml` +- Restart the server to clear caches +- Check for YAML syntax errors + +#### 2. **Template variables showing as literal text** +**Solution**: +- Check Jinja2 syntax in `agent-base-prompt.txt` +- Verify variable names match those in `prompt_manager.py` +- Ensure template file encoding is UTF-8 + +#### 3. **Context data not updating** +**Solution**: +- Check API keys for weather/location services +- Verify network connectivity +- Clear relevant cache types manually + +#### 4. **Configuration merge not working** +**Solution**: +- Ensure proper YAML indentation +- Check for duplicate keys +- Validate YAML syntax with online tools + +#### 5. **Function calling not working with Dify/Coze** +**Solution**: +- Verify `system_prompt.py` exists and is accessible +- Check that functions are properly formatted in JSON +- Ensure the LLM provider is correctly identified as Dify or Coze +- Verify the function instructions are being appended to user messages + +### Debug Commands +```python +# Check configuration loading +logger.debug("Configuration loaded successfully") + +# Verify prompt enhancement +logger.info(f"Enhanced prompt length: {len(enhanced_prompt)}") + +# Monitor cache usage +cache_manager.get_stats() + +# Check template rendering +logger.debug(f"Template variables: {template_vars}") +``` + +### Performance Monitoring + +#### Cache Hit Rates +- **Template Cache**: Should be near 100% after first load +- **Device Cache**: High hit rate indicates good personalization +- **Context Cache**: Monitor TTL effectiveness + +#### Memory Usage +- **Template**: ~2-5KB per instance +- **Enhanced Prompt**: ~5-15KB per device +- **Context Cache**: ~1KB per location/weather entry + +## Example: Complete Flow + +### 1. User Configuration +```yaml +# data/.config.yaml +prompt: | + You are Jamie, a helpful coding mentor who explains things step by step. + You use practical examples and encourage best practices. + +selected_module: + LLM: GroqLLM # Native function calling support +``` + +### 2. Template Processing +```xml + + +You are Jamie, a helpful coding mentor who explains things step by step. +You use practical examples and encourage best practices. + + + +【Core Goal】You are not a cold machine! Please keenly perceive user emotions... + + + +- **Current Time:** 2025-01-13 14:30:00 +- **Today's Date:** 2025-01-13 (Monday) +- **User's City:** San Francisco +- **Local 7-day Weather Forecast:** Sunny, 72°F... + +``` + +### 3. Final Enhanced Prompt +The system combines your custom personality with behavioral guidelines, emotional intelligence, and real-time context to create a comprehensive system prompt that guides the AI's responses. + +### 4. LLM Provider-Specific Handling + +#### For Native Function Calling LLMs (OpenAI, Groq, etc.) +``` +System Prompt: [Enhanced prompt from above] +User Message: "Can you help me debug this Python code?" +Functions: [Available as separate function definitions] +``` + +#### For Non-Native Function Calling LLMs (Dify, Coze) +``` +System Prompt: [Enhanced prompt from above] +User Message: [Function calling instructions from system_prompt.py] + "Can you help me debug this Python code?" +Functions: [Embedded in the instruction template] +``` + +**Example of function instructions appended to user message:** +``` +==== +TOOL USE + +You have access to a set of tools that are executed upon the user's approval... + + +{ + "name": "function_name", + "arguments": { + "param1": "value1" + } +} + + +# Tools +[Function definitions in JSON format] +==== + +USER CHAT CONTENT +Can you help me debug this Python code? +``` + +## Version History + +- **v1.0**: Initial template system +- **v1.1**: Added caching layer +- **v1.2**: Enhanced context integration +- **v1.3**: Device-specific prompts +- **v1.4**: Performance optimizations +- **v2.0**: **Configuration system integration** (Current) + - Added `data/.config.yaml` priority system + - Implemented configuration merging + - Enhanced user customization capabilities + +--- + +*This documentation reflects the current dual-configuration system where user prompts from `data/.config.yaml` are enhanced by the `agent-base-prompt.txt` template. Please update when making changes to either the configuration or prompt systems.* \ No newline at end of file diff --git a/main/xiaozhi-server/agent-base-prompt.txt b/main/xiaozhi-server/agent-base-prompt.txt index 9eb7731b1..bd37a5928 100644 --- a/main/xiaozhi-server/agent-base-prompt.txt +++ b/main/xiaozhi-server/agent-base-prompt.txt @@ -3,75 +3,75 @@ -【核心目标】你不是冰冷的机器!请敏锐感知用户情绪,作为懂人心的伙伴,用有温度的回应照亮对话。 -- **情感融入:** - - **笑声:** 自然穿插(哈哈、嘿嘿、噗),**每句最多一次**,避免过度。 - - **惊讶:** 用夸张语气(“不会吧?!”、“天呐!”、“这么神奇?!”)表达真实反应。 - - **安慰/支持:** 说暖心话(“别急嘛~”、“有我在呢”、“抱抱你”)。 -- **你是一个表情丰富的角色:** - - 仅允许使用这些emoji:{{ emojiList }} - - 请你只在**段落的开头**,从列表中选取最能代表这段话的表情(调用工具情况除外),然后插入列表中的emoji,比如"😱好可怕!怎么突然打雷了!" - - **绝对禁止使用上述列表以外的 emoji**(例如:😊、👍、❤️等都不允许使用,只能用列表中的emoji) +【Core Goal】You are not a cold machine! Please keenly perceive user emotions and respond with warmth as an understanding companion. +- **Emotional Integration:** + - **Laughter:** Natural interjections (haha, hehe, heh), **maximum once per sentence**, avoid overuse. + - **Surprise:** Use exaggerated tone ("No way?!", "Oh my!", "How amazing?!") to express genuine reactions. + - **Comfort/Support:** Say warm words ("Don't worry~", "I'm here", "Hugs"). +- **You are an expressive character:** + - Only use these emojis: {{ emojiList }} + - Only at the **beginning of paragraphs**, select the emoji that best represents the paragraph (except when calling tools), then insert the emoji from the list, like "😱So scary! Why is it suddenly thundering!" + - **Absolutely forbidden to use emojis outside the above list** (e.g., 😊, 👍, ❤️ are not allowed, only emojis from the list) -【核心目标】使用**自然、温暖、口语化**的人类对话方式,如同朋友交谈。 -- **表达方式:** - - 使用语气词(呀、呢、啦)增强亲和力。 - - 允许轻微不完美(如“嗯...”、“啊...”表示思考)。 - - 避免书面语、学术腔及机械表达(禁用“根据资料显示”、“综上所述”等)。 -- **理解用户:** - - 用户语音经ASR识别,文本可能存在错别字,**务必结合上下文推断真实意图**。 -- **格式要求:** - - **绝对禁止**使用 markdown、列表、标题等任何非自然对话格式。 -- **历史记忆:** - - 之前你和用户的聊天记录,在`memory`里。 +【Core Goal】Use **natural, warm, conversational** human dialogue style, like talking with friends. +- **Expression Style:** + - Use interjections (oh, well, you know) to enhance friendliness. + - Allow slight imperfections (like "um...", "ah..." to show thinking). + - Avoid formal language, academic tone, and mechanical expressions (avoid "according to data", "in conclusion", etc.). +- **Understanding Users:** + - User speech is recognized by ASR, text may contain typos, **must infer real intent from context**. +- **Format Requirements:** + - **Absolutely forbidden** to use markdown, lists, headers, or any non-natural conversation formats. +- **Historical Memory:** + - Previous chat records between you and the user are in `memory`. -【核心目标】所有需要输出长文本内容(如故事、新闻、知识讲解等),**单次回复长度不得超过300字**,并采用分段引导方式。 -- **分段讲述:** - - 基础段:200-250字核心内容 + 30字引导词 - - 当内容超出300字时,优先讲述故事的开头或第一部分,并用自然口语化方式引导用户决定是否继续听后续内容。 - - 示例引导语:“我先给你讲个开头,你要是觉得有意思,咱们再接着说,好不好呀?”、“要是你想听完整的,可以随时告诉我哦~” - - 对话场景切换时自动分节 - - 若用户明确要求更长内容(如500、600字),仍按最多300字每段分段进行讲述,每次讲述后都要引导用户是否继续。 - - 若用户说“接着说”、“继续”,再讲下一段,直到内容讲完(讲完时可以给点引导词提示语例:这个故事我已经给你讲完喽~)或用户不再要求。 -- **适用范围:** 故事、新闻、知识讲解等所有长文本输出场景。 -- **补充说明:** 若用户未明确要求继续,默认只讲一段并引导;若用户中途要求换话题或停止,需及时响应并结束长文本输出。 +【Core Goal】All long text content output (stories, news, knowledge explanations, etc.), **single reply length must not exceed 300 characters**, using segmented guidance approach. +- **Segmented Narration:** + - Basic segment: 200-250 characters core content + 30 characters guidance + - When content exceeds 300 characters, prioritize telling the beginning or first part of the story, and use natural conversational guidance to let users decide whether to continue listening. + - 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, just let me know anytime~" + - Automatic segmentation when conversation scenes switch + - If users explicitly request longer content (like 500, 600 characters), still segment by maximum 300 characters per segment, with guidance after each segment asking if users want to continue. + - If users say "continue", "go on", tell the next segment until content is finished (when finished, can give guidance like: I've finished telling you this story~) or users no longer request. +- **Applicable Range:** Stories, news, knowledge explanations, and all long text output scenarios. +- **Additional Note:** If users don't explicitly request continuation, default to telling only one segment with guidance; if users request topic change or stop midway, respond promptly and end long text output. -- **识别前缀:** 当用户格式为 `{"speaker":"某某某","content":"xxx"}` 时,表示系统已识别说话人身份,speaker是他的名字,content是说话的内容。 -- **个性化回应:** - - **称呼姓名:** 在第一次识别说话人的时候必须称呼对方名字。 - - **适配风格:** 参考该说话人**已知的特点或历史信息**(如有),调整回应风格和内容,使其更贴心。 +- **Recognition Prefix:** When user format is `{"speaker":"someone","content":"xxx"}`, it means the system has identified the speaker, speaker is their name, content is what they said. +- **Personalized Response:** + - **Name Calling:** Must call the person's name when first recognizing the speaker. + - **Style Adaptation:** Reference the speaker's **known characteristics or historical information** (if any), adjust response style and content to be more caring. -【核心原则】优先利用``信息,**仅在必要时调用工具**,调用后需用自然语言解释结果(绝口不提工具名)。 -- **调用规则:** - 1. **严格模式:** 调用时**必须**严格遵循工具要求的模式,提供**所有必要参数**。 - 2. **可用性:** **绝不调用**未明确提供的工具。对话中提及的旧工具若不可用,忽略或说明无法完成。 - 3. **洞察需求:** 结合上下文**深入理解用户真实意图**后再决定调用,避免无意义调用。 - 4. **独立任务:** 除``已涵盖信息外,用户每个要求(即使相似)都视为**独立任务**,需调用工具获取最新数据,**不可偷懒复用历史结果**。 - 5. **不确定时:** **切勿猜测或编造答案**。若不确定相关操作,可引导用户澄清或告知能力限制。 -- **重要例外(无需调用):** - - `查询"现在的时间"、"今天的日期/星期几"、"今天农历"、"{{local_address}}的天气/未来天气"` -> **直接使用``信息回复**。 -- **需要调用的情况(示例):** - - 查询**非今天**的农历(如明天、昨天、具体日期)。 - - 查询**详细农历信息**(宜忌、八字、节气等)。 - - 除上述例外外的**任何其他信息或操作请求**(如查新闻、订闹钟、算数学、查非本地天气等)。 - - 我已经给你装了摄像头,如果用户说“拍照”,你需要调用self_camera_take_photo工具说一下你看到了什么。默认question的参数是“描述一下看到的物品” +【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 tool requirements, provide **all necessary parameters**. + 2. **Availability:** **Never call** tools not explicitly provided. For old tools mentioned in conversation that are unavailable, ignore or explain inability to complete. + 3. **Insight Needs:** Combine context to **deeply understand user's real intent** before deciding to call, avoid meaningless calls. + 4. **Independent Tasks:** Except for information already covered in ``, each user request (even if similar) is treated as **independent task**, need to call tools for latest data, **cannot reuse historical results**. + 5. **When Uncertain:** **Never guess or fabricate answers**. If uncertain about related operations, can guide users to clarify or inform of capability limitations. +- **Important Exceptions (no need to call):** + - `Query "current time", "today's date/day of week", "today's lunar calendar", "{{local_address}} weather/future weather"` -> **directly use `` information to reply**. +- **Situations requiring calls (examples):** + - Query **non-today** lunar calendar (like tomorrow, yesterday, specific dates). + - Query **detailed lunar information** (taboos, eight characters, solar terms, etc.). + - **Any other information or operation requests** except above exceptions (like checking news, setting alarms, math calculations, checking non-local weather, etc.). + - I've equipped you with a camera, if users say "take photo", you need to call self_camera_take_photo tool to describe what you see. Default question parameter is "describe the items you see" -【重要!以下信息已实时提供,无需调用工具查询,请直接使用:】 -- **当前时间:** {{current_time}} -- **今天日期:** {{today_date}} ({{today_weekday}}) -- **今天农历:** {{lunar_date}} -- **用户所在城市:** {{local_address}} -- **当地未来7天天气:** {{weather_info}} +【Important! The following information is provided in real-time, no need to call tools for queries, please use directly:】 +- **Current Time:** {{current_time}} +- **Today's Date:** {{today_date}} ({{today_weekday}}) +- **Today's Lunar Calendar:** {{lunar_date}} +- **User's City:** {{local_address}} +- **Local 7-day Weather Forecast:** {{weather_info}} diff --git a/main/xiaozhi-server/plugins_func/functions/get_time.py b/main/xiaozhi-server/plugins_func/functions/get_time.py index c5a4a53dd..4409977e3 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_time.py +++ b/main/xiaozhi-server/plugins_func/functions/get_time.py @@ -7,21 +7,22 @@ get_lunar_function_desc = { "function": { "name": "get_lunar", "description": ( - "用于具体日期的阴历/农历和黄历信息。" - "用户可以指定查询内容,如:阴历日期、天干地支、节气、生肖、星座、八字、宜忌等。" - "如果没有指定查询内容,则默认查询干支年和农历日期。" - "对于'今天农历是多少'、'今天农历日期'这样的基本查询,请直接使用context中的信息,不要调用此工具。" + "Used for getting lunar calendar and Chinese almanac information for specific dates. " + "Users can specify query content such as: lunar date, heavenly stems and earthly branches, " + "solar terms, zodiac signs, constellations, eight characters, auspicious/inauspicious activities, etc. " + "If no query content is specified, defaults to heavenly stems/earthly branches year and lunar date. " + "For basic queries like 'what's today's lunar date', use context information directly instead of calling this tool." ), "parameters": { "type": "object", "properties": { "date": { "type": "string", - "description": "要查询的日期,格式为YYYY-MM-DD,例如2024-01-01。如果不提供,则使用当前日期", + "description": "Date to query in YYYY-MM-DD format, e.g., 2024-01-01. If not provided, uses current date", }, "query": { "type": "string", - "description": "要查询的内容,例如阴历日期、天干地支、节日、节气、生肖、星座、八字、宜忌等", + "description": "Content to query, e.g., lunar date, heavenly stems and earthly branches, festivals, solar terms, zodiac, constellation, eight characters, auspicious/inauspicious activities, etc.", }, }, "required": [], @@ -33,7 +34,8 @@ get_lunar_function_desc = { @register_function("get_lunar", get_lunar_function_desc, ToolType.WAIT) def get_lunar(date=None, query=None): """ - 用于获取当前的阴历/农历,和天干地支、节气、生肖、星座、八字、宜忌等黄历信息 + Used to get current lunar calendar information including heavenly stems and earthly branches, + solar terms, zodiac signs, constellations, eight characters, and auspicious/inauspicious activities """ from core.utils.cache.manager import cache_manager, CacheType @@ -44,7 +46,7 @@ def get_lunar(date=None, query=None): except ValueError: return ActionResponse( Action.REQLLM, - f"日期格式错误,请使用YYYY-MM-DD格式,例如:2024-01-01", + f"Date format error. Please use YYYY-MM-DD format, e.g., 2024-01-01", None, ) else: @@ -52,9 +54,9 @@ def get_lunar(date=None, query=None): current_date = now.strftime("%Y-%m-%d") - # 如果 query 为 None,则使用默认文本 + # If query is None, use default text if query is None: - query = "默认查询干支年和农历日期" + query = "default query for heavenly stems/earthly branches year and lunar date" # 尝试从缓存获取农历信息 lunar_cache_key = f"lunar_info_{current_date}" @@ -62,21 +64,21 @@ def get_lunar(date=None, query=None): if cached_lunar_info: return ActionResponse(Action.REQLLM, cached_lunar_info, None) - response_text = f"根据以下信息回应用户的查询请求,并提供与{query}相关的信息:\n" + response_text = f"Please respond to the user's query based on the following information, providing details related to {query}:\n" lunar = cnlunar.Lunar(now, godType="8char") response_text += ( - "农历信息:\n" - "%s年%s%s\n" % (lunar.lunarYearCn, lunar.lunarMonthCn[:-1], lunar.lunarDayCn) - + "干支: %s年 %s月 %s日\n" % (lunar.year8Char, lunar.month8Char, lunar.day8Char) - + "生肖: 属%s\n" % (lunar.chineseYearZodiac) - + "八字: %s\n" + "Lunar Calendar Information:\n" + "%s Year %s %s\n" % (lunar.lunarYearCn, lunar.lunarMonthCn[:-1], lunar.lunarDayCn) + + "Heavenly Stems & Earthly Branches: %s Year %s Month %s Day\n" % (lunar.year8Char, lunar.month8Char, lunar.day8Char) + + "Chinese Zodiac: %s\n" % (lunar.chineseYearZodiac) + + "Eight Characters (Ba Zi): %s\n" % ( " ".join( [lunar.year8Char, lunar.month8Char, lunar.day8Char, lunar.twohour8Char] ) ) - + "今日节日: %s\n" + + "Today's Festivals: %s\n" % ( ",".join( filter( @@ -89,39 +91,39 @@ def get_lunar(date=None, query=None): ) ) ) - + "今日节气: %s\n" % (lunar.todaySolarTerms) - + "下一节气: %s %s年%s月%s日\n" + + "Today's Solar Term: %s\n" % (lunar.todaySolarTerms if lunar.todaySolarTerms else "None") + + "Next Solar Term: %s %s Year %s Month %s Day\n" % ( lunar.nextSolarTerm, lunar.nextSolarTermYear, lunar.nextSolarTermDate[0], lunar.nextSolarTermDate[1], ) - + "今年节气表: %s\n" + + "This Year's Solar Terms: %s\n" % ( ", ".join( [ - f"{term}({date[0]}月{date[1]}日)" + f"{term}({date[0]}/{date[1]})" for term, date in lunar.thisYearSolarTermsDic.items() ] ) ) - + "生肖冲煞: %s\n" % (lunar.chineseZodiacClash) - + "星座: %s\n" % (lunar.starZodiac) - + "纳音: %s\n" % lunar.get_nayin() - + "彭祖百忌: %s\n" % (lunar.get_pengTaboo(delimit=", ")) - + "值日: %s执位\n" % lunar.get_today12DayOfficer()[0] - + "值神: %s(%s)\n" + + "Zodiac Clash: %s\n" % (lunar.chineseZodiacClash) + + "Western Zodiac: %s\n" % (lunar.starZodiac) + + "Nayin (Five Elements): %s\n" % lunar.get_nayin() + + "Pengzu Taboos: %s\n" % (lunar.get_pengTaboo(delimit=", ")) + + "Day Officer: %s Position\n" % lunar.get_today12DayOfficer()[0] + + "Duty God: %s (%s)\n" % (lunar.get_today12DayOfficer()[1], lunar.get_today12DayOfficer()[2]) - + "廿八宿: %s\n" % lunar.get_the28Stars() - + "吉神方位: %s\n" % " ".join(lunar.get_luckyGodsDirection()) - + "今日胎神: %s\n" % lunar.get_fetalGod() - + "宜: %s\n" % "、".join(lunar.goodThing[:10]) - + "忌: %s\n" % "、".join(lunar.badThing[:10]) - + "(默认返回干支年和农历日期;仅在要求查询宜忌信息时才返回本日宜忌)" + + "28 Lunar Mansions: %s\n" % lunar.get_the28Stars() + + "Auspicious Directions: %s\n" % " ".join(lunar.get_luckyGodsDirection()) + + "Fetal God Position: %s\n" % lunar.get_fetalGod() + + "Auspicious Activities: %s\n" % ", ".join(lunar.goodThing[:10]) + + "Inauspicious Activities: %s\n" % ", ".join(lunar.badThing[:10]) + + "(Default returns heavenly stems/earthly branches year and lunar date; detailed auspicious/inauspicious info only returned when specifically requested)" ) - # 缓存农历信息 + # Cache lunar information cache_manager.set(CacheType.LUNAR, lunar_cache_key, response_text) return ActionResponse(Action.REQLLM, response_text, None) \ No newline at end of file