mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-27 04:49:47 +01:00
fix(westernization): runtime English surface, voiceprint truth, CI gates
Server runtime: - translate model-visible strings: direct_answer tool schema, web_search tool desc/errors/results, call_device tool desc/replies, hass_state desc/report strings; they were Chinese text fed to LLMs and devices - replace Chinese pconline geocoder with ip-api.com (English city names) - prompt_manager: drop dead Chinese WEEKDAY_MAP, stop forcing lang=zh_CN for weather, English fallback location - delete orphan alibl_endpoint.py (no importers after AliBL removal) and dead initialize_voiceprint() calling a nonexistent ASR hook - translate mcp_server_settings.json descriptors - test_current_time: assert English weekday/date behavior (upstream test still expected Chinese weekdays) Docs/branding: - README and docs/guides/voiceprint.md: voiceprint IS implemented via the HTTP VoiceprintProvider; document the real protocol (health/identify) and privacy notes instead of falsely claiming the feature is missing - issue templates: English Ops: - Dockerfile-server-base: drop Aliyun PyPI mirror from published image - LICENSE: keep xinnan-tech copyright notice alongside downstream (MIT) - CI: run westernization_audit as a gate; make smoke test failure fatal - westernization.md: point python verification at the real pytest layout
This commit is contained in:
parent
cfe3da5c7b
commit
feb6edb47f
21 changed files with 228 additions and 364 deletions
41
.github/ISSUE_TEMPLATE/bug_report.md
vendored
41
.github/ISSUE_TEMPLATE/bug_report.md
vendored
|
|
@ -1,32 +1,27 @@
|
||||||
---
|
---
|
||||||
name: Bug 报告(Bug Report)
|
name: Bug Report
|
||||||
about: 反馈项目中的缺陷或问题
|
about: Report a defect or problem in the project
|
||||||
title: "[Bug] 简短描述问题"
|
title: "[Bug] Short description of the problem"
|
||||||
labels: bug
|
labels: bug
|
||||||
assignees: ''
|
assignees: ''
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🐛 问题描述
|
## 🐛 Problem Description
|
||||||
<!-- 清晰简洁地描述问题是什么 -->
|
<!-- Clear and concise description of what the problem is -->
|
||||||
|
|
||||||
## 🖥️ 环境信息
|
## 🖥️ Environment
|
||||||
- 部署方式: 全模块部署 还是 单Server部署
|
- Deployment mode: full modules (manager + server) or server-only
|
||||||
- 版本号: 例如 0.3.x
|
- Version: e.g. 0.9.7
|
||||||
|
|
||||||
## 🔍 告诉我们,应该怎么复现这个问题
|
## 🔍 Steps to Reproduce
|
||||||
<!-- 这个很重要,方便我们快速定位 -->
|
<!-- This matters a lot; it helps us locate the problem quickly -->
|
||||||
1. 打开 '...'
|
1. Go to '...'
|
||||||
2. 点击 '...'
|
2. Click '...'
|
||||||
3. 滚动到 '...'
|
3. Scroll to '...'
|
||||||
4. 看到错误
|
4. See error
|
||||||
|
|
||||||
## 🤔 你原本希望是怎么样的
|
## 🤔 Expected Behavior
|
||||||
<!-- 简要描述预期的正确行为 -->
|
<!-- Briefly describe what you expected to happen -->
|
||||||
|
|
||||||
## 😯 提供一些截图
|
## 📋 Logs / Screenshots
|
||||||
<!-- 如果适用,添加问题的截图 -->
|
<!-- Paste relevant server or browser logs; screenshots welcome -->
|
||||||
1. 比如日志截图,越多越好
|
|
||||||
2. 比如界面反应
|
|
||||||
|
|
||||||
## 📋 其他信息
|
|
||||||
<!-- 在此添加关于此问题的任何其他上下文信息 -->
|
|
||||||
|
|
|
||||||
22
.github/ISSUE_TEMPLATE/code_improvement.md
vendored
22
.github/ISSUE_TEMPLATE/code_improvement.md
vendored
|
|
@ -1,19 +1,19 @@
|
||||||
---
|
---
|
||||||
name: 代码优化建议(Code Improvement)
|
name: Code Improvement
|
||||||
about: 提出对现有代码的优化或改进建议
|
about: Propose an optimization or improvement to existing code
|
||||||
title: "[Improvement] 简短描述改进内容"
|
title: "[Improvement] Short description of the improvement"
|
||||||
labels: refactor
|
labels: refactor
|
||||||
assignees: ''
|
assignees: ''
|
||||||
---
|
---
|
||||||
|
|
||||||
## 💡 改进描述
|
## 💡 Improvement Description
|
||||||
<!-- 描述需要改进的代码部分以及存在的问题 -->
|
<!-- Describe the code area that needs improvement and the problem with it -->
|
||||||
|
|
||||||
## 🌟 改进建议
|
## 🌟 Proposed Improvement
|
||||||
<!-- 提出具体的改进方案或思路 -->
|
<!-- Describe the concrete improvement plan or idea -->
|
||||||
|
|
||||||
## 🛠️ 相关代码
|
## 🛠️ Related Code
|
||||||
<!-- 如果可能,提供相关代码片段或链接 -->
|
<!-- If possible, provide code snippets or links -->
|
||||||
|
|
||||||
## 📋 其他信息
|
## 📋 Additional Context
|
||||||
<!-- 在此添加任何其他相关信息 -->
|
<!-- Add any other relevant information here -->
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,16 @@
|
||||||
---
|
---
|
||||||
name: 文档改进建议(Documentation Improvement)
|
name: Documentation Improvement
|
||||||
about: 提出对项目文档的改进或补充建议
|
about: Propose improvements or additions to the project documentation
|
||||||
title: "[Docs] 简短描述改进内容"
|
title: "[Docs] Short description of the improvement"
|
||||||
labels: documentation
|
labels: documentation
|
||||||
assignees: ''
|
assignees: ''
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📚 改进描述
|
## 📚 Improvement Description
|
||||||
<!-- 描述需要改进的文档部分以及存在的问题 -->
|
<!-- Describe the documentation section that needs improvement and why -->
|
||||||
|
|
||||||
## ✨ 改进建议
|
## ✨ Proposed Improvement
|
||||||
<!-- 提出具体的改进方案或内容 -->
|
<!-- Describe the concrete improvement or replacement content -->
|
||||||
|
|
||||||
## 📋 其他信息
|
## 📋 Additional Context
|
||||||
<!-- 在此添加任何其他相关信息 -->
|
<!-- Add any other relevant information here -->
|
||||||
|
|
|
||||||
22
.github/ISSUE_TEMPLATE/feature_request.md
vendored
22
.github/ISSUE_TEMPLATE/feature_request.md
vendored
|
|
@ -1,19 +1,19 @@
|
||||||
---
|
---
|
||||||
name: 功能请求(Feature Request)
|
name: Feature Request
|
||||||
about: 提出新的功能或改进建议
|
about: Propose a new feature or improvement
|
||||||
title: "[Feature] 简短描述功能"
|
title: "[Feature] Short description of the feature"
|
||||||
labels: enhancement
|
labels: enhancement
|
||||||
assignees: ''
|
assignees: ''
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🚀 需求描述
|
## 🚀 Feature Description
|
||||||
<!-- 清晰简洁地描述你希望发生什么 -->
|
<!-- Clear and concise description of what you want to happen -->
|
||||||
|
|
||||||
## 🎯 解决方案
|
## 🎯 Proposed Solution
|
||||||
<!-- 描述你认为可行的解决方案或实现方式 -->
|
<!-- Describe the solution or implementation approach you have in mind -->
|
||||||
|
|
||||||
## 📝 备选方案
|
## 📝 Alternatives Considered
|
||||||
<!-- 描述你考虑过的替代方案或功能 -->
|
<!-- Describe alternative solutions or features you considered -->
|
||||||
|
|
||||||
## 📋 其他信息
|
## 📋 Additional Context
|
||||||
<!-- 在此添加关于需求的任何其他上下文信息 -->
|
<!-- Add any other context or screenshots about the feature request here -->
|
||||||
|
|
|
||||||
15
.github/workflows/test.yml
vendored
15
.github/workflows/test.yml
vendored
|
|
@ -10,6 +10,14 @@ concurrency:
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
westernization-audit:
|
||||||
|
name: Westernization audit
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Run westernization audit
|
||||||
|
run: bash scripts/westernization_audit.sh
|
||||||
|
|
||||||
python:
|
python:
|
||||||
name: Python (xiaozhi-server)
|
name: Python (xiaozhi-server)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
@ -28,12 +36,7 @@ jobs:
|
||||||
- name: Run smoke test
|
- name: Run smoke test
|
||||||
working-directory: main/xiaozhi-server
|
working-directory: main/xiaozhi-server
|
||||||
run: |
|
run: |
|
||||||
if [ -f tests/test_smoke.py ]; then
|
pytest tests/test_smoke.py -x -q
|
||||||
pytest tests/test_smoke.py -x -q
|
|
||||||
else
|
|
||||||
echo "::warning::Slice 2 not done yet — tests/test_smoke.py missing"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
java:
|
java:
|
||||||
name: Java (manager-api)
|
name: Java (manager-api)
|
||||||
|
|
|
||||||
|
|
@ -12,10 +12,8 @@ RUN apt-get update && \
|
||||||
apt-get clean && \
|
apt-get clean && \
|
||||||
rm -rf /var/lib/apt/lists/*
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# Pip mirror and network resilience (same mirror family as upstream product)
|
# Pip network resilience (default PyPI index)
|
||||||
RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \
|
RUN pip config set global.timeout 120 && \
|
||||||
pip config set global.trusted-host mirrors.aliyun.com && \
|
|
||||||
pip config set global.timeout 120 && \
|
|
||||||
pip config set install.retries 5
|
pip config set install.retries 5
|
||||||
|
|
||||||
ENV LANG=en_US.UTF-8 \
|
ENV LANG=en_US.UTF-8 \
|
||||||
|
|
|
||||||
3
LICENSE
3
LICENSE
|
|
@ -1,6 +1,7 @@
|
||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2025 lapy
|
Copyright (c) 2025 xinnan-tech (original project: xinnan-tech/xiaozhi-esp32-server)
|
||||||
|
Copyright (c) 2025 lapy (westernized adaptations)
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
|
|
||||||
|
|
@ -215,7 +215,7 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
||||||
|
|
||||||
| Usage Method | Supported Platforms | Free Platforms |
|
| Usage Method | Supported Platforms | Free Platforms |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Local use | 3D-Speaker | 3D-Speaker |
|
| External HTTP service | Any voiceprint API compatible with the built-in `VoiceprintProvider` protocol (see [guide](./docs/guides/voiceprint.md)) | Self-hosted services |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -185,7 +185,6 @@ Identify users by their voice patterns.
|
||||||
```yaml
|
```yaml
|
||||||
# Voiceprint configuration
|
# Voiceprint configuration
|
||||||
voiceprint:
|
voiceprint:
|
||||||
enabled: true
|
|
||||||
url: http://192.168.1.100:8005/voiceprint/health?key=abcd
|
url: http://192.168.1.100:8005/voiceprint/health?key=abcd
|
||||||
speakers:
|
speakers:
|
||||||
- "user1,John,John is a software engineer"
|
- "user1,John,John is a software engineer"
|
||||||
|
|
@ -193,6 +192,9 @@ voiceprint:
|
||||||
- "user3,Bob,Bob is a student"
|
- "user3,Bob,Bob is a student"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
See [Voiceprint Recognition](../guides/voiceprint.md) for the service
|
||||||
|
protocol and privacy notes.
|
||||||
|
|
||||||
#### **Voice Commands**
|
#### **Voice Commands**
|
||||||
- "Do you know who I am?"
|
- "Do you know who I am?"
|
||||||
- "Register my voice"
|
- "Register my voice"
|
||||||
|
|
|
||||||
|
|
@ -1,149 +1,78 @@
|
||||||
# 🎤 Voiceprint Recognition
|
# 🎤 Voiceprint Recognition
|
||||||
|
|
||||||
**⚠️ Important Notice: Voiceprint recognition is not currently implemented in the English version of Xiaozhi ESP32 Server.**
|
Voiceprint recognition is **implemented** in this build through the built-in
|
||||||
|
`VoiceprintProvider` (`main/xiaozhi-server/core/utils/voiceprint_provider.py`).
|
||||||
|
It runs in parallel with ASR: each audio segment is sent both to ASR and to an
|
||||||
|
external voiceprint HTTP service, and the identified speaker is injected into
|
||||||
|
the LLM context for personalized responses.
|
||||||
|
|
||||||
|
> Note: the server does **not** ship a voiceprint model. You must run any
|
||||||
|
> voiceprint service that speaks the HTTP protocol below. The community
|
||||||
|
> [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) project is
|
||||||
|
> one compatible implementation (it uses ModelScope's 3D-Speaker models), but
|
||||||
|
> any service exposing the same endpoints and key scheme works.
|
||||||
|
|
||||||
## 🎯 What is Voiceprint Recognition?
|
## 🎯 What is Voiceprint Recognition?
|
||||||
|
|
||||||
Voiceprint recognition is a biometric technology that identifies users by their unique voice characteristics. It allows Xiaozhi to:
|
Voiceprint recognition is a biometric technology that identifies users by their
|
||||||
|
unique voice characteristics. It allows Xiaozhi to:
|
||||||
|
|
||||||
- **Identify users** by their voice patterns
|
- **Identify users** by their voice patterns
|
||||||
- **Provide personalized responses** based on who is speaking
|
- **Provide personalized responses** based on who is speaking
|
||||||
- **Enable access control** through voice authentication
|
- **Enable access control** through voice authentication
|
||||||
- **Support multi-user environments** with different user profiles
|
- **Support multi-user environments** with different user profiles
|
||||||
|
|
||||||
## 🚧 Current Status
|
## ⚙️ Configuration
|
||||||
|
|
||||||
The voiceprint recognition feature is **not available** in the current English version of Xiaozhi ESP32 Server. This feature was part of the original Chinese implementation but has not been ported to the Western version.
|
Enable it in `config.yaml` (single-module) or via the control console:
|
||||||
|
|
||||||
## 🔗 Original Implementation
|
```yaml
|
||||||
|
voiceprint:
|
||||||
|
# Voiceprint service address with your API key
|
||||||
|
url: http://192.168.1.100:8005/voiceprint/health?key=abcd
|
||||||
|
# Speakers: speaker_id,name,description
|
||||||
|
speakers:
|
||||||
|
- "test1,John,John is a programmer"
|
||||||
|
- "test2,Jane,Jane is a product manager"
|
||||||
|
# Optional: identification similarity threshold (default 0.4)
|
||||||
|
similarity_threshold: 0.4
|
||||||
|
```
|
||||||
|
|
||||||
For users who need voiceprint recognition functionality, please refer to the **original Chinese implementation**:
|
The service URL is parsed for a `key` query parameter, which is sent as the
|
||||||
|
service's API key. If `url` or `speakers` is missing, voiceprint recognition
|
||||||
|
stays disabled and a warning is logged.
|
||||||
|
|
||||||
### **Original Documentation**
|
## 🛠️ Service Protocol
|
||||||
- **Chinese Documentation**: [Voiceprint Integration Guide](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/voiceprint-integration.md)
|
|
||||||
- **Original Repository**: [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server)
|
|
||||||
|
|
||||||
### **Original Voiceprint Service**
|
The built-in provider expects an HTTP service exposing:
|
||||||
- **Voiceprint API**: [xinnan-tech/voiceprint-api](https://github.com/xinnan-tech/voiceprint-api)
|
|
||||||
- **Service Documentation**: [Voiceprint API README](https://github.com/xinnan-tech/voiceprint-api/blob/main/README.md)
|
|
||||||
|
|
||||||
## 🛠️ Implementation Details (Original)
|
- `GET /voiceprint/health?key=<key>` — health probe; expects
|
||||||
|
`{"status": "healthy"}` (cached after the first success).
|
||||||
|
- `POST /voiceprint/identify` — multipart form with the WAV audio and the API
|
||||||
|
key; the service replies with the best-matching speaker id and a similarity
|
||||||
|
score (scores below `similarity_threshold` are treated as unknown).
|
||||||
|
|
||||||
The original voiceprint recognition system includes:
|
Speaker voice vectors are enrolled out-of-band by the service itself; the
|
||||||
|
server only sends audio and reads back identifications. See the original
|
||||||
|
[voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) README for a
|
||||||
|
reference implementation of these endpoints.
|
||||||
|
|
||||||
### **Components**
|
## ⚖️ Privacy and Compliance
|
||||||
- **Voiceprint API Service** - Standalone service for voice processing
|
|
||||||
- **MySQL Database** - Stores voiceprint feature vectors
|
|
||||||
- **Docker Deployment** - Containerized service deployment
|
|
||||||
- **REST API** - HTTP endpoints for voiceprint management
|
|
||||||
|
|
||||||
### **Features**
|
Voiceprints are biometric data (GDPR special category in the EU, BIPA in
|
||||||
- **Voice Registration** - Register users' voice patterns
|
Illinois, etc.). Before enabling:
|
||||||
- **Voice Recognition** - Identify users by their voice
|
|
||||||
- **Database Storage** - Persistent storage of voiceprint data
|
|
||||||
- **API Integration** - RESTful API for voiceprint operations
|
|
||||||
|
|
||||||
### **Technical Requirements**
|
- Run the voiceprint service **locally**; do not send family audio to third
|
||||||
- **MySQL Database** - For storing voiceprint data
|
parties without a processor agreement.
|
||||||
- **Docker** - For service deployment
|
- Obtain explicit consent from every enrolled speaker and document retention
|
||||||
- **Audio Processing** - WAV audio file handling
|
and deletion procedures.
|
||||||
- **Feature Extraction** - Voice characteristic analysis
|
- Keep `similarity_threshold` conservative; misidentification feeds the wrong
|
||||||
|
persona into the LLM context.
|
||||||
## 🔮 Future Implementation
|
|
||||||
|
|
||||||
Voiceprint recognition may be implemented in future versions of the English Xiaozhi ESP32 Server. This would involve:
|
|
||||||
|
|
||||||
### **Planned Features**
|
|
||||||
- **English Voice Models** - Optimized for English speech patterns
|
|
||||||
- **Western API Integration** - Integration with Western voice recognition services
|
|
||||||
- **Privacy-Focused Design** - Local processing with privacy protection
|
|
||||||
- **Multi-language Support** - Support for multiple languages
|
|
||||||
|
|
||||||
### **Implementation Considerations**
|
|
||||||
- **Privacy Concerns** - Voice biometric data handling
|
|
||||||
- **Accuracy Requirements** - High accuracy for user identification
|
|
||||||
- **Performance Impact** - Minimal impact on system performance
|
|
||||||
- **Legal Compliance** - Compliance with privacy regulations
|
|
||||||
|
|
||||||
## 🎯 Alternative Solutions
|
|
||||||
|
|
||||||
While voiceprint recognition is not available, you can achieve similar functionality through:
|
|
||||||
|
|
||||||
### **User Identification Methods**
|
|
||||||
- **Device-based Identification** - Different devices for different users
|
|
||||||
- **Voice Commands** - Custom voice commands for user identification
|
|
||||||
- **Manual User Selection** - Manual user switching in the interface
|
|
||||||
- **Time-based Profiles** - Different profiles based on time of day
|
|
||||||
|
|
||||||
### **Personalization Features**
|
|
||||||
- **Custom Responses** - Personalized responses based on user preferences
|
|
||||||
- **User Profiles** - Different user profiles with custom settings
|
|
||||||
- **Voice Customization** - Different TTS voices for different users
|
|
||||||
- **Command Customization** - Custom voice commands per user
|
|
||||||
|
|
||||||
## 📚 Related Documentation
|
## 📚 Related Documentation
|
||||||
|
|
||||||
### **Available Features**
|
- **[Voice Interaction](../features/voice-interaction.md)** — Basic voice recognition and synthesis
|
||||||
- **[Voice Interaction](../features/voice-interaction.md)** - Basic voice recognition and synthesis
|
- **[Integrations](../features/integrations.md)** — Third-party service integrations
|
||||||
- **[Plugin System](../features/plugins.md)** - Extensible functionality
|
- **[Configuration](../configuration/basic-setup.md)** — System configuration
|
||||||
- **[Integrations](../features/integrations.md)** - Third-party service integrations
|
|
||||||
- **[Configuration](../configuration/basic-setup.md)** - System configuration
|
|
||||||
|
|
||||||
### **Original Features**
|
|
||||||
- **[Original Repository](https://github.com/xinnan-tech/xiaozhi-esp32-server)** - Complete original implementation
|
|
||||||
- **[Chinese Documentation](https://github.com/xinnan-tech/xiaozhi-esp32-server/tree/main/docs)** - Original documentation
|
|
||||||
- **[Voiceprint API](https://github.com/xinnan-tech/voiceprint-api)** - Original voiceprint service
|
|
||||||
|
|
||||||
## 🆘 Support and Questions
|
|
||||||
|
|
||||||
### **For Voiceprint Recognition**
|
|
||||||
- **Original Implementation**: Refer to [xinnan-tech repository](https://github.com/xinnan-tech/xiaozhi-esp32-server)
|
|
||||||
- **Voiceprint Service**: Check [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api)
|
|
||||||
- **Chinese Documentation**: [Original voiceprint guide](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/voiceprint-integration.md)
|
|
||||||
|
|
||||||
### **For English Version**
|
|
||||||
- **Feature Requests**: [GitHub Issues](https://github.com/lapy/xiaozhi-esp32-server/issues)
|
|
||||||
- **Community Support**: [Discord Community](https://discord.gg/xiaozhi-esp32)
|
|
||||||
- **General Questions**: [FAQ](../support/faq.md)
|
|
||||||
|
|
||||||
## 🎯 Next Steps
|
|
||||||
|
|
||||||
Since voiceprint recognition is not available in the English version:
|
|
||||||
|
|
||||||
1. **[Use Available Features](../features/voice-interaction.md)** - Explore current voice capabilities
|
|
||||||
2. **[Check Original Implementation](https://github.com/xinnan-tech/xiaozhi-esp32-server)** - Refer to Chinese version if needed
|
|
||||||
3. **[Request Feature Implementation](https://github.com/lapy/xiaozhi-esp32-server/issues)** - Submit feature request
|
|
||||||
4. **[Explore Alternatives](#alternative-solutions)** - Use alternative user identification methods
|
|
||||||
|
|
||||||
## 🆘 Need Help?
|
|
||||||
|
|
||||||
- **Voiceprint Questions?** Check [Original Implementation](https://github.com/xinnan-tech/xiaozhi-esp32-server)
|
|
||||||
- **English Version Questions?** Browse [FAQ](../support/faq.md)
|
|
||||||
- **Feature Requests?** Submit [GitHub Issue](https://github.com/lapy/xiaozhi-esp32-server/issues)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🎯 Quick Reference
|
|
||||||
|
|
||||||
### **Current Status**
|
|
||||||
- ❌ **Not Available** in English version
|
|
||||||
- ✅ **Available** in original Chinese version
|
|
||||||
- 🔗 **Original Implementation**: [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server)
|
|
||||||
|
|
||||||
### **Alternative Solutions**
|
|
||||||
- Device-based identification
|
|
||||||
- Custom voice commands
|
|
||||||
- Manual user selection
|
|
||||||
- Time-based profiles
|
|
||||||
|
|
||||||
### **Future Plans**
|
|
||||||
- English voice models
|
|
||||||
- Western API integration
|
|
||||||
- Privacy-focused design
|
|
||||||
- Multi-language support
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Voiceprint recognition is not available in the English version. Please refer to the original Chinese implementation for this feature. 🎤**
|
|
||||||
|
|
||||||
👉 **[Next: Available Features →](../features/voice-interaction.md)**
|
👉 **[Next: Available Features →](../features/voice-interaction.md)**
|
||||||
|
|
|
||||||
|
|
@ -55,19 +55,21 @@ auto_import_modules("plugins_func.functions")
|
||||||
class TTSException(RuntimeError):
|
class TTSException(RuntimeError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# direct_answer 虚拟工具定义
|
# direct_answer virtual tool definition.
|
||||||
# 不是真实工具,是路由机制:将"调不调工具"的二选一变为"调哪个"的多选,防止小模型误触发真实工具
|
# Not a real tool: it is a routing mechanism that turns the binary
|
||||||
|
# "call a tool or not" choice into a "which one" selection, which stops small
|
||||||
|
# models from misfiring real tools.
|
||||||
DIRECT_ANSWER_TOOL = {
|
DIRECT_ANSWER_TOOL = {
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "direct_answer",
|
"name": "direct_answer",
|
||||||
"description": "当用户的请求不匹配其他任何工具时,可用此选项直接回复。将回复内容写在response参数里。",
|
"description": "Use this option to reply directly when the user's request matches no other tool. Write your full reply in the response parameter.",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"response": {
|
"response": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "你回复用户的完整内容",
|
"description": "The complete reply you give to the user",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"required": ["response"],
|
"required": ["response"],
|
||||||
|
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
import re
|
|
||||||
from urllib.parse import urlsplit
|
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_WS_URL = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/"
|
|
||||||
INFERENCE_PATH = "/api-ws/v1/inference"
|
|
||||||
HOSTNAME_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$")
|
|
||||||
HAPPY_EYEBALLS_DELAY = 0.25
|
|
||||||
|
|
||||||
|
|
||||||
def build_ws_connect_options(open_timeout):
|
|
||||||
return {
|
|
||||||
"open_timeout": open_timeout,
|
|
||||||
"happy_eyeballs_delay": HAPPY_EYEBALLS_DELAY,
|
|
||||||
"interleave": 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_ws_url(value):
|
|
||||||
ws_url = str(value or DEFAULT_WS_URL).strip()
|
|
||||||
parsed = urlsplit(ws_url)
|
|
||||||
hostname = (parsed.hostname or "").lower()
|
|
||||||
is_dashscope = hostname in {
|
|
||||||
"dashscope.aliyuncs.com",
|
|
||||||
"dashscope-intl.aliyuncs.com",
|
|
||||||
}
|
|
||||||
is_workspace = hostname.endswith(".maas.aliyuncs.com")
|
|
||||||
|
|
||||||
try:
|
|
||||||
port = parsed.port
|
|
||||||
except ValueError:
|
|
||||||
port = -1
|
|
||||||
|
|
||||||
if (
|
|
||||||
parsed.scheme.lower() != "wss"
|
|
||||||
or not HOSTNAME_PATTERN.fullmatch(hostname)
|
|
||||||
or not (is_dashscope or is_workspace)
|
|
||||||
or parsed.path.rstrip("/") != INFERENCE_PATH
|
|
||||||
or parsed.query
|
|
||||||
or parsed.fragment
|
|
||||||
or parsed.username
|
|
||||||
or parsed.password
|
|
||||||
or port not in {None, 443}
|
|
||||||
):
|
|
||||||
raise ValueError(
|
|
||||||
"ws_url must be an official Alibaba Cloud WSS inference endpoint"
|
|
||||||
)
|
|
||||||
return ws_url
|
|
||||||
|
|
@ -129,24 +129,3 @@ def initialize_asr(config):
|
||||||
)
|
)
|
||||||
logger.bind(tag=TAG).info("ASR module initialization completed")
|
logger.bind(tag=TAG).info("ASR module initialization completed")
|
||||||
return new_asr
|
return new_asr
|
||||||
|
|
||||||
|
|
||||||
def initialize_voiceprint(asr_instance, config):
|
|
||||||
"""Initialize voiceprint recognition functionality"""
|
|
||||||
voiceprint_config = config.get("voiceprint")
|
|
||||||
if not voiceprint_config:
|
|
||||||
return False
|
|
||||||
|
|
||||||
# Apply configuration
|
|
||||||
if not voiceprint_config.get("url") or not voiceprint_config.get("speakers"):
|
|
||||||
logger.bind(tag=TAG).warning("Voiceprint recognition configuration incomplete")
|
|
||||||
return False
|
|
||||||
|
|
||||||
try:
|
|
||||||
asr_instance.init_voiceprint(voiceprint_config)
|
|
||||||
logger.bind(tag=TAG).info("ASR module voiceprint recognition functionality dynamically enabled")
|
|
||||||
logger.bind(tag=TAG).info(f"Configured speaker count: {len(voiceprint_config['speakers'])}")
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Dynamic initialization of voiceprint recognition functionality failed: {str(e)}")
|
|
||||||
return False
|
|
||||||
|
|
|
||||||
|
|
@ -15,16 +15,6 @@ from jinja2 import Template
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
WEEKDAY_MAP = {
|
|
||||||
"Monday": "星期一",
|
|
||||||
"Tuesday": "星期二",
|
|
||||||
"Wednesday": "星期三",
|
|
||||||
"Thursday": "星期四",
|
|
||||||
"Friday": "星期五",
|
|
||||||
"Saturday": "星期六",
|
|
||||||
"Sunday": "星期日",
|
|
||||||
}
|
|
||||||
|
|
||||||
EMOJI_List = [
|
EMOJI_List = [
|
||||||
"😶",
|
"😶",
|
||||||
"🙂",
|
"🙂",
|
||||||
|
|
@ -153,7 +143,7 @@ class PromptManager:
|
||||||
from core.utils.util import get_ip_info
|
from core.utils.util import get_ip_info
|
||||||
|
|
||||||
ip_info = get_ip_info(client_ip, self.logger)
|
ip_info = get_ip_info(client_ip, self.logger)
|
||||||
city = ip_info.get("city", "未知位置")
|
city = ip_info.get("city", "Unknown location")
|
||||||
location = f"{city}"
|
location = f"{city}"
|
||||||
|
|
||||||
# 存入缓存
|
# 存入缓存
|
||||||
|
|
@ -161,7 +151,7 @@ class PromptManager:
|
||||||
return location
|
return location
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}")
|
self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}")
|
||||||
return "未知位置"
|
return "Unknown location"
|
||||||
|
|
||||||
def _get_weather_info(self, conn: "ConnectionHandler", location: str) -> str:
|
def _get_weather_info(self, conn: "ConnectionHandler", location: str) -> str:
|
||||||
"""获取天气信息"""
|
"""获取天气信息"""
|
||||||
|
|
@ -184,7 +174,7 @@ class PromptManager:
|
||||||
async def _call():
|
async def _call():
|
||||||
try:
|
try:
|
||||||
result_holder.append(
|
result_holder.append(
|
||||||
await get_weather(conn, location=location, lang="zh_CN")
|
await get_weather(conn, location=location, lang="en_US")
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
exception_holder.append(e)
|
exception_holder.append(e)
|
||||||
|
|
|
||||||
|
|
@ -86,9 +86,12 @@ def get_ip_info(ip_addr, logger):
|
||||||
# Cache miss: resolve the IP through the API.
|
# Cache miss: resolve the IP through the API.
|
||||||
if is_private_ip(ip_addr):
|
if is_private_ip(ip_addr):
|
||||||
ip_addr = ""
|
ip_addr = ""
|
||||||
url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={ip_addr}"
|
# ip-api.com returns English place names worldwide; status=="fail"
|
||||||
resp = requests.get(url).json()
|
# (e.g. private/loopback addresses) yields an empty city.
|
||||||
ip_info = {"city": resp.get("city")}
|
url = f"http://ip-api.com/json/{ip_addr}?fields=status,city&lang=en"
|
||||||
|
resp = requests.get(url, timeout=5).json()
|
||||||
|
city = resp.get("city") if resp.get("status") == "success" else None
|
||||||
|
ip_info = {"city": city or ""}
|
||||||
|
|
||||||
# Store the result in cache.
|
# Store the result in cache.
|
||||||
cache_manager.set(CacheType.IP_INFO, ip_addr, ip_info)
|
cache_manager.set(CacheType.IP_INFO, ip_addr, ip_info)
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,10 @@
|
||||||
{
|
{
|
||||||
"des": [
|
"des": [
|
||||||
"在data目录下创建.mcp_server_settings.json文件,可以选择下面的MCP服务,也可以自行添加新的MCP服务。",
|
"Create a .mcp_server_settings.json file in the data directory. You can pick MCP services below or add your own.",
|
||||||
"后面不断测试补充好用的mcp服务,欢迎大家一起补充。",
|
"More useful MCP services will be added as they are tested; contributions welcome.",
|
||||||
"记得删除注释行,des属性仅为说明,不会被解析。",
|
"Remember to delete the comment lines: the des property is informational only and is not parsed.",
|
||||||
"des和link属性,仅为说明安装方式,方便大家查看原始链接,不是必须项。",
|
"The des and link properties only document installation and original links; they are optional.",
|
||||||
"当前支持三种传输模式:stdio(标准输入输出), sse(Server-Sent Events), streamable-http(流式HTTP)。"
|
"Three transport modes are supported: stdio, sse (Server-Sent Events), and streamable-http."
|
||||||
],
|
],
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"Home Assistant": {
|
"Home Assistant": {
|
||||||
|
|
@ -42,7 +42,7 @@
|
||||||
"headers": {
|
"headers": {
|
||||||
"Authorization": "Bearer YOUR TOKEN"
|
"Authorization": "Bearer YOUR TOKEN"
|
||||||
},
|
},
|
||||||
"des": "使用SSE传输模式(默认)"
|
"des": "Uses SSE transport mode (default)"
|
||||||
},
|
},
|
||||||
"streamable-http-mcp-server": {
|
"streamable-http-mcp-server": {
|
||||||
"url": "http://localhost:8000/mcp",
|
"url": "http://localhost:8000/mcp",
|
||||||
|
|
@ -50,7 +50,7 @@
|
||||||
"headers": {
|
"headers": {
|
||||||
"Authorization": "Bearer YOUR TOKEN"
|
"Authorization": "Bearer YOUR TOKEN"
|
||||||
},
|
},
|
||||||
"des": "使用Streamable HTTP传输模式,适用于生产环境的Web部署"
|
"des": "Uses Streamable HTTP transport mode, suitable for production web deployments"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""呼叫设备工具"""
|
"""Device calling tool"""
|
||||||
import httpx
|
import httpx
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
|
|
@ -15,18 +15,24 @@ call_device_function_desc = {
|
||||||
"function": {
|
"function": {
|
||||||
"name": "call_device",
|
"name": "call_device",
|
||||||
"description": (
|
"description": (
|
||||||
"用于设备之间建立语音通话连接。"
|
"Establish a voice call connection between devices. "
|
||||||
"当用户说出以下意图时调用此工具:\n"
|
"Call this tool when the user expresses one of these intents:\n"
|
||||||
"1. 主动呼叫:用户说”呼叫XX/打电话给XX/连线XX/打给XX/帮我呼叫XX”时调用,nickname取XX。"
|
"1. Outgoing call: call it when the user says things like "
|
||||||
"例如:”呼叫张三”→nickname=”张三”、”帮我连线小陈”→nickname=”小陈”;\n"
|
"\"call XX / phone XX / connect me to XX / dial XX / get me XX on the line\"; "
|
||||||
"2. 接听来电:系统刚提示”您收到来自XX的来电,是否接听?”后,用户说”接听/接通/同意接听/同意连线/同意对话”时调用,"
|
"take XX as the nickname. "
|
||||||
"nickname取提示中的XX。\n"
|
"Examples: \"call John\" -> nickname=\"John\", "
|
||||||
"如果用户输入不是明确接听,也不是明确拒绝,不得调用call_device,必须先追问一次"
|
"\"connect me to Sarah\" -> nickname=\"Sarah\";\n"
|
||||||
|
"2. Answering an incoming call: right after the system announces "
|
||||||
|
"\"Incoming call from XX, do you want to answer?\", call it when the "
|
||||||
|
"user says \"answer / pick up / yes answer / yes connect / yes talk\"; "
|
||||||
|
"take XX from the announcement as the nickname.\n"
|
||||||
|
"If the user's input is neither a clear acceptance nor a clear refusal, "
|
||||||
|
"do NOT call call_device; you must ask once first."
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"nickname": {"type": "string", "description": "目标设备的备注名,例如:小陈、小翁"},
|
"nickname": {"type": "string", "description": "Display name of the target device, e.g. John, Sarah"},
|
||||||
},
|
},
|
||||||
"required": ["nickname"],
|
"required": ["nickname"],
|
||||||
},
|
},
|
||||||
|
|
@ -44,7 +50,7 @@ def _failed_reply(msg: str) -> ActionResponse:
|
||||||
|
|
||||||
|
|
||||||
def _is_answering(conn: "ConnectionHandler") -> bool:
|
def _is_answering(conn: "ConnectionHandler") -> bool:
|
||||||
"""检查是否为接听模式(conn.incoming_call 不为空)"""
|
"""Whether this is answer mode (conn.incoming_call is not empty)"""
|
||||||
return hasattr(conn, 'incoming_call') and conn.incoming_call is not None
|
return hasattr(conn, 'incoming_call') and conn.incoming_call is not None
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -52,24 +58,24 @@ def _is_answering(conn: "ConnectionHandler") -> bool:
|
||||||
async def call_device(conn: "ConnectionHandler", nickname: str):
|
async def call_device(conn: "ConnectionHandler", nickname: str):
|
||||||
caller_mac = conn.headers.get("device-id")
|
caller_mac = conn.headers.get("device-id")
|
||||||
if not caller_mac:
|
if not caller_mac:
|
||||||
return _failed_reply("无法获取本机MAC地址")
|
return _failed_reply("Unable to get this device's MAC address")
|
||||||
|
|
||||||
api_config = conn.config.get("manager-api", {})
|
api_config = conn.config.get("manager-api", {})
|
||||||
api_url = api_config.get("url")
|
api_url = api_config.get("url")
|
||||||
api_secret = api_config.get("secret")
|
api_secret = api_config.get("secret")
|
||||||
if not api_url or not api_secret:
|
if not api_url or not api_secret:
|
||||||
logger.bind(tag=TAG).error("manager-api配置缺失")
|
logger.bind(tag=TAG).error("manager-api configuration missing")
|
||||||
return _failed_reply("配置错误,请稍后再试")
|
return _failed_reply("Configuration error, please try again later")
|
||||||
|
|
||||||
headers = {"Authorization": f"Bearer {api_secret}"}
|
headers = {"Authorization": f"Bearer {api_secret}"}
|
||||||
|
|
||||||
# 区分是主动呼叫还是接听来电
|
# Distinguish outgoing call from answering an incoming call
|
||||||
is_answer = _is_answering(conn)
|
is_answer = _is_answering(conn)
|
||||||
params = {"callerMac": caller_mac, "nickname": nickname}
|
params = {"callerMac": caller_mac, "nickname": nickname}
|
||||||
if is_answer:
|
if is_answer:
|
||||||
params["answer"] = "true"
|
params["answer"] = "true"
|
||||||
|
|
||||||
# 查询通讯录并发起呼叫
|
# Look up the address book and place the call
|
||||||
try:
|
try:
|
||||||
resp = await _request_api(
|
resp = await _request_api(
|
||||||
f"{api_url}/device/address-book/call",
|
f"{api_url}/device/address-book/call",
|
||||||
|
|
@ -78,18 +84,18 @@ async def call_device(conn: "ConnectionHandler", nickname: str):
|
||||||
)
|
)
|
||||||
result = resp.json()
|
result = resp.json()
|
||||||
except httpx.HTTPError as e:
|
except httpx.HTTPError as e:
|
||||||
logger.bind(tag=TAG).error(f"呼叫请求失败: {e}")
|
logger.bind(tag=TAG).error(f"Call request failed: {e}")
|
||||||
return _failed_reply("呼叫失败,请稍后再试")
|
return _failed_reply("Call failed, please try again later")
|
||||||
|
|
||||||
if result.get("code") != 0:
|
if result.get("code") != 0:
|
||||||
return _failed_reply(result.get("msg", "呼叫失败"))
|
return _failed_reply(result.get("msg", "Call failed"))
|
||||||
|
|
||||||
data = result.get("data", {})
|
data = result.get("data", {})
|
||||||
if data.get("status") == "error":
|
if data.get("status") == "error":
|
||||||
return _failed_reply(data.get("message"))
|
return _failed_reply(data.get("message"))
|
||||||
|
|
||||||
if is_answer:
|
if is_answer:
|
||||||
return ActionResponse(action=Action.NONE, response="已成功接听")
|
return ActionResponse(action=Action.NONE, response="Call answered")
|
||||||
else:
|
else:
|
||||||
conn.calling = True
|
conn.calling = True
|
||||||
return ActionResponse(action=Action.NONE, response=f"正在呼叫{nickname},请等待对方接听")
|
return ActionResponse(action=Action.NONE, response=f"Calling {nickname}, please wait for them to answer")
|
||||||
|
|
|
||||||
|
|
@ -14,13 +14,13 @@ hass_get_state_function_desc = {
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "hass_get_state",
|
"name": "hass_get_state",
|
||||||
"description": "获取homeassistant里设备的状态,包括查询灯光亮度、颜色、色温,媒体播放器的音量,设备的暂停、继续操作",
|
"description": "Get device state in homeassistant, including light brightness, color, color temperature, media player volume, and device pause/resume state",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"entity_id": {
|
"entity_id": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "需要操作的设备id,homeassistant里的entity_id",
|
"description": "Device id to query, entity_id in homeassistant",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["entity_id"],
|
"required": ["entity_id"],
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,8 @@ TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
_DEFAULT_DESCRIPTION = (
|
_DEFAULT_DESCRIPTION = (
|
||||||
"联网搜索工具。当用户明确需要联网搜索问题时使用此工具。"
|
"Web search tool. Use this tool when the user explicitly asks for "
|
||||||
|
"current information from the internet."
|
||||||
)
|
)
|
||||||
|
|
||||||
WEB_SEARCH_FUNCTION_DESC = {
|
WEB_SEARCH_FUNCTION_DESC = {
|
||||||
|
|
@ -28,7 +29,7 @@ WEB_SEARCH_FUNCTION_DESC = {
|
||||||
"properties": {
|
"properties": {
|
||||||
"query": {
|
"query": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "搜索关键词或问题",
|
"description": "Search keywords or question",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": ["query"],
|
"required": ["query"],
|
||||||
|
|
@ -38,7 +39,7 @@ WEB_SEARCH_FUNCTION_DESC = {
|
||||||
|
|
||||||
|
|
||||||
async def _search_metaso(api_key: str, query: str, max_results: int) -> str:
|
async def _search_metaso(api_key: str, query: str, max_results: int) -> str:
|
||||||
"""调用秘塔搜索API"""
|
"""Call the Metaso search API"""
|
||||||
url = "https://metaso.cn/api/v1/search"
|
url = "https://metaso.cn/api/v1/search"
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {api_key}",
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
|
@ -53,32 +54,32 @@ async def _search_metaso(api_key: str, query: str, max_results: int) -> str:
|
||||||
"includeRawContent": False,
|
"includeRawContent": False,
|
||||||
"conciseSnippet": False,
|
"conciseSnippet": False,
|
||||||
}
|
}
|
||||||
logger.bind(tag=TAG).debug(f"秘塔搜索请求 | URL: {url} | payload: {payload}")
|
logger.bind(tag=TAG).debug(f"Metaso search request | URL: {url} | payload: {payload}")
|
||||||
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
||||||
response = await client.post(url, json=payload, headers=headers)
|
response = await client.post(url, json=payload, headers=headers)
|
||||||
data = response.json()
|
data = response.json()
|
||||||
logger.bind(tag=TAG).debug(f"秘塔搜索响应 | status: {response.status_code}")
|
logger.bind(tag=TAG).debug(f"Metaso search response | status: {response.status_code}")
|
||||||
|
|
||||||
webpages = data.get("webpages", [])
|
webpages = data.get("webpages", [])
|
||||||
if not webpages:
|
if not webpages:
|
||||||
return "未找到相关搜索结果。"
|
return "No related search results found."
|
||||||
|
|
||||||
lines = ["【联网搜索结果】"]
|
lines = ["[Web search results]"]
|
||||||
for i, item in enumerate(webpages, 1):
|
for i, item in enumerate(webpages, 1):
|
||||||
title = item.get("title", "无标题")
|
title = item.get("title", "Untitled")
|
||||||
snippet = item.get("summary", "")
|
snippet = item.get("summary", "")
|
||||||
date = item.get("date", "")
|
date = item.get("date", "")
|
||||||
lines.append(f"{i}. 标题:{title}")
|
lines.append(f"{i}. Title: {title}")
|
||||||
if date:
|
if date:
|
||||||
lines.append(f" 日期:{date}")
|
lines.append(f" Date: {date}")
|
||||||
if snippet:
|
if snippet:
|
||||||
lines.append(f" 摘要:{snippet}")
|
lines.append(f" Summary: {snippet}")
|
||||||
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
async def _search_tavily(api_key: str, query: str, max_results: int) -> str:
|
async def _search_tavily(api_key: str, query: str, max_results: int) -> str:
|
||||||
"""调用Tavily搜索API"""
|
"""Call the Tavily search API"""
|
||||||
url = "https://api.tavily.com/search"
|
url = "https://api.tavily.com/search"
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {api_key}",
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
|
@ -90,81 +91,82 @@ async def _search_tavily(api_key: str, query: str, max_results: int) -> str:
|
||||||
"search_depth": "advanced",
|
"search_depth": "advanced",
|
||||||
"include_answer": "advanced",
|
"include_answer": "advanced",
|
||||||
}
|
}
|
||||||
logger.bind(tag=TAG).debug(f"Tavily搜索请求 | URL: {url} | payload: {payload}")
|
logger.bind(tag=TAG).debug(f"Tavily search request | URL: {url} | payload: {payload}")
|
||||||
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
||||||
response = await client.post(url, json=payload, headers=headers)
|
response = await client.post(url, json=payload, headers=headers)
|
||||||
data = response.json()
|
data = response.json()
|
||||||
logger.bind(tag=TAG).debug(f"Tavily搜索响应 | status: {response.status_code} | data: {data}")
|
logger.bind(tag=TAG).debug(f"Tavily search response | status: {response.status_code} | data: {data}")
|
||||||
|
|
||||||
results = data.get("results", [])
|
results = data.get("results", [])
|
||||||
if not results:
|
if not results:
|
||||||
return "未找到相关搜索结果。"
|
return "No related search results found."
|
||||||
|
|
||||||
answer = data.get("answer", "")
|
answer = data.get("answer", "")
|
||||||
lines = [f"【联网搜索结果】\n总结:{answer}"]
|
lines = [f"[Web search results]\nSummary: {answer}"]
|
||||||
# for i, item in enumerate(results, 1):
|
# for i, item in enumerate(results, 1):
|
||||||
# title = item.get("title", "无标题")
|
# title = item.get("title", "Untitled")
|
||||||
# summary = item.get("content", "")
|
# summary = item.get("content", "")
|
||||||
# lines.append(f"{i}. 标题:{title}")
|
# lines.append(f"{i}. Title: {title}")
|
||||||
# if summary:
|
# if summary:
|
||||||
# lines.append(f" 摘要:{summary}")
|
# lines.append(f" Summary: {summary}")
|
||||||
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
async def _search_serply(api_key: str, query: str, max_results: int) -> str:
|
async def _search_serply(api_key: str, query: str, max_results: int) -> str:
|
||||||
"""调用Serply搜索API"""
|
"""Call the Serply search API"""
|
||||||
url = "https://api.serply.io/v1/search"
|
url = "https://api.serply.io/v1/search"
|
||||||
headers = {
|
headers = {
|
||||||
"X-Api-Key": api_key,
|
"X-Api-Key": api_key,
|
||||||
"User-Agent": "xiaozhi-esp32-server",
|
"User-Agent": "xiaozhi-esp32-server",
|
||||||
}
|
}
|
||||||
# Serply单页最多返回10条,且返回条数可能略多于num,需要本地再截断一次
|
# Serply returns at most 10 items per page and may return slightly more
|
||||||
|
# than num, so truncate locally once more.
|
||||||
params = {"q": query, "num": min(max_results, 10)}
|
params = {"q": query, "num": min(max_results, 10)}
|
||||||
logger.bind(tag=TAG).debug(f"Serply搜索请求 | URL: {url} | params: {params}")
|
logger.bind(tag=TAG).debug(f"Serply search request | URL: {url} | params: {params}")
|
||||||
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
||||||
response = await client.get(url, params=params, headers=headers)
|
response = await client.get(url, params=params, headers=headers)
|
||||||
data = response.json()
|
data = response.json()
|
||||||
logger.bind(tag=TAG).debug(f"Serply搜索响应 | status: {response.status_code}")
|
logger.bind(tag=TAG).debug(f"Serply search response | status: {response.status_code}")
|
||||||
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
detail = data.get("detail", "") if isinstance(data, dict) else ""
|
detail = data.get("detail", "") if isinstance(data, dict) else ""
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"Serply搜索失败 | status: {response.status_code} | detail: {detail}"
|
f"Serply search failed | status: {response.status_code} | detail: {detail}"
|
||||||
)
|
)
|
||||||
return "联网搜索请求失败,请检查API Key是否正确。"
|
return "Web search request failed. Please check that the API key is correct."
|
||||||
|
|
||||||
results = data.get("results", [])
|
results = data.get("results", [])
|
||||||
if not results:
|
if not results:
|
||||||
return "未找到相关搜索结果。"
|
return "No related search results found."
|
||||||
|
|
||||||
lines = ["【联网搜索结果】"]
|
lines = ["[Web search results]"]
|
||||||
for i, item in enumerate(results[:max_results], 1):
|
for i, item in enumerate(results[:max_results], 1):
|
||||||
title = item.get("title", "无标题")
|
title = item.get("title", "Untitled")
|
||||||
snippet = item.get("description", "")
|
snippet = item.get("description", "")
|
||||||
lines.append(f"{i}. 标题:{title}")
|
lines.append(f"{i}. Title: {title}")
|
||||||
if snippet:
|
if snippet:
|
||||||
lines.append(f" 摘要:{snippet}")
|
lines.append(f" Summary: {snippet}")
|
||||||
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
@register_function("web_search", WEB_SEARCH_FUNCTION_DESC, ToolType.SYSTEM_CTL)
|
@register_function("web_search", WEB_SEARCH_FUNCTION_DESC, ToolType.SYSTEM_CTL)
|
||||||
async def web_search(conn: "ConnectionHandler", query: str = None):
|
async def web_search(conn: "ConnectionHandler", query: str = None):
|
||||||
logger.bind(tag=TAG).info(f"web_search 被调用 | query={query}")
|
logger.bind(tag=TAG).info(f"web_search called | query={query}")
|
||||||
if not query:
|
if not query:
|
||||||
return ActionResponse(Action.REQLLM, "请提供搜索关键词。", None)
|
return ActionResponse(Action.REQLLM, "Please provide search keywords.", None)
|
||||||
|
|
||||||
web_search_config = conn.config.get("plugins", {}).get("web_search", {})
|
web_search_config = conn.config.get("plugins", {}).get("web_search", {})
|
||||||
provider = web_search_config.get("provider", "").lower()
|
provider = web_search_config.get("provider", "").lower()
|
||||||
max_results = int(web_search_config.get("max_results", 3))
|
max_results = int(web_search_config.get("max_results", 3))
|
||||||
logger.bind(tag=TAG).info(f"web_search 配置 | provider={provider} | max_results={max_results} | config_keys={list(web_search_config.keys())}")
|
logger.bind(tag=TAG).info(f"web_search config | provider={provider} | max_results={max_results} | config_keys={list(web_search_config.keys())}")
|
||||||
|
|
||||||
api_key = web_search_config.get("api_key", "")
|
api_key = web_search_config.get("api_key", "")
|
||||||
if not api_key:
|
if not api_key:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
Action.REQLLM,
|
Action.REQLLM,
|
||||||
"联网搜索功能未配置API Key,请在配置文件中填写。",
|
"Web search has no API key configured. Please fill it in the config file.",
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -178,18 +180,18 @@ async def web_search(conn: "ConnectionHandler", query: str = None):
|
||||||
else:
|
else:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
Action.REQLLM,
|
Action.REQLLM,
|
||||||
f"联网搜索功能未配置或配置的搜索源无效(当前:{provider}),请检查配置。",
|
f"Web search is not configured or the search provider is invalid (current: {provider}). Please check the configuration.",
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
logger.bind(tag=TAG).info(f"搜索结果组装完成:\n{result_text}")
|
logger.bind(tag=TAG).info(f"Search results assembled:\n{result_text}")
|
||||||
except httpx.TimeoutException:
|
except httpx.TimeoutException:
|
||||||
logger.bind(tag=TAG).error("联网搜索请求超时")
|
logger.bind(tag=TAG).error("Web search request timed out")
|
||||||
result_text = "联网搜索请求超时,请稍后重试。"
|
result_text = "The web search request timed out. Please try again later."
|
||||||
except httpx.HTTPStatusError as e:
|
except httpx.HTTPStatusError as e:
|
||||||
logger.bind(tag=TAG).error(f"联网搜索请求失败: {e}")
|
logger.bind(tag=TAG).error(f"Web search request failed: {e}")
|
||||||
result_text = "联网搜索请求失败,请稍后重试。"
|
result_text = "The web search request failed. Please try again later."
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"联网搜索异常: {e}")
|
logger.bind(tag=TAG).error(f"Web search error: {e}")
|
||||||
result_text = "联网搜索出现异常,请稍后重试。"
|
result_text = "The web search hit an error. Please try again later."
|
||||||
|
|
||||||
return ActionResponse(Action.REQLLM, result_text, None)
|
return ActionResponse(Action.REQLLM, result_text, None)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"""Tests for core/utils/current_time.py.
|
"""Tests for core/utils/current_time.py.
|
||||||
|
|
||||||
Uses freezegun to control `datetime.now()` so the tests don't flake
|
Uses freezegun to control `datetime.now()` so the tests don't flake
|
||||||
around midnight, and to verify the weekday/lunar mapping logic.
|
around midnight, and to verify the weekday/date formatting logic.
|
||||||
"""
|
"""
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
@ -27,8 +27,8 @@ def test_get_current_date_format_is_iso():
|
||||||
|
|
||||||
|
|
||||||
@freeze_time("2026-09-02 10:30:00") # 2026-09-02 is a Wednesday
|
@freeze_time("2026-09-02 10:30:00") # 2026-09-02 is a Wednesday
|
||||||
def test_get_current_weekday_returns_chinese_label():
|
def test_get_current_weekday_returns_english_label():
|
||||||
assert current_time.get_current_weekday() == "星期三"
|
assert current_time.get_current_weekday() == "Wednesday"
|
||||||
|
|
||||||
|
|
||||||
def test_weekday_map_has_all_seven_days():
|
def test_weekday_map_has_all_seven_days():
|
||||||
|
|
@ -36,6 +36,8 @@ def test_weekday_map_has_all_seven_days():
|
||||||
"Monday", "Tuesday", "Wednesday", "Thursday",
|
"Monday", "Tuesday", "Wednesday", "Thursday",
|
||||||
"Friday", "Saturday", "Sunday",
|
"Friday", "Saturday", "Sunday",
|
||||||
}
|
}
|
||||||
|
# Western builds map each weekday to its English name.
|
||||||
|
assert all(k == v for k, v in current_time.WEEKDAY_MAP.items())
|
||||||
|
|
||||||
|
|
||||||
@freeze_time("2026-09-02 10:30:00")
|
@freeze_time("2026-09-02 10:30:00")
|
||||||
|
|
@ -43,15 +45,14 @@ def test_get_current_time_info_returns_four_tuple():
|
||||||
info = current_time.get_current_time_info()
|
info = current_time.get_current_time_info()
|
||||||
assert isinstance(info, tuple)
|
assert isinstance(info, tuple)
|
||||||
assert len(info) == 4
|
assert len(info) == 4
|
||||||
time_str, date_str, weekday, lunar = info
|
time_str, date_str, weekday, formatted_date = info
|
||||||
assert time_str == "10:30"
|
assert time_str == "10:30"
|
||||||
assert date_str == "2026-09-02"
|
assert date_str == "2026-09-02"
|
||||||
assert weekday == "星期三"
|
assert weekday == "Wednesday"
|
||||||
assert "年" in lunar # lunar output contains "年"
|
assert formatted_date == "September 02, 2026"
|
||||||
|
|
||||||
|
|
||||||
@freeze_time("2026-09-02 10:30:00")
|
@freeze_time("2026-09-02 10:30:00")
|
||||||
def test_get_current_lunar_date_contains_year():
|
def test_get_current_lunar_date_is_gregorian_alias():
|
||||||
"""cnlunar should produce a string containing 年 character."""
|
"""Western builds return the formatted Gregorian date."""
|
||||||
lunar = current_time.get_current_lunar_date()
|
assert current_time.get_current_lunar_date() == "September 02, 2026"
|
||||||
assert "年" in lunar
|
|
||||||
|
|
|
||||||
|
|
@ -190,13 +190,14 @@ Run the owning subsystem checks after each slice when possible.
|
||||||
### Python server
|
### Python server
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 main/xiaozhi-server/test/test_runner.py
|
cd main/xiaozhi-server
|
||||||
|
PYTHONPATH=. pytest tests/ -q
|
||||||
```
|
```
|
||||||
|
|
||||||
Or project venv if needed:
|
Or the interactive harness:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./.venv-xiaozhi/bin/python main/xiaozhi-server/test/test_runner.py
|
cd main/xiaozhi-server && PYTHONPATH=. python3 ../digital-human/test_runner.py
|
||||||
```
|
```
|
||||||
|
|
||||||
### Manager API
|
### Manager API
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue