diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 11c87a5f6..a3f155911 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -165,6 +165,12 @@ plugins: search_from_ragflow: # 知识库的描述信息,方便大语言模型知道什么时候调用 description: "当用户问xxx时,调用本方法,使用知识库中的信息回答问题" + # 意图识别判定为普通聊天时的知识库兜底检索。 + # 描述无法穷举库内所有主题,开启后即使意图识别没选中知识库, + # 也会用用户问题真实检索一次,命中阈值内的内容就改用知识库回答 + fallback_enabled: true + # 兜底检索的最低相似度(0~1),低于该值的片段直接丢弃 + fallback_min_similarity: 0.5 # ragflow接口配置 base_url: "http://192.168.0.8" # ragflow api访问令牌 diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index 1a72d1d68..63d148895 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -47,7 +47,12 @@ async def handle_user_intent(conn: "ConnectionHandler", text): # 会话开始时生成sentence_id 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): @@ -80,6 +85,77 @@ async def analyze_intent_with_llm(conn: "ConnectionHandler", text): 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( conn: "ConnectionHandler", intent_result, original_text ): diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py index 1dd5bb172..f7e90ab3e 100644 --- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py +++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py @@ -60,6 +60,27 @@ class IntentProvider(IntentProviderBase): 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 = ( "【严格格式要求】你必须只能返回JSON格式,绝对不能返回任何自然语言!\n\n" "你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n" @@ -72,6 +93,7 @@ class IntentProvider(IntentProviderBase): "- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n" "- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n" f"{functions_desc}\n" + f"{knowledge_rules}" "处理步骤:\n" "1. 分析用户输入,确定用户意图\n" "2. 检查是否为上述基础信息查询(时间、日期等),如是则返回result_for_context\n" diff --git a/main/xiaozhi-server/plugins_func/functions/search_from_ragflow.py b/main/xiaozhi-server/plugins_func/functions/search_from_ragflow.py index 40abf8c4a..a4365972f 100644 --- a/main/xiaozhi-server/plugins_func/functions/search_from_ragflow.py +++ b/main/xiaozhi-server/plugins_func/functions/search_from_ragflow.py @@ -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( "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: 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", "") api_key = ragflow_config.get("api_key", "") 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", []) contents = [] for chunk in chunks: - content = chunk.get("content", "") + content = _normalize_content(chunk.get("content", "")) if 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)) + contents.append(content) if contents: # 组织知识库内容为引用模式 diff --git a/main/xiaozhi-server/tests/core/handle/test_knowledge_fallback.py b/main/xiaozhi-server/tests/core/handle/test_knowledge_fallback.py new file mode 100644 index 000000000..40d412092 --- /dev/null +++ b/main/xiaozhi-server/tests/core/handle/test_knowledge_fallback.py @@ -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