mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
Compare commits
7 commits
935f0f1136
...
bdcf68feb9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bdcf68feb9 | ||
|
|
61a8c04477 | ||
|
|
b545623b38 | ||
|
|
63e2bcec8a | ||
|
|
c74a6aaa68 | ||
|
|
0d7180d898 | ||
|
|
b0cc1dc0d1 |
16 changed files with 567 additions and 52 deletions
|
|
@ -272,7 +272,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
||||||
|
|
||||||
| 使用方式 | 支持平台 | 免费平台 |
|
| 使用方式 | 支持平台 | 免费平台 |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| OpenAI 接口调用 | 阿里百炼、智谱ChatGLMVLLM | 智谱ChatGLMVLLM |
|
| OpenAI 接口调用 | 阿里百炼、智谱ChatGLMVLLM、科大讯飞 | 智谱ChatGLMVLLM |
|
||||||
|
|
||||||
实际上,任何支持 OpenAI 接口调用的 VLLM 均可接入使用。
|
实际上,任何支持 OpenAI 接口调用的 VLLM 均可接入使用。
|
||||||
|
|
||||||
|
|
@ -322,6 +322,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
||||||
| Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 |
|
| Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 |
|
||||||
| Memory | mem_local_short | 本地总结 | 免费 | |
|
| Memory | mem_local_short | 本地总结 | 免费 | |
|
||||||
| Memory | nomem | 无记忆模式 | 免费 | |
|
| Memory | nomem | 无记忆模式 | 免费 | |
|
||||||
|
| Memory | mem_report_only | 仅上报 | 免费 | 只上报聊天记录,不做记忆总结 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -270,7 +270,7 @@ Tatsächlich kann jedes LLM, das OpenAI-Schnittstellenaufrufe unterstützt, inte
|
||||||
|
|
||||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||||
|
|
||||||
Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
|
Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
|
||||||
|
|
||||||
|
|
@ -320,6 +320,7 @@ Die Stimmabdruckerkennung erfordert einen separat bereitgestellten [voiceprint-a
|
||||||
| Memory | [powermem](../powermem-integration.md) | Lokale Zusammenfassung | Abhängig von LLM und DB | OceanBase Open Source, unterstützt intelligente Abfrage |
|
| Memory | [powermem](../powermem-integration.md) | Lokale Zusammenfassung | Abhängig von LLM und DB | OceanBase Open Source, unterstützt intelligente Abfrage |
|
||||||
| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
|
| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
|
||||||
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
|
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
|
||||||
|
| Memory | mem_report_only | Nur Meldung | Kostenlos | Meldet nur Chat-Verläufe, keine Gedächtniszusammenfassung |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -270,7 +270,7 @@ In fact, any LLM that supports OpenAI interface calls can be integrated and used
|
||||||
|
|
||||||
| Usage Method | Supported Platforms | Free Platforms |
|
| Usage Method | Supported Platforms | Free Platforms |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||||
|
|
||||||
In fact, any VLLM that supports OpenAI interface calls can be integrated and used.
|
In fact, any VLLM that supports OpenAI interface calls can be integrated and used.
|
||||||
|
|
||||||
|
|
@ -320,6 +320,7 @@ Voiceprint recognition requires a separately deployed [voiceprint-api](https://g
|
||||||
| Memory | [powermem](../powermem-integration.md) | Local summarization | Depends on LLM and DB | OceanBase open source, supports intelligent retrieval |
|
| Memory | [powermem](../powermem-integration.md) | Local summarization | Depends on LLM and DB | OceanBase open source, supports intelligent retrieval |
|
||||||
| Memory | mem_local_short | Local summarization | Free | |
|
| Memory | mem_local_short | Local summarization | Free | |
|
||||||
| Memory | nomem | No memory mode | Free | |
|
| Memory | nomem | No memory mode | Free | |
|
||||||
|
| Memory | mem_report_only | Report only | Free | Only reports chat records, no memory summarization |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -270,7 +270,7 @@ En la práctica, se puede integrar cualquier LLM que admita llamadas por la inte
|
||||||
|
|
||||||
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Llamadas por la interfaz OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
| Llamadas por la interfaz OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||||
|
|
||||||
En la práctica, se puede integrar cualquier VLLM que admita llamadas por la interfaz OpenAI.
|
En la práctica, se puede integrar cualquier VLLM que admita llamadas por la interfaz OpenAI.
|
||||||
|
|
||||||
|
|
@ -320,6 +320,7 @@ El reconocimiento de huella de voz requiere desplegar por separado el servicio [
|
||||||
| Memory | [powermem](../powermem-integration.md) | Resumen local | Depende del LLM y de la base de datos | OceanBase de código abierto; admite búsqueda inteligente |
|
| Memory | [powermem](../powermem-integration.md) | Resumen local | Depende del LLM y de la base de datos | OceanBase de código abierto; admite búsqueda inteligente |
|
||||||
| Memory | mem_local_short | Resumen local | Gratuito | |
|
| Memory | mem_local_short | Resumen local | Gratuito | |
|
||||||
| Memory | nomem | Modo sin memoria | Gratuito | |
|
| Memory | nomem | Modo sin memoria | Gratuito | |
|
||||||
|
| Memory | mem_report_only | Solo informe | Gratuito | Solo informa el historial de chat, sin resumen de memoria |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -270,7 +270,7 @@ Na verdade, qualquer LLM que suporte chamadas via interface OpenAI pode ser inte
|
||||||
|
|
||||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||||
|
|
||||||
Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado.
|
Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado.
|
||||||
|
|
||||||
|
|
@ -320,6 +320,7 @@ O reconhecimento de impressão vocal exige um serviço [voiceprint-api](https://
|
||||||
| Memória | [powermem](../powermem-integration.md) | Resumo local | Depende do LLM e BD | OceanBase de código aberto, suporta busca inteligente |
|
| Memória | [powermem](../powermem-integration.md) | Resumo local | Depende do LLM e BD | OceanBase de código aberto, suporta busca inteligente |
|
||||||
| Memória | mem_local_short | Resumo local | Gratuito | |
|
| Memória | mem_local_short | Resumo local | Gratuito | |
|
||||||
| Memória | nomem | Modo sem memória | Gratuito | |
|
| Memória | nomem | Modo sem memória | Gratuito | |
|
||||||
|
| Memória | mem_report_only | Apenas relatório | Gratuito | Apenas reporta o histórico de chat, sem resumo de memória |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -271,7 +271,7 @@ Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện OpenAI đề
|
||||||
|
|
||||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Gọi giao diện OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
| Gọi giao diện OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
|
||||||
|
|
||||||
Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện OpenAI đều có thể truy cập sử dụng.
|
Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện OpenAI đều có thể truy cập sử dụng.
|
||||||
|
|
||||||
|
|
@ -321,6 +321,7 @@ Nhận dạng vân giọng cần dịch vụ [voiceprint-api](https://github.com
|
||||||
| Memory | [powermem](../powermem-integration.md) | Tóm tắt cục bộ | Phụ thuộc vào LLM và DB | OceanBase mã nguồn mở, hỗ trợ tìm kiếm thông minh |
|
| Memory | [powermem](../powermem-integration.md) | Tóm tắt cục bộ | Phụ thuộc vào LLM và DB | OceanBase mã nguồn mở, hỗ trợ tìm kiếm thông minh |
|
||||||
| Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | |
|
| Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | |
|
||||||
| Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | |
|
| Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | |
|
||||||
|
| Memory | mem_report_only | Chỉ báo cáo | Miễn phí | Chỉ báo cáo lịch sử trò chuyện, không tóm tắt bộ nhớ |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,15 +2,16 @@
|
||||||
|
|
||||||
## 功能简介
|
## 功能简介
|
||||||
|
|
||||||
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持四个搜索源:秘塔(Metaso)、Tavily、Serply和Outcrawl,用户可根据需要选择其中一个。
|
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持五个搜索源:秘塔(Metaso)、Tavily、Serply、Outcrawl和SpecStream,用户可根据需要选择其中一个。
|
||||||
|
|
||||||
## API Key申请指南
|
## API Key申请指南
|
||||||
|
|
||||||
目前我们适配了`秘塔搜索`、`Tavily搜索`、`Serply搜索`和`Outcrawl搜索`。
|
目前我们适配了`秘塔搜索`、`Tavily搜索`、`Serply搜索`、`Outcrawl搜索`和`SpecStream搜索`。
|
||||||
- Tavily搜索:每个月1000次免费额度。
|
- Tavily搜索:每个月1000次免费额度。
|
||||||
- 秘塔搜索:拥有较为优质的国内数据源。
|
- 秘塔搜索:拥有较为优质的国内数据源。
|
||||||
- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。
|
- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。
|
||||||
- Outcrawl搜索:面向AI智能体的网页搜索接口,每月1000 credits免费额度。
|
- Outcrawl搜索:面向AI智能体的网页搜索接口,每月1000 credits免费额度。
|
||||||
|
- SpecStream搜索:注册赠送10美元,每条结果带来源链接和摘要,有发布日期时一并返回;每1000次搜索5美元(每次最多10条结果)。
|
||||||
|
|
||||||
## API Key申请指南
|
## API Key申请指南
|
||||||
|
|
||||||
|
|
@ -40,6 +41,13 @@
|
||||||
- 复制生成的API Key,这是配置所需的关键信息
|
- 复制生成的API Key,这是配置所需的关键信息
|
||||||
- 接口说明见 [Outcrawl文档](https://outcrawl.ai/docs/search/overview)
|
- 接口说明见 [Outcrawl文档](https://outcrawl.ai/docs/search/overview)
|
||||||
|
|
||||||
|
### 方式五:使用SpecStream搜索
|
||||||
|
|
||||||
|
- 访问 [SpecStream](https://specstream.ai/signup?src=xiaozhi-esp32-server),注册并登录账号
|
||||||
|
- 在工作区的 Agents & API 页面创建API Key
|
||||||
|
- 复制生成的API Key,这是配置所需的关键信息
|
||||||
|
- 接口说明见 [SpecStream文档](https://specstream.ai/search-api)
|
||||||
|
|
||||||
## 配置方式
|
## 配置方式
|
||||||
|
|
||||||
### 方式1. 使用智控台部署(推荐)
|
### 方式1. 使用智控台部署(推荐)
|
||||||
|
|
@ -48,14 +56,14 @@
|
||||||
- 进入"配置角色"页面,选择要配置的智能体
|
- 进入"配置角色"页面,选择要配置的智能体
|
||||||
- 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件
|
- 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件
|
||||||
- 勾选"联网搜索"
|
- 勾选"联网搜索"
|
||||||
- 填入搜索源(`metaso`、`tavily`、`serply`或`outcrawl`),并将对应的`API Key`填入配置项
|
- 填入搜索源(`metaso`、`tavily`、`serply`、`outcrawl`或`specstream`),并将对应的`API Key`填入配置项
|
||||||
- 保存配置,再保存智能体配置
|
- 保存配置,再保存智能体配置
|
||||||
|
|
||||||
### 方式2. 单模块xiaozhi-server部署
|
### 方式2. 单模块xiaozhi-server部署
|
||||||
|
|
||||||
在 `data/.config.yaml` 中配置:
|
在 `data/.config.yaml` 中配置:
|
||||||
|
|
||||||
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily`、`serply` 或 `outcrawl`
|
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily`、`serply`、`outcrawl` 或 `specstream`
|
||||||
- 将申请到的API Key填入 `api_key`
|
- 将申请到的API Key填入 `api_key`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
-- 联网搜索插件新增SpecStream搜索源
|
||||||
|
|
||||||
|
UPDATE `ai_model_provider`
|
||||||
|
SET `fields` = JSON_SET(
|
||||||
|
`fields`,
|
||||||
|
'$[0].label',
|
||||||
|
'搜索源:metaso / tavily / serply / outcrawl / specstream'
|
||||||
|
)
|
||||||
|
WHERE `id` = 'SYSTEM_PLUGIN_WEB_SEARCH';
|
||||||
|
|
@ -767,3 +767,10 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202611021200.sql
|
path: classpath:db/changelog/202611021200.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202611101200
|
||||||
|
author: Specstreamai
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202611101200.sql
|
||||||
|
|
|
||||||
|
|
@ -172,19 +172,20 @@ plugins:
|
||||||
# ragflow知识库id
|
# ragflow知识库id
|
||||||
dataset_ids: ["123456789"]
|
dataset_ids: ["123456789"]
|
||||||
# 联网搜索插件配置
|
# 联网搜索插件配置
|
||||||
# 支持秘塔(metaso)、Tavily、Serply和Outcrawl四个搜索源
|
# 支持秘塔(metaso)、Tavily、Serply、Outcrawl和SpecStream五个搜索源
|
||||||
# 秘塔API Key申请:https://metaso.cn/search-api/api-keys
|
# 秘塔API Key申请:https://metaso.cn/search-api/api-keys
|
||||||
# Tavily API Key申请:https://app.tavily.com/home
|
# Tavily API Key申请:https://app.tavily.com/home
|
||||||
# Serply API Key申请:https://serply.io
|
# Serply API Key申请:https://serply.io
|
||||||
# Outcrawl API Key申请:https://outcrawl.ai
|
# Outcrawl API Key申请:https://outcrawl.ai
|
||||||
|
# SpecStream API Key申请:https://specstream.ai/signup?src=xiaozhi-esp32-server
|
||||||
web_search:
|
web_search:
|
||||||
# 搜索源:metaso / tavily / serply / outcrawl
|
# 搜索源:metaso / tavily / serply / outcrawl / specstream
|
||||||
provider: "metaso"
|
provider: "metaso"
|
||||||
# 工具描述,用于告知LLM何时调用此工具,可根据需要自定义
|
# 工具描述,用于告知LLM何时调用此工具,可根据需要自定义
|
||||||
description: "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。"
|
description: "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。"
|
||||||
# 返回结果数量(默认5)
|
# 返回结果数量(默认5)
|
||||||
max_results: 5
|
max_results: 5
|
||||||
# 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key / Outcrawl API Key
|
# 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key / Outcrawl API Key / SpecStream API Key
|
||||||
api_key: "mk-xxx"
|
api_key: "mk-xxx"
|
||||||
# 声纹识别配置
|
# 声纹识别配置
|
||||||
voiceprint:
|
voiceprint:
|
||||||
|
|
@ -765,7 +766,11 @@ VLLM:
|
||||||
# 开通应用地址:https://console.xfyun.cn/app/myapp
|
# 开通应用地址:https://console.xfyun.cn/app/myapp
|
||||||
# 有免费额度,但也要开通服务,才能获取api_key
|
# 有免费额度,但也要开通服务,才能获取api_key
|
||||||
# 每一个模型都需要单独开通,每一个模型的 api_key 都不同,例如 Lite 模型在 https://console.xfyun.cn/services/cbm 开通
|
# 每一个模型都需要单独开通,每一个模型的 api_key 都不同,例如 Lite 模型在 https://console.xfyun.cn/services/cbm 开通
|
||||||
base_url: https://ark.cn-beijing.volces.com/api/v3
|
# 讯飞星火的 OpenAI 兼容端点,可用模型名(lite / 4.0Ultra 等)见
|
||||||
|
# https://www.xfyun.cn/doc/spark/HTTP调用文档.html
|
||||||
|
# 注意 base_url 必须指向讯飞自己的域名。这里曾误填成火山方舟的
|
||||||
|
# ark.cn-beijing.volces.com,会把讯飞的 api_key 发给火山引擎。
|
||||||
|
base_url: https://spark-api-open.xf-yun.com/v1
|
||||||
model_name: lite
|
model_name: lite
|
||||||
api_key: 你的api_key
|
api_key: 你的api_key
|
||||||
TTS:
|
TTS:
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
# PCM缓冲区
|
# PCM缓冲区
|
||||||
self.pcm_buffer = bytearray()
|
self.pcm_buffer = bytearray()
|
||||||
|
|
||||||
|
# 一句话只发一次句首标记,重试时不能重复发
|
||||||
|
self._tts_first_sent = False
|
||||||
|
|
||||||
def tts_text_priority_thread(self):
|
def tts_text_priority_thread(self):
|
||||||
"""流式文本处理线程"""
|
"""流式文本处理线程"""
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
|
|
@ -90,35 +93,60 @@ class TTSProvider(TTSProviderBase):
|
||||||
self._process_before_stop_play_files()
|
self._process_before_stop_play_files()
|
||||||
|
|
||||||
def to_tts_single_stream(self, text, is_last=False):
|
def to_tts_single_stream(self, text, is_last=False):
|
||||||
try:
|
|
||||||
max_repeat_time = 5
|
|
||||||
original_text = text
|
original_text = text
|
||||||
|
try:
|
||||||
text = MarkdownCleaner.clean_markdown(text)
|
text = MarkdownCleaner.clean_markdown(text)
|
||||||
if self._correct_words_pattern:
|
if self._correct_words_pattern:
|
||||||
text = self._correct_words_pattern.sub(lambda m: self.correct_words[m.group(0)], text)
|
text = self._correct_words_pattern.sub(lambda m: self.correct_words[m.group(0)], text)
|
||||||
try:
|
|
||||||
asyncio.run(self.text_to_speak(text, is_last))
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).warning(
|
|
||||||
f"语音生成失败{5 - max_repeat_time + 1}次: {original_text},错误: {e}"
|
|
||||||
)
|
|
||||||
max_repeat_time -= 1
|
|
||||||
|
|
||||||
if max_repeat_time > 0:
|
# 原来的写法只试一次,而且失败后 max_repeat_time 只减 1(5→4),
|
||||||
|
# 于是 "max_repeat_time > 0" 恒为真 —— 失败也照样打「语音生成成功」。
|
||||||
|
max_repeat_time = 5
|
||||||
|
succeeded = False
|
||||||
|
attempt = 0
|
||||||
|
self._tts_first_sent = False
|
||||||
|
for attempt in range(1, max_repeat_time + 1):
|
||||||
|
error = None
|
||||||
|
try:
|
||||||
|
ok, audio_sent = asyncio.run(self.text_to_speak(text, is_last))
|
||||||
|
except Exception as e:
|
||||||
|
ok, audio_sent = False, False
|
||||||
|
error = e
|
||||||
|
if ok:
|
||||||
|
succeeded = True
|
||||||
|
break
|
||||||
|
if audio_sent:
|
||||||
|
# 音频已经推给设备了,再试一次同一句会被播两遍
|
||||||
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"语音生成失败: {original_text},已推送音频,不再重试"
|
||||||
|
)
|
||||||
|
break
|
||||||
|
suffix = f",错误: {error}" if error else ""
|
||||||
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"语音生成失败{attempt}次: {original_text}{suffix}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if succeeded:
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"语音生成成功: {original_text},重试{5 - max_repeat_time}次"
|
f"语音生成成功: {original_text},重试{attempt - 1}次"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"语音生成失败: {original_text},请检查网络或服务是否正常"
|
f"语音生成失败: {original_text},请检查网络或服务是否正常"
|
||||||
)
|
)
|
||||||
|
# 收尾标记只在这里发一次。text_to_speak 失败时不再自己塞 LAST,
|
||||||
|
# 否则重试成功的音频会排在 LAST 之后,设备根本听不到。
|
||||||
|
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
||||||
finally:
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, is_last):
|
async def text_to_speak(self, text, is_last):
|
||||||
"""流式处理TTS音频,每句只推送一次音频列表"""
|
"""流式处理TTS音频,每句只推送一次音频列表
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple[bool, bool]: (是否合成成功, 是否已经推送过音频帧)
|
||||||
|
音频一旦推给设备就不能重试,否则同一句会被播两遍。
|
||||||
|
"""
|
||||||
payload = {"text": text, "character": self.voice}
|
payload = {"text": text, "character": self.voice}
|
||||||
|
|
||||||
frame_bytes = int(
|
frame_bytes = int(
|
||||||
|
|
@ -128,6 +156,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
/ 1000
|
/ 1000
|
||||||
* 2
|
* 2
|
||||||
) # 16-bit = 2 bytes
|
) # 16-bit = 2 bytes
|
||||||
|
audio_sent = False
|
||||||
try:
|
try:
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.post(
|
async with session.post(
|
||||||
|
|
@ -138,11 +167,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"TTS请求失败: {resp.status}, {await resp.text()}"
|
f"TTS请求失败: {resp.status}, {await resp.text()}"
|
||||||
)
|
)
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
return False, False
|
||||||
return
|
|
||||||
|
|
||||||
self.pcm_buffer.clear()
|
self.pcm_buffer.clear()
|
||||||
|
if not self._tts_first_sent:
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
||||||
|
self._tts_first_sent = True
|
||||||
|
|
||||||
# 处理音频流数据
|
# 处理音频流数据
|
||||||
async for chunk in resp.content.iter_any():
|
async for chunk in resp.content.iter_any():
|
||||||
|
|
@ -161,6 +191,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
end_of_stream=False,
|
end_of_stream=False,
|
||||||
callback=self.handle_opus
|
callback=self.handle_opus
|
||||||
)
|
)
|
||||||
|
audio_sent = True
|
||||||
|
|
||||||
# flush 剩余不足一帧的数据
|
# flush 剩余不足一帧的数据
|
||||||
if self.pcm_buffer:
|
if self.pcm_buffer:
|
||||||
|
|
@ -170,14 +201,16 @@ class TTSProvider(TTSProviderBase):
|
||||||
callback=self.handle_opus
|
callback=self.handle_opus
|
||||||
)
|
)
|
||||||
self.pcm_buffer.clear()
|
self.pcm_buffer.clear()
|
||||||
|
audio_sent = True
|
||||||
|
|
||||||
# 如果是最后一段,输出音频获取完毕
|
# 如果是最后一段,输出音频获取完毕
|
||||||
if is_last:
|
if is_last:
|
||||||
self._process_before_stop_play_files()
|
self._process_before_stop_play_files()
|
||||||
|
|
||||||
|
return True, audio_sent
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
return False, audio_sent
|
||||||
|
|
||||||
def audio_to_pcm_data_stream(
|
def audio_to_pcm_data_stream(
|
||||||
self, audio_file_path, callback=None
|
self, audio_file_path, callback=None
|
||||||
|
|
|
||||||
|
|
@ -85,6 +85,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
# PCM缓冲区
|
# PCM缓冲区
|
||||||
self.pcm_buffer = bytearray()
|
self.pcm_buffer = bytearray()
|
||||||
|
|
||||||
|
# 一句话只发一次句首标记,重试时不能重复发
|
||||||
|
self._tts_first_sent = False
|
||||||
|
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn):
|
||||||
"""初始化音频通道,并根据conn.sample_rate更新配置"""
|
"""初始化音频通道,并根据conn.sample_rate更新配置"""
|
||||||
# 调用父类方法
|
# 调用父类方法
|
||||||
|
|
@ -146,35 +149,60 @@ class TTSProvider(TTSProviderBase):
|
||||||
self._process_before_stop_play_files()
|
self._process_before_stop_play_files()
|
||||||
|
|
||||||
def to_tts_single_stream(self, text, is_last=False):
|
def to_tts_single_stream(self, text, is_last=False):
|
||||||
try:
|
|
||||||
max_repeat_time = 5
|
|
||||||
original_text = text
|
original_text = text
|
||||||
|
try:
|
||||||
text = MarkdownCleaner.clean_markdown(text)
|
text = MarkdownCleaner.clean_markdown(text)
|
||||||
if self._correct_words_pattern:
|
if self._correct_words_pattern:
|
||||||
text = self._correct_words_pattern.sub(lambda m: self.correct_words[m.group(0)], text)
|
text = self._correct_words_pattern.sub(lambda m: self.correct_words[m.group(0)], text)
|
||||||
try:
|
|
||||||
asyncio.run(self.text_to_speak(text, is_last))
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).warning(
|
|
||||||
f"语音生成失败{5 - max_repeat_time + 1}次: {original_text},错误: {e}"
|
|
||||||
)
|
|
||||||
max_repeat_time -= 1
|
|
||||||
|
|
||||||
if max_repeat_time > 0:
|
# 原来的写法只试一次,而且失败后 max_repeat_time 只减 1(5→4),
|
||||||
|
# 于是 "max_repeat_time > 0" 恒为真 —— 失败也照样打「语音生成成功」。
|
||||||
|
max_repeat_time = 5
|
||||||
|
succeeded = False
|
||||||
|
attempt = 0
|
||||||
|
self._tts_first_sent = False
|
||||||
|
for attempt in range(1, max_repeat_time + 1):
|
||||||
|
error = None
|
||||||
|
try:
|
||||||
|
ok, audio_sent = asyncio.run(self.text_to_speak(text, is_last))
|
||||||
|
except Exception as e:
|
||||||
|
ok, audio_sent = False, False
|
||||||
|
error = e
|
||||||
|
if ok:
|
||||||
|
succeeded = True
|
||||||
|
break
|
||||||
|
if audio_sent:
|
||||||
|
# 音频已经推给设备了,再试一次同一句会被播两遍
|
||||||
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"语音生成失败: {original_text},已推送音频,不再重试"
|
||||||
|
)
|
||||||
|
break
|
||||||
|
suffix = f",错误: {error}" if error else ""
|
||||||
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"语音生成失败{attempt}次: {original_text}{suffix}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if succeeded:
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"语音生成成功: {original_text},重试{5 - max_repeat_time}次"
|
f"语音生成成功: {original_text},重试{attempt - 1}次"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"语音生成失败: {original_text},请检查网络或服务是否正常"
|
f"语音生成失败: {original_text},请检查网络或服务是否正常"
|
||||||
)
|
)
|
||||||
|
# 收尾标记只在这里发一次。text_to_speak 失败时不再自己塞 LAST,
|
||||||
|
# 否则重试成功的音频会排在 LAST 之后,设备根本听不到。
|
||||||
|
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
||||||
finally:
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, is_last):
|
async def text_to_speak(self, text, is_last):
|
||||||
"""流式处理TTS音频,每句只推送一次音频列表"""
|
"""流式处理TTS音频,每句只推送一次音频列表
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple[bool, bool]: (是否合成成功, 是否已经推送过音频帧)
|
||||||
|
音频一旦推给设备就不能重试,否则同一句会被播两遍。
|
||||||
|
"""
|
||||||
payload = {
|
payload = {
|
||||||
"model": self.model,
|
"model": self.model,
|
||||||
"text": text,
|
"text": text,
|
||||||
|
|
@ -195,6 +223,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
/ 1000
|
/ 1000
|
||||||
* 2
|
* 2
|
||||||
) # 16-bit = 2 bytes
|
) # 16-bit = 2 bytes
|
||||||
|
audio_sent = False
|
||||||
try:
|
try:
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.post(
|
async with session.post(
|
||||||
|
|
@ -208,11 +237,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"TTS请求失败: {resp.status}, {await resp.text()}"
|
f"TTS请求失败: {resp.status}, {await resp.text()}"
|
||||||
)
|
)
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
return False, False
|
||||||
return
|
|
||||||
|
|
||||||
self.pcm_buffer.clear()
|
self.pcm_buffer.clear()
|
||||||
|
if not self._tts_first_sent:
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
||||||
|
self._tts_first_sent = True
|
||||||
|
|
||||||
# 处理音频流数据
|
# 处理音频流数据
|
||||||
buffer = b""
|
buffer = b""
|
||||||
|
|
@ -246,8 +276,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"TTS请求失败, 错误码:{status_code}, 错误消息:{status_msg}"
|
f"TTS请求失败, 错误码:{status_code}, 错误消息:{status_msg}"
|
||||||
)
|
)
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
return False, audio_sent
|
||||||
return
|
|
||||||
|
|
||||||
status = data.get("data", {}).get("status", 1)
|
status = data.get("data", {}).get("status", 1)
|
||||||
audio_hex = data.get("data", {}).get("audio")
|
audio_hex = data.get("data", {}).get("audio")
|
||||||
|
|
@ -268,6 +297,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
self.opus_encoder.encode_pcm_to_opus_stream(
|
||||||
frame, end_of_stream=False, callback=self.handle_opus
|
frame, end_of_stream=False, callback=self.handle_opus
|
||||||
)
|
)
|
||||||
|
audio_sent = True
|
||||||
|
|
||||||
# flush 剩余不足一帧的数据
|
# flush 剩余不足一帧的数据
|
||||||
if self.pcm_buffer:
|
if self.pcm_buffer:
|
||||||
|
|
@ -277,14 +307,16 @@ class TTSProvider(TTSProviderBase):
|
||||||
callback=self.handle_opus,
|
callback=self.handle_opus,
|
||||||
)
|
)
|
||||||
self.pcm_buffer.clear()
|
self.pcm_buffer.clear()
|
||||||
|
audio_sent = True
|
||||||
|
|
||||||
# 如果是最后一段,输出音频获取完毕
|
# 如果是最后一段,输出音频获取完毕
|
||||||
if is_last:
|
if is_last:
|
||||||
self._process_before_stop_play_files()
|
self._process_before_stop_play_files()
|
||||||
|
|
||||||
|
return True, audio_sent
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
return False, audio_sent
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""资源清理"""
|
"""资源清理"""
|
||||||
|
|
|
||||||
|
|
@ -197,6 +197,58 @@ async def _search_outcrawl(api_key: str, query: str, max_results: int) -> str:
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
async def _search_specstream(api_key: str, query: str, max_results: int) -> str:
|
||||||
|
"""调用SpecStream搜索API"""
|
||||||
|
url = "https://api.specstream.ai/v1/web-search"
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
"User-Agent": "xiaozhi-esp32-server",
|
||||||
|
}
|
||||||
|
# 单次10条以内按基础价计费,所以num按1到10截取
|
||||||
|
params = {"q": query, "num": max(1, min(max_results, 10))}
|
||||||
|
logger.bind(tag=TAG).debug(f"SpecStream搜索请求 | URL: {url} | params: {params}")
|
||||||
|
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
|
||||||
|
response = await client.get(url, params=params, headers=headers)
|
||||||
|
data = response.json()
|
||||||
|
logger.bind(tag=TAG).debug(f"SpecStream搜索响应 | status: {response.status_code}")
|
||||||
|
|
||||||
|
if response.status_code != 200:
|
||||||
|
# 错误信封为 {"error": {"code": "...", "message": "...", "details": {}}}
|
||||||
|
error = data.get("error", {}) if isinstance(data, dict) else {}
|
||||||
|
code = error.get("code", "") if isinstance(error, dict) else ""
|
||||||
|
detail = error.get("message", "") if isinstance(error, dict) else ""
|
||||||
|
logger.bind(tag=TAG).error(
|
||||||
|
f"SpecStream搜索失败 | status: {response.status_code} | code: {code} | detail: {detail}"
|
||||||
|
)
|
||||||
|
if code in ("missing_api_key", "invalid_token"):
|
||||||
|
return "联网搜索请求失败,请检查API Key是否正确。"
|
||||||
|
if code in ("insufficient_balance", "payment_required"):
|
||||||
|
return "联网搜索额度已用完,请检查SpecStream账户余额。"
|
||||||
|
# 其余code(rate_limited、capacity、bad_request等)统一引导重试
|
||||||
|
return "联网搜索请求失败,请稍后重试。"
|
||||||
|
|
||||||
|
page = data.get("data") or {}
|
||||||
|
sources = page.get("sources", [])
|
||||||
|
if not sources:
|
||||||
|
return "未找到相关搜索结果。"
|
||||||
|
|
||||||
|
lines = ["【联网搜索结果】"]
|
||||||
|
answer = (page.get("answer") or {}).get("value", "")
|
||||||
|
if answer:
|
||||||
|
lines.append(f"总结:{answer}")
|
||||||
|
for i, item in enumerate(sources[:max_results], 1):
|
||||||
|
title = item.get("title") or "无标题"
|
||||||
|
snippet = item.get("snippet", "")
|
||||||
|
date = item.get("published") or ""
|
||||||
|
lines.append(f"{i}. 标题:{title}")
|
||||||
|
if date:
|
||||||
|
lines.append(f" 日期:{date}")
|
||||||
|
if snippet:
|
||||||
|
lines.append(f" 摘要:{snippet}")
|
||||||
|
|
||||||
|
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 被调用 | query={query}")
|
||||||
|
|
@ -225,6 +277,8 @@ async def web_search(conn: "ConnectionHandler", query: str = None):
|
||||||
result_text = await _search_serply(api_key, query, max_results)
|
result_text = await _search_serply(api_key, query, max_results)
|
||||||
elif provider == "outcrawl":
|
elif provider == "outcrawl":
|
||||||
result_text = await _search_outcrawl(api_key, query, max_results)
|
result_text = await _search_outcrawl(api_key, query, max_results)
|
||||||
|
elif provider == "specstream":
|
||||||
|
result_text = await _search_specstream(api_key, query, max_results)
|
||||||
else:
|
else:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
Action.REQLLM,
|
Action.REQLLM,
|
||||||
|
|
|
||||||
81
main/xiaozhi-server/tests/config/test_provider_endpoints.py
Normal file
81
main/xiaozhi-server/tests/config/test_provider_endpoints.py
Normal file
|
|
@ -0,0 +1,81 @@
|
||||||
|
"""供应器默认端点自检:防止不同 provider 的 base_url 被复制粘贴串台。
|
||||||
|
|
||||||
|
背景:``config.yaml`` 里每个 provider 的 ``base_url`` / ``url`` 都是照抄对应
|
||||||
|
厂商文档填的,很容易从相邻的 provider 直接复制粘贴。真实案例:``VLLM``
|
||||||
|
段的 ``XunfeiSparkLLM`` 抄了上面 ``LLM.DoubaoLLM`` 的火山方舟地址
|
||||||
|
(ark.cn-beijing.volces.com),选它做视觉模型时会把讯飞的 api_key 发给
|
||||||
|
火山引擎,而 ``model_name: lite`` 在那个端点上并不存在。
|
||||||
|
|
||||||
|
这里用一张「配置块 -> 端点主机名」的对照表把这类串台钉死。新增 provider
|
||||||
|
时顺手往表里加一行即可。
|
||||||
|
|
||||||
|
注意:本用例读的是仓库里**出厂的** ``config.yaml``,不是用户
|
||||||
|
``data/.config.yaml`` 合并后的结果 —— 要守的就是这份出厂默认值。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from config.config_loader import get_project_dir, read_config
|
||||||
|
|
||||||
|
|
||||||
|
# (模块段, provider 名, 端点主机名里必须出现的片段)
|
||||||
|
PROVIDER_ENDPOINT_HOSTS = [
|
||||||
|
("LLM", "AliLLM", "dashscope.aliyuncs.com"),
|
||||||
|
("LLM", "AliAppLLM", "dashscope.aliyuncs.com"),
|
||||||
|
("LLM", "ChatGLMLLM", "bigmodel.cn"),
|
||||||
|
("LLM", "DeepSeekLLM", "deepseek.com"),
|
||||||
|
("LLM", "DifyLLM", "dify.ai"),
|
||||||
|
("LLM", "DoubaoLLM", "volces.com"),
|
||||||
|
("LLM", "VolcesAiGatewayLLM", "volces.com"),
|
||||||
|
("VLLM", "ChatGLMVLLM", "bigmodel.cn"),
|
||||||
|
("VLLM", "QwenVLVLLM", "dashscope.aliyuncs.com"),
|
||||||
|
("VLLM", "XunfeiSparkLLM", "xf-yun.com"),
|
||||||
|
("ASR", "OpenaiASR", "api.openai.com"),
|
||||||
|
("ASR", "GroqASR", "api.groq.com"),
|
||||||
|
("ASR", "Qwen3ASRFlash", "dashscope.aliyuncs.com"),
|
||||||
|
("TTS", "OpenAITTS", "api.openai.com"),
|
||||||
|
("TTS", "DoubaoTTS", "bytedance.com"),
|
||||||
|
("TTS", "TTS302AI", "302ai.cn"),
|
||||||
|
("TTS", "VolcesAiGatewayTTS", "volces.com"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def default_config():
|
||||||
|
"""仓库里出厂的默认配置(未经用户 data/.config.yaml 覆盖)。"""
|
||||||
|
return read_config(get_project_dir() + "config.yaml")
|
||||||
|
|
||||||
|
|
||||||
|
def _endpoint_of(block: dict) -> str:
|
||||||
|
"""取 provider 配置块里生效的端点。
|
||||||
|
|
||||||
|
顺序与运行时一致:``core/providers/vllm/openai.py`` 和
|
||||||
|
``core/providers/llm/openai/openai.py`` 都是 ``base_url`` 优先、
|
||||||
|
``url`` 兜底;部分 TTS 用 ``api_url``。
|
||||||
|
"""
|
||||||
|
return block.get("base_url") or block.get("url") or block.get("api_url") or ""
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"module,provider,expected_host",
|
||||||
|
PROVIDER_ENDPOINT_HOSTS,
|
||||||
|
ids=[f"{m}.{p}" for m, p, _ in PROVIDER_ENDPOINT_HOSTS],
|
||||||
|
)
|
||||||
|
def test_provider_endpoint_matches_platform(
|
||||||
|
default_config, module, provider, expected_host
|
||||||
|
):
|
||||||
|
"""provider 的端点必须落在它自己那家厂商的域名下。"""
|
||||||
|
block = default_config.get(module, {}).get(provider)
|
||||||
|
assert block is not None, f"config.yaml 里找不到 {module}.{provider} 配置块"
|
||||||
|
|
||||||
|
endpoint = _endpoint_of(block)
|
||||||
|
assert endpoint, f"{module}.{provider} 没有配置 base_url / url / api_url"
|
||||||
|
|
||||||
|
host = urlparse(endpoint).netloc
|
||||||
|
assert expected_host in host, (
|
||||||
|
f"{module}.{provider} 的端点 {endpoint!r} 解析出的主机是 {host!r},"
|
||||||
|
f"与平台不符(期望包含 {expected_host!r})—— 疑似从别的 provider 复制粘贴时带串了"
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,152 @@
|
||||||
|
"""流式 TTS 的重试:失败要真的重试,日志也不能把失败写成成功。
|
||||||
|
|
||||||
|
index_stream / minimax_httpstream 原来的 to_tts_single_stream 只试一次;
|
||||||
|
失败后 max_repeat_time 只减 1(5→4),于是 `if max_repeat_time > 0` 恒为真,
|
||||||
|
失败也照样打「语音生成成功」,真正的「语音生成失败」分支永远走不到。
|
||||||
|
"""
|
||||||
|
import queue
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from core.providers.tts import index_stream, minimax_httpstream
|
||||||
|
from core.providers.tts.dto.dto import SentenceType
|
||||||
|
|
||||||
|
PROVIDERS = [index_stream.TTSProvider, minimax_httpstream.TTSProvider]
|
||||||
|
|
||||||
|
# 日志里区分成功/失败的固定文案
|
||||||
|
SUCCESS_LOG = "语音生成成功"
|
||||||
|
FAILURE_LOG = "请检查网络或服务是否正常"
|
||||||
|
|
||||||
|
|
||||||
|
def _make_provider(cls):
|
||||||
|
"""只填 to_tts_single_stream 用得到的字段。
|
||||||
|
|
||||||
|
绕开 __init__:它会去建 opus 编码器,而编解码依赖系统里的 libopus,
|
||||||
|
单测里根本用不上。
|
||||||
|
"""
|
||||||
|
provider = object.__new__(cls)
|
||||||
|
provider.tts_audio_queue = queue.Queue()
|
||||||
|
provider.correct_words = {}
|
||||||
|
provider._correct_words_pattern = None
|
||||||
|
provider._tts_first_sent = False
|
||||||
|
return provider
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _capture_logs():
|
||||||
|
"""抓 loguru 的输出。"""
|
||||||
|
messages = []
|
||||||
|
handler_id = logger.add(
|
||||||
|
lambda msg: messages.append(str(msg)), level="DEBUG", format="{message}"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
yield messages
|
||||||
|
finally:
|
||||||
|
logger.remove(handler_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _drain(provider):
|
||||||
|
items = []
|
||||||
|
while not provider.tts_audio_queue.empty():
|
||||||
|
items.append(provider.tts_audio_queue.get())
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _stub(provider, results):
|
||||||
|
"""把 text_to_speak 换成按 results 依次返回的桩,并记录调用次数。
|
||||||
|
|
||||||
|
results 里的每一项要么是 (ok, audio_sent),要么是 Exception(直接抛出)。
|
||||||
|
"""
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
async def fake_text_to_speak(text, is_last):
|
||||||
|
calls.append(text)
|
||||||
|
result = results[min(len(calls) - 1, len(results) - 1)]
|
||||||
|
if isinstance(result, Exception):
|
||||||
|
raise result
|
||||||
|
return result
|
||||||
|
|
||||||
|
provider.text_to_speak = fake_text_to_speak
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", PROVIDERS)
|
||||||
|
def test_transient_failure_is_retried(cls):
|
||||||
|
"""前两次失败、第三次成功:必须真的重试到成功。"""
|
||||||
|
provider = _make_provider(cls)
|
||||||
|
calls = _stub(provider, [(False, False), (False, False), (True, True)])
|
||||||
|
|
||||||
|
with _capture_logs() as messages:
|
||||||
|
provider.to_tts_single_stream("今天天气怎么样")
|
||||||
|
|
||||||
|
assert len(calls) == 3, "失败后应该重试,而不是只试一次"
|
||||||
|
assert any(SUCCESS_LOG in m for m in messages), "重试成功后应该打「语音生成成功」"
|
||||||
|
assert not any(FAILURE_LOG in m for m in messages), "最终成功了不该再打「语音生成失败」"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", PROVIDERS)
|
||||||
|
def test_failure_is_logged_as_failure(cls):
|
||||||
|
"""一直失败:日志必须是失败,不能反着写成成功。"""
|
||||||
|
provider = _make_provider(cls)
|
||||||
|
calls = _stub(provider, [(False, False)])
|
||||||
|
|
||||||
|
with _capture_logs() as messages:
|
||||||
|
provider.to_tts_single_stream("今天天气怎么样")
|
||||||
|
|
||||||
|
assert len(calls) == 5, "最多重试 5 次"
|
||||||
|
assert any(FAILURE_LOG in m for m in messages), "失败必须打「语音生成失败」"
|
||||||
|
assert not any(SUCCESS_LOG in m for m in messages), "失败不能打「语音生成成功」"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", PROVIDERS)
|
||||||
|
def test_exception_is_retried_and_logged_as_failure(cls):
|
||||||
|
"""text_to_speak 抛异常时同样要重试,并且按失败记账。"""
|
||||||
|
provider = _make_provider(cls)
|
||||||
|
calls = _stub(provider, [RuntimeError("连接超时")])
|
||||||
|
|
||||||
|
with _capture_logs() as messages:
|
||||||
|
provider.to_tts_single_stream("今天天气怎么样")
|
||||||
|
|
||||||
|
assert len(calls) == 5
|
||||||
|
assert any(FAILURE_LOG in m for m in messages)
|
||||||
|
assert not any(SUCCESS_LOG in m for m in messages)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", PROVIDERS)
|
||||||
|
def test_no_retry_once_audio_was_pushed(cls):
|
||||||
|
"""音频已经推给设备就不能再试,否则同一句会被播两遍。"""
|
||||||
|
provider = _make_provider(cls)
|
||||||
|
calls = _stub(provider, [(False, True)])
|
||||||
|
|
||||||
|
with _capture_logs() as messages:
|
||||||
|
provider.to_tts_single_stream("今天天气怎么样")
|
||||||
|
|
||||||
|
assert len(calls) == 1, "音频已经推出去就不该重试"
|
||||||
|
assert any(FAILURE_LOG in m for m in messages)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", PROVIDERS)
|
||||||
|
def test_last_marker_sent_once_after_retries_exhausted(cls):
|
||||||
|
"""失败收尾的 LAST 标记只发一次,不能每次重试都发。"""
|
||||||
|
provider = _make_provider(cls)
|
||||||
|
_stub(provider, [(False, False)])
|
||||||
|
|
||||||
|
provider.to_tts_single_stream("今天天气怎么样")
|
||||||
|
|
||||||
|
items = _drain(provider)
|
||||||
|
lasts = [i for i in items if i[0] is SentenceType.LAST]
|
||||||
|
assert len(lasts) == 1, f"LAST 标记应该只发一次,实际 {len(lasts)} 次"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", PROVIDERS)
|
||||||
|
def test_no_last_marker_when_retry_succeeds(cls):
|
||||||
|
"""重试成功时不能发 LAST,否则成功的音频会排在 LAST 后面听不到。"""
|
||||||
|
provider = _make_provider(cls)
|
||||||
|
_stub(provider, [(False, False), (True, True)])
|
||||||
|
|
||||||
|
provider.to_tts_single_stream("今天天气怎么样")
|
||||||
|
|
||||||
|
items = _drain(provider)
|
||||||
|
assert not [i for i in items if i[0] is SentenceType.LAST]
|
||||||
|
|
@ -0,0 +1,128 @@
|
||||||
|
"""Tests for the SpecStream source of the web_search plugin.
|
||||||
|
|
||||||
|
The HTTP layer is replaced with a fake client and every request is recorded.
|
||||||
|
Nothing here touches the network.
|
||||||
|
"""
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from plugins_func.functions import web_search as web_search_module
|
||||||
|
from plugins_func.register import Action
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResponse:
|
||||||
|
def __init__(self, status_code=200, payload=None):
|
||||||
|
self.status_code = status_code
|
||||||
|
self.payload = payload
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self.payload
|
||||||
|
|
||||||
|
|
||||||
|
class FakeAsyncClient:
|
||||||
|
"""Stands in for httpx.AsyncClient and records what was requested."""
|
||||||
|
|
||||||
|
requests = []
|
||||||
|
response = None
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *exc_info):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, url, params=None, headers=None):
|
||||||
|
FakeAsyncClient.requests.append({"url": url, "params": params, "headers": headers})
|
||||||
|
return FakeAsyncClient.response
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_http(monkeypatch):
|
||||||
|
"""Replace httpx.AsyncClient with the recording fake."""
|
||||||
|
FakeAsyncClient.requests = []
|
||||||
|
FakeAsyncClient.response = FakeResponse(payload={"data": {"sources": []}})
|
||||||
|
monkeypatch.setattr(httpx, "AsyncClient", FakeAsyncClient)
|
||||||
|
return FakeAsyncClient
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConn:
|
||||||
|
def __init__(self, web_search_config):
|
||||||
|
self.config = {"plugins": {"web_search": web_search_config}}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_specstream_sends_bearer_key_and_num(fake_http):
|
||||||
|
await web_search_module._search_specstream("ss-key", "上海天气", 5)
|
||||||
|
|
||||||
|
[request] = fake_http.requests
|
||||||
|
assert request["url"] == "https://api.specstream.ai/v1/web-search"
|
||||||
|
assert request["params"] == {"q": "上海天气", "num": 5}
|
||||||
|
assert request["headers"]["Authorization"] == "Bearer ss-key"
|
||||||
|
assert request["headers"]["User-Agent"] == "xiaozhi-esp32-server"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("max_results", "num"), [(0, 1), (50, 10)])
|
||||||
|
async def test_specstream_clamps_num(fake_http, max_results, num):
|
||||||
|
await web_search_module._search_specstream("ss-key", "q", max_results)
|
||||||
|
|
||||||
|
assert fake_http.requests[0]["params"]["num"] == num
|
||||||
|
|
||||||
|
|
||||||
|
async def test_specstream_formats_answer_titles_dates_and_snippets_without_urls(fake_http):
|
||||||
|
fake_http.response = FakeResponse(
|
||||||
|
payload={
|
||||||
|
"data": {
|
||||||
|
"answer": {"value": "多云", "page": "https://a.example/1"},
|
||||||
|
"sources": [
|
||||||
|
{"url": "https://a.example/1", "title": "标题一", "snippet": "摘要一", "published": "2026-11-10"},
|
||||||
|
{"url": "https://a.example/2", "title": "", "snippet": "", "published": None},
|
||||||
|
{"url": "https://a.example/3", "title": "标题三", "snippet": "摘要三"},
|
||||||
|
],
|
||||||
|
"price_usd": 0.005,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await web_search_module._search_specstream("ss-key", "q", 2)
|
||||||
|
|
||||||
|
assert result == "【联网搜索结果】\n总结:多云\n1. 标题:标题一\n 日期:2026-11-10\n 摘要:摘要一\n2. 标题:无标题"
|
||||||
|
assert "https://" not in result
|
||||||
|
|
||||||
|
|
||||||
|
async def test_specstream_empty_sources(fake_http):
|
||||||
|
fake_http.response = FakeResponse(payload={"data": {"answer": None, "sources": []}})
|
||||||
|
|
||||||
|
assert await web_search_module._search_specstream("ss-key", "q", 3) == "未找到相关搜索结果。"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("status", "code", "message"),
|
||||||
|
[
|
||||||
|
(401, "invalid_token", "联网搜索请求失败,请检查API Key是否正确。"),
|
||||||
|
(401, "missing_api_key", "联网搜索请求失败,请检查API Key是否正确。"),
|
||||||
|
(402, "insufficient_balance", "联网搜索额度已用完,请检查SpecStream账户余额。"),
|
||||||
|
(429, "rate_limited", "联网搜索请求失败,请稍后重试。"),
|
||||||
|
(503, "capacity", "联网搜索请求失败,请稍后重试。"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_specstream_error_code(fake_http, status, code, message):
|
||||||
|
fake_http.response = FakeResponse(
|
||||||
|
status_code=status, payload={"error": {"code": code, "message": "denied", "details": {}}}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert await web_search_module._search_specstream("ss-key", "q", 3) == message
|
||||||
|
|
||||||
|
|
||||||
|
async def test_web_search_dispatches_to_specstream(fake_http):
|
||||||
|
fake_http.response = FakeResponse(
|
||||||
|
payload={"data": {"answer": None, "sources": [{"url": "https://a.example", "title": "T", "snippet": "S"}]}}
|
||||||
|
)
|
||||||
|
conn = FakeConn({"provider": "SpecStream", "api_key": "ss-key", "max_results": 3})
|
||||||
|
|
||||||
|
response = await web_search_module.web_search(conn, "q")
|
||||||
|
|
||||||
|
assert response.action == Action.REQLLM
|
||||||
|
assert response.result == "【联网搜索结果】\n1. 标题:T\n 摘要:S"
|
||||||
|
assert fake_http.requests[0]["params"] == {"q": "q", "num": 3}
|
||||||
Loading…
Reference in a new issue