Compare commits

...

7 commits

Author SHA1 Message Date
Lakzmy123
0f56f2c127
Merge 79fd094b52 into 61a8c04477 2026-11-16 15:39:32 +08:00
wengzh
61a8c04477
feat(web_search): 新增 SpecStream 搜索源 (#3560)
Some checks failed
Tests / Python (xiaozhi-server) (push) Successful in 10m44s
Tests / Java (manager-api) (push) Failing after 30s
Tests / Vue (manager-web) (push) Successful in 11m40s
* feat(web_search): 新增SpecStream搜索源

* docs(web_search): SpecStream API Key申请链接指向注册页

* docs: 更新SpecStream搜索的免费额度信息

---------

Co-authored-by: Tarek Etman <tarek@specstream.ai>
2026-11-16 14:53:37 +08:00
wengzh
b545623b38
Merge pull request #3561 from xinnan-tech/py-test-mem
Py test mem
2026-11-16 14:52:51 +08:00
Sakura-RanChen
63e2bcec8a revert(config): 移除 mem_report_only 出厂配置块,维持单模块 fail-fast 契约
回退 #3547 的核心改动。
mem_report_only 仅在智控台模式下有意义:选项及配置块由 manager-api数据库下发,不依赖本地 config.yaml。
2026-11-13 17:42:16 +08:00
zhenglieAllen
c74a6aaa68
fix(config): 修正 XunfeiSparkLLM 的 base_url 误填成火山方舟地址 (#3546)
现象:把 selected_module.VLLM 设为 XunfeiSparkLLM 后,视觉理解请求全部失败
(鉴权失败或 404),而且讯飞的 api_key 会被发到火山引擎。

原因:config.yaml 里 VLLM.XunfeiSparkLLM.base_url 填的是
https://ark.cn-beijing.volces.com/api/v3 —— 那是上面 LLM.DoubaoLLM 的火山
方舟地址,疑似复制粘贴时带串了。core/providers/vllm/openai.py 取端点时
base_url 优先于 url,所以这个值会直接生效;配套的 model_name: lite 是讯飞
的模型名,在火山方舟上并不存在。

改法:base_url 改成讯飞星火官方 OpenAI 兼容端点
https://spark-api-open.xf-yun.com/v1,并在注释里写明端点与模型名的出处。

测试:新增 tests/config/test_provider_endpoints.py,用一张「provider ->
端点主机名」对照表把这类串台钉死。修复前该用例失败,修复后通过。

Co-authored-by: Allen <zljtx2008@gmail.com>
2026-11-13 16:51:00 +08:00
zhenglieAllen
0d7180d898
fix(config): 给 mem_report_only 补上 Memory 配置块 (#3547)
* fix(config): 给 mem_report_only 补上 Memory 配置块

现象
把 selected_module.Memory 设成 mem_report_only 后,服务在连接初始化阶段
直接崩:

    KeyError: 'mem_report_only'

原因
core/providers/memory/mem_report_only/ 下有完整的 provider 实现,
core/connection.py 的 _initialize_memory 里也显式处理了它
(`if memory_type == "nomem" or memory_type == "mem_report_only"`),
但 config.yaml 的 Memory 段只配了 mem0ai / powermem / nomem /
mem_local_short 四项,没有 mem_report_only。

而 core/connection.py 取配置的方式是直接下标:

    memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]]["type"]

于是只要在 selected_module 里选了 mem_report_only,这个下标就取不到,
连接初始化阶段 KeyError。data/.config.yaml 那边也是整段替换
(self.config["Memory"] = private_config["Memory"]),用户光改
selected_module 而不重复声明一遍 Memory 段,一样会炸。

改法
在 config.yaml 的 Memory 段补上 mem_report_only 配置块(type:
mem_report_only),让出厂配置自洽 —— 选了就能直接用,不需要用户自己
再补一段配置。

测试
新增 tests/config/test_provider_registry.py,钉死两条不变量:
- selected_module 里选中的 provider 必须在对应配置段里存在(防启动期 KeyError);
- 每个 provider 段的每个键,type 字段都必须指向真实存在的实现
  (防「配置有、实现没有」);
- Memory 这类一一对应的模块,实现里有的 provider 配置里必须有(防本次
  这种「实现有、配置没有」)。

修复前 test_every_implemented_provider_is_configured[Memory] 失败,
修复后通过。本地全量:5 failed / 99 passed / 33 skipped / 8 errors,
失败项与改动前完全一致(本地缺 portalocker / pytest-asyncio / edge_tts,
CI 由 requirements.txt 提供),无回归。

* docs(readme): 组件列表补齐 mem_report_only 与科大讯飞视觉模型

现象
README 的「本项目支持的平台/组件列表」有两处和实际出厂配置对不上:

1. VLLM 视觉模型表只列了「阿里百炼、智谱ChatGLMVLLM」,但 config.yaml 的
   VLLM 段出厂就带了 XunfeiSparkLLM(讯飞星火)这个 provider。
2. Memory 记忆存储表只列了 mem0ai / powermem / mem_local_short / nomem,
   没有 mem_report_only —— 而 core/providers/memory/mem_report_only/ 里有
   实现,core/connection.py 里也显式处理了它。

原因
这两个表是手工维护的,新增 provider 时没有同步。VLLM 段的讯飞星火尤其
隐蔽:它的 base_url 还被误填成了火山方舟的地址(ark.cn-beijing.volces.com),
看起来像是没在用,于是没人往表里补。

改法
6 份 README(README.md + docs/readme/ 下的 en/de/es/vi/pt_BR)同步更新:

- VLLM 视觉模型表的「支持平台」列补上科大讯飞 / iFLYTEK。免费平台列不动 ——
  讯飞星火虽有免费额度,但每个模型要单独开通服务后才能用,不属于开箱免费。
- Memory 记忆存储表补上 mem_report_only 一行(使用方式「仅上报」,
  备注「只上报聊天记录,不做记忆总结」,取自 provider 自身的 docstring)。

测试
纯文档改动,无代码路径变化。本次一并把 VLLM 表和 Memory 表跟 config.yaml
的实际内容对齐,避免再出现「文档列的组件在配置里选不到」的情况。

---------

Co-authored-by: Allen <zljtx2008@gmail.com>
2026-11-13 16:31:17 +08:00
lkm
79fd094b52 fix(knowledge): 意图漏召回时增加知识库兜底检索 (#3555) 2026-11-10 17:34:39 +08:00
17 changed files with 722 additions and 24 deletions

View file

@ -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 | 仅上报 | 免费 | 只上报聊天记录,不做记忆总结 |
--- ---

View file

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

View file

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

View file

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

View file

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

View file

@ -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ớ |
--- ---

View file

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

View file

@ -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';

View file

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

View file

@ -165,6 +165,12 @@ plugins:
search_from_ragflow: search_from_ragflow:
# 知识库的描述信息,方便大语言模型知道什么时候调用 # 知识库的描述信息,方便大语言模型知道什么时候调用
description: "当用户问xxx时,调用本方法,使用知识库中的信息回答问题" description: "当用户问xxx时,调用本方法,使用知识库中的信息回答问题"
# 意图识别判定为普通聊天时的知识库兜底检索。
# 描述无法穷举库内所有主题,开启后即使意图识别没选中知识库,
# 也会用用户问题真实检索一次,命中阈值内的内容就改用知识库回答
fallback_enabled: true
# 兜底检索的最低相似度(0~1),低于该值的片段直接丢弃
fallback_min_similarity: 0.5
# ragflow接口配置 # ragflow接口配置
base_url: "http://192.168.0.8" base_url: "http://192.168.0.8"
# ragflow api访问令牌 # ragflow api访问令牌
@ -172,19 +178,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 +772,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:

View file

@ -47,7 +47,12 @@ async def handle_user_intent(conn: "ConnectionHandler", text):
# 会话开始时生成sentence_id # 会话开始时生成sentence_id
conn.sentence_id = str(uuid.uuid4().hex) conn.sentence_id = str(uuid.uuid4().hex)
# 处理各种意图 # 处理各种意图
return await process_intent_result(conn, intent_result, text) handled = await process_intent_result(conn, intent_result, text)
if handled:
return True
# 意图识别没有命中任何工具时,若配置了知识库,再做一次检索兜底,
# 避免"知识库里有答案,但描述没覆盖到该主题,导致检索根本没被触发"
return await fallback_knowledge_base(conn, text)
async def check_direct_exit(conn: "ConnectionHandler", text): async def check_direct_exit(conn: "ConnectionHandler", text):
@ -80,6 +85,77 @@ async def analyze_intent_with_llm(conn: "ConnectionHandler", text):
return None return None
# 目前只有 ragflow 检索插件,后续新增知识库后端时在这里补充函数名即可
KNOWLEDGE_TOOL_NAMES = ("search_from_ragflow",)
def _get_knowledge_fallback_config(conn: "ConnectionHandler"):
"""返回知识库兜底所需配置,未配置知识库时返回 None"""
plugins = conn.config.get("plugins", {}) or {}
for tool_name in KNOWLEDGE_TOOL_NAMES:
tool_config = plugins.get(tool_name)
if isinstance(tool_config, dict) and tool_config.get("dataset_ids"):
return tool_config
return None
async def fallback_knowledge_base(conn: "ConnectionHandler", text: str) -> bool:
"""意图识别判定为普通聊天时的知识库兜底检索。
意图识别只看得到知识库的"名称+描述"(受长度限制,很难穷举所有主题),
因此存在"知识库里有答案、但描述没覆盖该主题,检索从未被触发"的漏召回。
这里在意图识别结束后补充一次真实检索:命中相似度阈值内的片段就带着资料回复,
否则交回普通聊天流程,不改变原有行为。
"""
tool_config = _get_knowledge_fallback_config(conn)
if tool_config is None:
return False
if not tool_config.get("fallback_enabled", True):
return False
if getattr(conn, "func_handler", None) is None:
return False
try:
min_similarity = float(tool_config.get("fallback_min_similarity", 0.5))
except (TypeError, ValueError):
min_similarity = 0.5
from plugins_func.functions.search_from_ragflow import retrieve_chunks
hits = await retrieve_chunks(conn, text, min_similarity=min_similarity)
if not hits:
return False
conn.logger.bind(tag=TAG).info(
f"意图识别未命中知识库工具,兜底检索命中 {len(hits)} 条"
f"(最高相似度 {hits[0]['similarity']:.3f}),改用知识库回答"
)
await send_stt_message(conn, text)
conn.client_abort = False
context_text = f"# 关于问题【{text}】查到知识库如下\n"
context_text += "```\n\n\n".join(hit["content"] for hit in hits[:5])
context_text += "\n```"
def process_knowledge_reply():
conn.dialogue.put(Message(role="user", content=text))
conn.dialogue.put(Message(role="tool", content=context_text))
try:
llm_result = asyncio.run_coroutine_threadsafe(
conn.intent.replyResult(context_text, text),
conn.loop,
).result()
except Exception as e:
conn.logger.bind(tag=TAG).error(f"知识库兜底生成回复失败: {e}")
llm_result = None
if llm_result:
speak_txt(conn, llm_result)
conn.executor.submit(process_knowledge_reply)
return True
async def process_intent_result( async def process_intent_result(
conn: "ConnectionHandler", intent_result, original_text conn: "ConnectionHandler", intent_result, original_text
): ):

View file

@ -60,6 +60,27 @@ class IntentProvider(IntentProviderBase):
functions_desc += "---\n" functions_desc += "---\n"
# 知识库类工具的 description 只是主题概览,无法穷举库内所有问答,
# 仅凭 description 判断相关性会造成"库里有答案、检索却没被触发"的漏召回,
# 因此对 search_from_* 类工具单独强调"可能相关就先检索"。
knowledge_rules = ""
kb_tool_names = [
func.get("function", {}).get("name", "")
for func in functions_list
if func.get("function", {}).get("name", "").startswith("search_from_")
]
if kb_tool_names:
knowledge_rules = (
"【知识库工具调用规则】\n"
f"- 可用的知识库工具:{'、'.join(kb_tool_names)}\n"
"- 知识库的描述只是主题概览,不可能列出库内的全部问答内容。\n"
"- 只要用户问题有可能落在知识库覆盖的产品、功能、用法、参数、故障排查范围内,"
"即使描述里没有明确提到这个细分主题,也必须调用知识库工具检索一次。\n"
"- 遇到“怎么使用、如何操作、有什么功能、怎么设置、报错怎么办”这类问题,"
"若与知识库主题相关,应优先检索知识库而不是直接走普通聊天。\n"
"- 宁可多检索一次:检索不到内容时系统会自动降级,不影响正常回答。\n\n"
)
prompt = ( prompt = (
"【严格格式要求】你必须只能返回JSON格式,绝对不能返回任何自然语言!\n\n" "【严格格式要求】你必须只能返回JSON格式,绝对不能返回任何自然语言!\n\n"
"你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n" "你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n"
@ -72,6 +93,7 @@ class IntentProvider(IntentProviderBase):
"- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n" "- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n"
"- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n" "- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n"
f"{functions_desc}\n" f"{functions_desc}\n"
f"{knowledge_rules}"
"处理步骤:\n" "处理步骤:\n"
"1. 分析用户输入,确定用户意图\n" "1. 分析用户输入,确定用户意图\n"
"2. 检查是否为上述基础信息查询(时间、日期等),如是则返回result_for_context\n" "2. 检查是否为上述基础信息查询(时间、日期等),如是则返回result_for_context\n"

View file

@ -25,6 +25,75 @@ SEARCH_FROM_RAGFLOW_FUNCTION_DESC = {
} }
def _get_ragflow_config(conn: "ConnectionHandler") -> dict:
return conn.config.get("plugins", {}).get("search_from_ragflow", {}) or {}
def _normalize_content(content) -> str:
"""把 chunk.content 统一成字符串"""
if isinstance(content, str):
return content
if isinstance(content, bytes):
return content.decode("utf-8", errors="replace")
if content is None:
return ""
return str(content)
async def retrieve_chunks(
conn: "ConnectionHandler", question: str, min_similarity: float = 0.0
) -> list:
"""直接检索知识库并返回命中的片段(按相似度降序,最多 5 条)。
与 search_from_ragflow 工具的区别:本函数只做检索、不做话术包装,
供意图识别兜底使用。任何异常都返回空列表,不阻塞正常对话链路。
"""
if not question:
return []
ragflow_config = _get_ragflow_config(conn)
base_url = ragflow_config.get("base_url", "")
api_key = ragflow_config.get("api_key", "")
dataset_ids = ragflow_config.get("dataset_ids", [])
if not base_url or not dataset_ids:
return []
payload = {"question": question, "dataset_ids": dataset_ids}
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
try:
async with httpx.AsyncClient(
timeout=httpx.Timeout(5.0, connect=3.0), verify=False
) as client:
response = await client.post(
base_url + "/api/v1/retrieval", json=payload, headers=headers
)
response.encoding = "utf-8"
result = json.loads(response.text)
if result.get("code") != 0:
return []
except Exception as e:
logger.bind(tag=TAG).debug(f"知识库兜底检索失败: {type(e).__name__} {e}")
return []
hits = []
for chunk in result.get("data", {}).get("chunks", []) or []:
content = _normalize_content(chunk.get("content", ""))
if not content:
continue
try:
# RAGFlow 返回 similarity 为 0~1 的浮点数,缺失时视为 0
similarity = float(chunk.get("similarity", 0) or 0)
except (TypeError, ValueError):
similarity = 0.0
if similarity < min_similarity:
continue
hits.append({"content": content, "similarity": similarity})
hits.sort(key=lambda item: item["similarity"], reverse=True)
return hits
@register_function( @register_function(
"search_from_ragflow", SEARCH_FROM_RAGFLOW_FUNCTION_DESC, ToolType.SYSTEM_CTL "search_from_ragflow", SEARCH_FROM_RAGFLOW_FUNCTION_DESC, ToolType.SYSTEM_CTL
) )
@ -36,7 +105,7 @@ async def search_from_ragflow(conn: "ConnectionHandler", question=None):
else: else:
question = str(question) if question is not None else "" question = str(question) if question is not None else ""
ragflow_config = conn.config.get("plugins", {}).get("search_from_ragflow", {}) ragflow_config = _get_ragflow_config(conn)
base_url = ragflow_config.get("base_url", "") base_url = ragflow_config.get("base_url", "")
api_key = ragflow_config.get("api_key", "") api_key = ragflow_config.get("api_key", "")
dataset_ids = ragflow_config.get("dataset_ids", []) dataset_ids = ragflow_config.get("dataset_ids", [])
@ -85,15 +154,9 @@ async def search_from_ragflow(conn: "ConnectionHandler", question=None):
chunks = result.get("data", {}).get("chunks", []) chunks = result.get("data", {}).get("chunks", [])
contents = [] contents = []
for chunk in chunks: for chunk in chunks:
content = chunk.get("content", "") content = _normalize_content(chunk.get("content", ""))
if content: if content:
# 安全地处理内容字符串 contents.append(content)
if isinstance(content, str):
contents.append(content)
elif isinstance(content, bytes):
contents.append(content.decode("utf-8", errors="replace"))
else:
contents.append(str(content))
if contents: if contents:
# 组织知识库内容为引用模式 # 组织知识库内容为引用模式

View file

@ -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,

View 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 复制粘贴时带串了"
)

View file

@ -0,0 +1,233 @@
"""意图识别漏召回时的知识库兜底检索测试。
复现场景(issue #3555):知识库里明明有对应问答,但意图识别阶段
只凭"知识库名称+描述"判断相关性,描述没覆盖该细分主题时直接判为
不相关,检索根本没被触发。
覆盖点:
1. ``retrieve_chunks`` 按相似度过滤并按降序返回;
2. 命中阈值时 ``fallback_knowledge_base`` 接管本轮回答;
3. 未命中 / 关闭开关 / 未配置知识库时,行为与改动前一致(返回 False)。
"""
from __future__ import annotations
import asyncio
import json
import threading
import types
from concurrent.futures import ThreadPoolExecutor
import httpx
from config.logger import setup_logging
# 模块级初始化:setup_logging 内部会用 asyncio.run 读配置,
# 不能在事件循环里首次调用,否则会撞上 "asyncio.run() cannot be called from a running event loop"
LOGGER = setup_logging()
CHUNKS = [
{
"content": "问题:知识库功能怎么使用?\n答案:上传知识库文件后即可使用……",
"similarity": 0.86,
},
{
"content": "问题:打印机如何连接 WIFI?\n答案:长按配网键 3 秒……",
"similarity": 0.62,
},
{"content": "问题:怎么充电?", "similarity": 0.11},
]
class _FakeResponse:
def __init__(self, payload):
self._payload = payload
self.encoding = None
@property
def text(self):
return json.dumps(self._payload, ensure_ascii=False)
def raise_for_status(self):
pass
class _FakeAsyncClient:
last_payload = None
def __init__(self, *_args, **_kwargs):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *_args):
return False
async def post(self, url, json=None, headers=None): # noqa: A002
_FakeAsyncClient.last_payload = json
return _FakeResponse({"code": 0, "data": {"chunks": CHUNKS}})
class _FakeDialogue:
def __init__(self):
self.dialogue = []
def put(self, msg):
self.dialogue.append(msg)
class _FakeTTS:
def __init__(self):
self.spoken = []
self.spoken_event = threading.Event()
self.tts_text_queue = types.SimpleNamespace(put=lambda _x: None)
def store_tts_text(self, _sentence_id, _text):
pass
def tts_one_sentence(self, _conn, _content_type, content_detail=None):
self.spoken.append(content_detail)
self.spoken_event.set()
class _FakeIntent:
async def replyResult(self, _text, _original_text):
return "知识库功能这样用:上传知识库文件后就能直接提问。"
class _FakeConn:
def __init__(self, plugins):
self.config = {"plugins": plugins}
self.logger = LOGGER
self.dialogue = _FakeDialogue()
self.tts = _FakeTTS()
self.intent = _FakeIntent()
self.func_handler = object()
self.client_abort = False
self.sentence_id = "sid"
self.executor = ThreadPoolExecutor(max_workers=1)
self.loop = None
self.stt_sent = []
def _plugin_config(**overrides):
config = {
"description": "某品牌说明书问答库",
"base_url": "http://rag.local",
"api_key": "ragflow-test",
"dataset_ids": ["ds1"],
"fallback_enabled": True,
"fallback_min_similarity": 0.5,
}
config.update(overrides)
return config
def _patch_ragflow_http(monkeypatch):
import plugins_func.functions.search_from_ragflow as ragflow
monkeypatch.setattr(
ragflow,
"httpx",
types.SimpleNamespace(
AsyncClient=_FakeAsyncClient,
Timeout=lambda *_a, **_k: None,
TimeoutException=httpx.TimeoutException,
HTTPStatusError=httpx.HTTPStatusError,
HTTPError=httpx.HTTPError,
),
)
def _prepare(monkeypatch):
"""导入被测模块并把发送 STT 的动作替换成记录,避免依赖真实连接。"""
import plugins_func.functions.search_from_ragflow as ragflow
from core.handle import intentHandler
_patch_ragflow_http(monkeypatch)
async def _fake_send_stt(conn, text):
conn.stt_sent.append(text)
monkeypatch.setattr(intentHandler, "send_stt_message", _fake_send_stt)
return ragflow, intentHandler
def test_retrieve_chunks_filters_by_similarity(monkeypatch):
ragflow, _ = _prepare(monkeypatch)
conn = _FakeConn({"search_from_ragflow": _plugin_config()})
async def run():
hits = await ragflow.retrieve_chunks(conn, "我要怎么使用知识库", 0.5)
high = await ragflow.retrieve_chunks(conn, "我要怎么使用知识库", 0.8)
return hits, high
hits, high = asyncio.run(run())
assert len(hits) == 2
assert hits[0]["similarity"] >= hits[1]["similarity"]
assert len(high) == 1
# 请求体应带上配置里的 knowledge base id
assert _FakeAsyncClient.last_payload["dataset_ids"] == ["ds1"]
def test_fallback_takes_over_when_hit(monkeypatch):
_, intentHandler = _prepare(monkeypatch)
conn = _FakeConn({"search_from_ragflow": _plugin_config()})
async def run():
conn.loop = asyncio.get_running_loop()
handled = await intentHandler.fallback_knowledge_base(
conn, "我要怎么使用知识库"
)
# 回复在线程池里生成,这里把等待放到线程里,避免卡住事件循环;
# 也不用 asyncio.sleep(conftest 会把它替换成空实现)
await conn.loop.run_in_executor(None, conn.tts.spoken_event.wait, 5)
return handled
handled = asyncio.run(run())
try:
assert handled is True
assert conn.stt_sent == ["我要怎么使用知识库"]
assert conn.dialogue.dialogue[0].role == "user"
assert conn.dialogue.dialogue[1].role == "tool"
assert "知识库功能怎么使用" in conn.dialogue.dialogue[1].content
assert conn.tts.spoken, "兜底命中后应给出语音回复"
finally:
conn.executor.shutdown(wait=True)
def test_fallback_skipped_without_hit(monkeypatch):
_, intentHandler = _prepare(monkeypatch)
conn = _FakeConn(
{"search_from_ragflow": _plugin_config(fallback_min_similarity=0.95)}
)
async def run():
conn.loop = asyncio.get_running_loop()
return await intentHandler.fallback_knowledge_base(conn, "今天天气怎么样")
try:
assert asyncio.run(run()) is False
assert conn.dialogue.dialogue == []
finally:
conn.executor.shutdown(wait=True)
def test_fallback_disabled_or_not_configured(monkeypatch):
_, intentHandler = _prepare(monkeypatch)
async def run():
disabled = _FakeConn(
{"search_from_ragflow": _plugin_config(fallback_enabled=False)}
)
disabled.loop = asyncio.get_running_loop()
first = await intentHandler.fallback_knowledge_base(disabled, "有问题吗")
empty = _FakeConn({})
empty.loop = asyncio.get_running_loop()
second = await intentHandler.fallback_knowledge_base(empty, "你好")
return first, second
first, second = asyncio.run(run())
assert first is False
assert second is False

View file

@ -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}