50 lines
2.1 KiB
Python
50 lines
2.1 KiB
Python
"""知识检索工具:注册给 Agent 的**只读**公共工具。
|
|||
|
|
|
||
|
|
为什么把知识检索做成工具,而不是让 Agent 直接持有检索服务:走 `ToolExecutor` 就同时
|
||
|
|
得到四件由基座保证的事——工具白名单(发布配置可收窄、缺配置即失败关闭)、权限校验、
|
||
|
|
调用审计(`agent.tool_executed`)、超时保护。Agent 拿到的 `source_references` 也由基座
|
||
|
|
统一附加,业务代码不能伪造来源引用。
|
||
|
|
|
||
|
|
工具只读是硬约束(`ToolRegistry.register` 会拒绝 `read_only=False`),本工具确实只查库。
|
||
|
|
"""
|
||
|
|
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
from app.core.contracts import RequestContext
|
||
|
|
from app.core.knowledge_contracts import KnowledgeSearchInput
|
||
|
|
|
||
|
|
|
||
|
|
async def knowledge_search_tool(
|
||
|
|
arguments: KnowledgeSearchInput, context: RequestContext
|
||
|
|
) -> dict[str, Any]:
|
||
|
|
"""检索三个知识集合,返回命中原文与来源信息。
|
||
|
|
|
||
|
|
检索链路(向量化 / Milvus)任一环节失败都**不抛异常**,而是以 `degraded=True` 返回:
|
||
|
|
客服 Agent 据此走「引导客户致电人工客服」,而不是把基础设施故障暴露成客户可见的错误。
|
||
|
|
"""
|
||
|
|
del context # 检索本身不区分身份;权限与白名单已在 ToolExecutor 中校验
|
||
|
|
# 延迟导入:bootstrap 会导入本模块完成工具注册,模块级导入会形成循环依赖。
|
||
|
|
from app.service.agent.bootstrap import get_knowledge_search_service
|
||
|
|
|
||
|
|
outcome = await get_knowledge_search_service().search(
|
||
|
|
arguments.query,
|
||
|
|
collections=(arguments.collection,) if arguments.collection else None,
|
||
|
|
top_k=arguments.top_k,
|
||
|
|
)
|
||
|
|
return {
|
||
|
|
"degraded": outcome.degraded,
|
||
|
|
"reason": outcome.reason,
|
||
|
|
"hits": [
|
||
|
|
{
|
||
|
|
"doc_id": hit.doc_id,
|
||
|
|
"title": hit.title,
|
||
|
|
"content": hit.content,
|
||
|
|
"score": round(hit.score, 4),
|
||
|
|
"source_file": hit.source_file,
|
||
|
|
"doc_no": hit.doc_no,
|
||
|
|
"visibility": hit.visibility,
|
||
|
|
}
|
||
|
|
for hit in outcome.hits
|
||
|
|
],
|
||
|
|
}
|