跳转到正文
wise-* 包教程 20 个可独立安装的 Composer 能力包:选包、装包、调用、扩展

实战:知识库问答闭环

1 2026-11-25 23:02:34

目标:把商品文档灌进知识库,让 AI 基于它回答并给出出处,同时把这套能力暴露给外部 MCP 客户端。三件事分别归 wise-rag(读)、wise-agent(编排)、wise-mcp(协议)。

场景

客服要回答"A100 功率多少"。模型的参数知识既不准也不可追溯,所以先把产品手册变成可检索的知识库,让模型在回答前先检索、回答时带出处。

同一个检索能力,内部 AI 助手要用,第三方 AI 客户端(Claude Desktop 之类)也想用——后者走 MCP,而不是再写一套 HTTP 接口。

开始之前

composer require wiseadmin/wise-rag wiseadmin/wise-agent wiseadmin/wise-mcp
php think vendor:publish
php think wise:vendor:publish
php think migrate:run
php think wise:rag:discover
php think wise:agent:discover
php think wise:agent:permissions

.env 里要配 AI_ENCRYPT_KEY、OPENAI_API_KEY 或 DEEPSEEK_API_KEY。ingestion.async = true 时还要有 php think queue:work 在跑,否则摄取任务停在"等待中"。

步骤一:建库 → 摄取 → 检索

// ① 建库
$kbId = wise_rag_create('product_docs', [
    'name'        => '商品文档',
    'description' => 'A100 系列产品手册',
    'visibility'  => 'public',
]);

// ② 摄取:元数据决定引用溯源能力
$docId = wise_rag_ingest($kbId, "# A100\n\n功率 250W,支持 PD 3.0。", [
    'external_id' => 'p100',
    'title'       => 'A100 说明书',
    'url'         => '/docs/p100',
]);

// ③ 检索:命中自带 cite
$hits = wise_rag_search('A100 功率多少', ['product_docs'], 5);
foreach ($hits as $hit) {
    $cite = $hit['meta']['cite'] ?? [];
    echo $hit['content'], ' | ', $cite['kb_key'] ?? '', ' / ', $cite['title'] ?? '', "\n";
}

title 与 url 不是可选项:不给 url,回答里只能给"某文档说了",用户点不进去,等于没有出处。

检索质量由 retrieval.hybrid / fusion / min_score 控制:向量管语义相近,关键词管型号与错误码。改完参数用 wise:rag:eval 量化,别凭感觉调。

步骤二:插件零接入(不写 PHP)

在插件 manifest.json 声明即可:

{
  "title": "智能库存",
  "ai_schema": {
    "knowledge_kb_key": "smartstock_docs",
    "knowledge_sources": [
      {
        "key": "product_docs",
        "title": "商品说明书",
        "provider": "table",
        "config": {
          "table": "smartstock_product",
          "id_field": "id",
          "title_field": "name",
          "content_fields": ["name", "description", "spec"],
          "updated_field": "update_time",
          "url_template": "/admin/smartstock/product/detail?id={id}"
        },
        "sync_mode": "manual",
        "chunk": { "size": 400, "overlap": 60, "splitter": "structure" }
      }
    ]
  }
}
php think wise:rag:discover            # 声明 → 幂等落库,缺库自动建
php think wise:rag:discover --index    # 发现后立即索引
php think wise:rag:index smartstock_docs --force
php think wise:rag:stats

三个细节决定这套声明能不能长期用:

  • provider 只有 table / attachment(仅本地驱动)/ manual 三种;
  • sync_mode = manual 表示数据改了不会自动重索引,要挂定时任务跑 wise:rag:index;
  • updated_field 决定增量索引是否准确,写错会让你每次都全量重建。

步骤三:把检索注册给 Agent

wise-rag 会自动往 ToolRegistry 注册两个工具名:全局 kb.search、每库一个 kb.{sanitized_key}.search。权限标识是 ai.tool.kb_search(access=read、risk=low、免人工确认),必须跑命令落库:

php think wise:agent:permissions            # 落库 ai.tool.kb_search
php think wise:agent:permissions --dry-run  # 先看会写什么

然后到后台「角色管理」勾选「AI 工具:知识库检索」。权限没勾,AI 调用会被拒——这是"本地测通了、上线就报无权限"的常见原因。

步骤四:让 Agent 走完整 Run Loop

$agent = wise_agent()->create(null, ['provider' => 'deepseek']);

$answer = wise_agent()->run($agent, '根据知识库回答:A100 的功率是多少?请给出出处。', [
    'temperature'                  => 0.2,
    'max_steps'                    => 6,
    'max_tokens_per_step'          => 2048,
    'max_agent_duration'           => 120,
    'max_tool_executions_per_step' => 3,
    'max_tool_execution_time'      => 15,
]);

temperature = 0.2 是刻意的:事实型问答要稳定不要发散。max_steps = 6 足够"检索 → 再检索 → 回答",给到 10 以上只会让成本上升。

一个必须避开的写法:不要写 ->withTools(['kb.search'])。BaseAgent::withTools() 只按 config('wise-agent.tools') 注册内置工具(file_read、db_query 等);kb.search 是 wise-rag 直接注册进 ToolRegistry 单例的,Run Loop 天然可见。用 withTools 反而会把它挡掉,且不报错。

调试检索(不走模型):

$registry = \wise\agent\tool\ToolRegistry::instance();
if ($registry->has('kb.search')) {
    $raw     = $registry->execute('kb.search', ['query' => 'A100 功率', 'top_k' => 3]);
    $payload = json_decode($raw, true);   // {query,count,results:[{content,score,source:{...}}]}
}

单轮闲聊不需要工具,直接用 chat():wise_agent()->chat('你好', 'deepseek', ['temperature' => 0.5])。

步骤五:暴露给 MCP 客户端

wise-rag 已经注册了 ToolProviderInterface 与 ResourceProviderInterface,由 MCP 的 CapabilityRegistry 聚合;外部看到的工具名仍是 kb.search(不带命名空间前缀)。

php think wise:mcp:discover
php think wise:mcp:serve --transport=stdio

桌面客户端配置:

{ "mcpServers": { "wise": { "command": "php", "args": ["think", "wise:mcp:serve"] } } }

权限不会因为换了入口就放宽:装了 wise-agent 时,McpServer 委托 AgentToolInvoker,复用 ToolExecute 的授权、审批、沙箱与审计;没装时降级成 HandlerToolInvoker,只剩 allow_write 布尔门禁。

权限与开关对照

层关键项默认要不要动
wise-ragagent.auto_tool / global_tooltrue / true一般不动
wise-ragmcp.expose_tools / expose_resourcestrue / true不想外露时关
wise-rag/admin/kb/* + RbacMiddleware已挂不动
wise-agentai.tool.kb_search 权限需跑 wise:agent:permissions必须落库并授权
wise-mcptransports.stdio.enabletrue按需
wise-mcpsecurity.allow_write / require_authfalse / true保持 fail-closed
wise-mcpweb.enablefalse要 HTTP 才开,且必须挂 Rbac

自查

php think wise:rag:stats
php think wise:rag:eval
php think wise:mcp:discover

四条要同时成立:

  1. wise_rag_search('A100 功率') 返回带 cite 的命中;
  2. Agent 回答包含知识库内容与出处链接;
  3. 角色没勾 ai.tool.kb_search 时,Agent 调用该工具被拒(验证权限真的生效);
  4. MCP 客户端能列出 kb.search 工具。

三个包的完整能力见 wise-rag、wise-agent、wise-mcp。

这篇文档对您有帮助吗?

相关文档