<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.cerostep.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.cerostep.com/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-10-20T07:12:12+00:00</updated><id>https://www.cerostep.com/feed.xml</id><title type="html">Cerostep</title><subtitle>Learning, practice, and engineering notes on DevOps and AI agents.</subtitle><author><name>Cerostep</name></author><entry xml:lang="zh"><title type="html">从 Chunk 到 RAG：搭建企业员工制度 AI 知识库</title><link href="https://www.cerostep.com/2026/10/20/enterprise-employee-handbook-rag/" rel="alternate" type="text/html" title="从 Chunk 到 RAG：搭建企业员工制度 AI 知识库" /><published>2026-10-19T16:00:00+00:00</published><updated>2026-10-19T16:00:00+00:00</updated><id>https://www.cerostep.com/2026/10/20/enterprise-employee-handbook-rag</id><content type="html" xml:base="https://www.cerostep.com/2026/10/20/enterprise-employee-handbook-rag/"><![CDATA[<h2 id="摘要">摘要</h2>

<p>假设我们需要为一家企业搭建员工制度 AI 助手，让员工可以直接询问：</p>

<blockquote>
  <p>正式员工每年有多少天年假？申请年假需要提前多久？</p>
</blockquote>

<blockquote>
  <p>出差住宿费可以报销多少？需要提供哪些材料？</p>
</blockquote>

<blockquote>
  <p>上班迟到几分钟会被记录？忘记打卡应该怎么办？</p>
</blockquote>

<p>这些问题看起来只是简单的问答，但要让 AI 稳定、准确地回答，就需要解决一系列工程问题：</p>

<ol>
  <li>如何将员工手册、报销制度和考勤规则转换为可检索的知识？</li>
  <li>什么是 Chunk？为什么不能简单地把整份员工手册直接交给大模型？</li>
  <li>如何结合 BM25 关键词检索与向量检索，找到真正相关的内容？</li>
  <li>为什么初步召回之后，还可能需要 Rerank 重排序？</li>
  <li>如何让大模型基于制度原文回答，并提供引用来源？</li>
  <li>如何评估答案质量，并在准确性、延迟和成本之间取得平衡？</li>
</ol>

<p>本文先总结 RAG 的核心概念，再通过一个完整的员工制度示例，逐步说明知识处理、检索、生成与评估的实现思路。</p>

<hr />

<h2 id="一ragchunk-与相关概念">一、RAG、Chunk 与相关概念</h2>

<h3 id="11-什么是-rag">1.1 什么是 RAG？</h3>

<p>RAG 是 Retrieval-Augmented Generation 的缩写，中文通常称为“检索增强生成”。</p>

<p>它的核心思路是：</p>

<p><strong>先从外部知识库中检索相关资料，再将这些资料提供给大语言模型，让模型基于检索结果生成答案。</strong></p>

<p>传统的大模型问答通常可以简化为：</p>

<pre><code class="language-mermaid">flowchart TD
    A[用户问题] --&gt; B[大语言模型（LLM）]
    B --&gt; C[生成答案]
</code></pre>

<p>RAG 则在生成之前增加了知识检索：</p>

<pre><code class="language-mermaid">flowchart TD
    A[用户问题] --&gt; B[检索知识库]
    B --&gt; C[获取相关资料]
    C --&gt; D[大语言模型（LLM）]
    D --&gt; E[生成答案]
</code></pre>

<p>这里的知识库可以包含企业内部文档、产品手册、技术文档、合同、FAQ 和业务规范等。</p>

<p>RAG 并不是重新训练一个大模型，也不是让模型永久记住所有企业资料。它是在每次处理问题时，动态地检索相关知识，并将其作为生成答案的依据。</p>

<p>对于企业内部问答，这种方式有三个重要价值：</p>

<ul>
  <li><strong>知识可更新：</strong> 制度变更后，可以更新知识库，而不必为了这些变化重新训练大模型。</li>
  <li><strong>答案可追溯：</strong> 可以将回答关联到原始文档、章节或页码。</li>
  <li><strong>知识可控制：</strong> 可以结合元数据、用户身份和访问权限，限制检索范围。</li>
</ul>

<p>但 RAG 并不保证答案一定正确。如果检索阶段漏掉了关键内容，或者检索到了过期制度，模型仍然可能给出错误答案。</p>

<h3 id="12-什么是-chunk">1.2 什么是 Chunk？</h3>

<p>Chunk 是将一份较长的文档切分后得到的文本片段。</p>

<p>例如，一份员工手册可能包含以下章节：</p>

<ul>
  <li>员工手册
    <ul>
      <li>第一章：入职与离职</li>
      <li>第二章：考勤管理</li>
      <li>第三章：休假制度</li>
      <li>第四章：费用报销</li>
      <li>第五章：绩效管理</li>
    </ul>
  </li>
</ul>

<p>如果直接把整份员工手册当作一个检索单元，那么当员工询问年假时，系统可能只能找到整份手册，而无法精准定位到年假条款。</p>

<p>因此，可以将文档切分为多个 Chunk：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Chunk 001：年假额度与适用范围
Chunk 002：年假申请流程
Chunk 003：年假结转规则
Chunk 004：迟到与早退规定
Chunk 005：忘记打卡处理流程
Chunk 006：差旅住宿报销标准
Chunk 007：报销材料与审批流程
</code></pre></div></div>

<p>每个 Chunk 都是一个相对独立的检索单元。</p>

<p>当用户询问年假申请流程时，系统可以直接检索与申请规则有关的片段，而不是把整份员工手册重新交给模型处理。</p>

<p>需要注意，Chunk 不一定对应一个完整的自然段，也不一定对应一个固定长度的字符串。它可以是一个段落、几个连续段落、一个表格片段，或者一个经过语义切分的制度条款。</p>

<p><strong>Chunk 的设计目标，是让每个片段尽量保留完整的业务含义，同时便于检索、排序和引用。</strong></p>

<h3 id="13-chunk-size-和-overlap-是什么">1.3 Chunk Size 和 Overlap 是什么？</h3>

<p>Chunk Size 表示一个 Chunk 的目标大小，通常可以按 Token 数量衡量，也可以在某些系统中按字符数衡量。</p>

<p>Overlap 表示相邻 Chunk 之间重复保留的内容，用于降低切分边界造成的信息丢失。</p>

<p>例如，原始制度文本为：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>员工每年享有 10 天带薪年假。
申请年假时，应至少提前 3 个工作日提交申请。
连续休假超过 5 个工作日的，需要额外经过部门负责人审批。
</code></pre></div></div>

<p>如果切分得过细，可能得到：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Chunk A：员工每年享有 10 天带薪年假。

Chunk B：申请年假时，应至少提前 3 个工作日提交申请。

Chunk C：连续休假超过 5 个工作日的，需要额外经过部门负责人审批。
</code></pre></div></div>

<p>这在很多情况下是合理的，但如果某条规则必须结合上一段的适用条件才能理解，过细切分就可能破坏上下文。</p>

<p>如果切分得过粗，则可能把年假、考勤、报销等不同主题放进同一个 Chunk，降低检索的精确性。</p>

<p>因此，切分策略需要在上下文完整性和检索精度之间取得平衡。</p>

<table>
  <thead>
    <tr>
      <th>参数</th>
      <th>作用</th>
      <th>设置不当的影响</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Chunk Size</td>
      <td>控制每个片段的大小</td>
      <td>太小可能缺失上下文，太大可能引入无关内容</td>
    </tr>
    <tr>
      <td>Overlap</td>
      <td>保留相邻片段之间的部分重复内容</td>
      <td>太小可能丢失跨边界信息，太大则增加重复内容和存储成本</td>
    </tr>
    <tr>
      <td>切分边界</td>
      <td>决定在哪里拆分文档</td>
      <td>可能把条件、例外或审批要求与主规则拆开</td>
    </tr>
    <tr>
      <td>元数据</td>
      <td>描述片段的来源、类型和适用范围</td>
      <td>不利于权限控制、过滤和引用追溯</td>
    </tr>
  </tbody>
</table>

<p>Chunk Size 和 Overlap 没有适用于所有场景的固定最优值。实际项目需要根据文档结构、查询类型、Embedding 模型和评测结果进行调整。</p>

<h3 id="14-rag-中几个重要的技术组件">1.4 RAG 中几个重要的技术组件</h3>

<table>
  <thead>
    <tr>
      <th>组件</th>
      <th>主要作用</th>
      <th>通俗理解</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>文档解析</td>
      <td>从 PDF、Word、HTML 等文件提取内容</td>
      <td>先把资料读出来</td>
    </tr>
    <tr>
      <td>Chunking</td>
      <td>将文档切分成片段</td>
      <td>把资料拆成适合检索的小块</td>
    </tr>
    <tr>
      <td>Embedding</td>
      <td>将文本转换成向量表示</td>
      <td>将文本编码成便于计算相似度的数字</td>
    </tr>
    <tr>
      <td>向量检索</td>
      <td>查找语义相近的片段</td>
      <td>找意思相近的资料</td>
    </tr>
    <tr>
      <td>BM25</td>
      <td>根据关键词匹配进行排序</td>
      <td>找包含相关词语的资料</td>
    </tr>
    <tr>
      <td>混合召回</td>
      <td>合并关键词检索与向量检索结果</td>
      <td>尽量减少漏掉有用资料的情况</td>
    </tr>
    <tr>
      <td>Rerank</td>
      <td>对候选片段进行更精细的相关性排序</td>
      <td>从候选资料中重新挑出更相关的内容</td>
    </tr>
    <tr>
      <td>LLM</td>
      <td>根据检索上下文生成答案</td>
      <td>阅读资料并组织回答</td>
    </tr>
    <tr>
      <td>元数据过滤</td>
      <td>根据部门、权限、版本等条件限制检索</td>
      <td>先确定哪些资料可以被查</td>
    </tr>
    <tr>
      <td>评测</td>
      <td>衡量检索和回答的实际质量</td>
      <td>用测试问题验证系统是否真的有效</td>
    </tr>
  </tbody>
</table>

<p>这些组件并不意味着每个 RAG 项目都必须使用全部技术。合理的工程设计应当从最简单、可验证的方案开始，再根据真实问题的失败情况增加复杂度。</p>

<hr />

<h2 id="二员工制度-rag-知识库的整体设计">二、员工制度 RAG 知识库的整体设计</h2>

<h3 id="21-明确业务目标">2.1 明确业务目标</h3>

<p>假设一家企业希望将员工手册、报销制度和考勤规范接入 AI 助手。</p>

<p>业务目标不是让模型泛泛地解释人力资源知识，而是让员工能够查询<strong>本企业当前有效的制度</strong>。</p>

<p>例如：</p>

<ul>
  <li>年假：额度、申请时间、审批流程、结转规则。</li>
  <li>报销：费用标准、适用范围、所需凭证、审批流程。</li>
  <li>考勤：迟到定义、打卡要求、漏打卡处理、异常申诉。</li>
</ul>

<p>这类业务具有几个典型特点：</p>

<ol>
  <li>制度文本相对稳定，但会定期更新。</li>
  <li>部分规则具有明确的数字、时间、金额和条件。</li>
  <li>同一个词可能在不同制度中具有不同含义。</li>
  <li>员工只能访问其有权限查看的信息。</li>
  <li>回答错误可能导致员工依据错误政策采取行动。</li>
</ol>

<p>因此，知识库不应只关注语义相似度，还需要考虑制度版本、适用对象、有效日期和原始出处。</p>

<h3 id="22-系统架构">2.2 系统架构</h3>

<p>一个基础的企业员工制度 RAG 系统可以分为离线知识处理和在线问答两条链路。</p>

<pre><code class="language-mermaid">flowchart TD
    A[员工手册、报销制度、考勤规范] --&gt; B[文档解析]
    B --&gt; C[清洗与结构识别]
    C --&gt; D[Chunk 切分]
    D --&gt; E[添加元数据]
    E --&gt; F[生成 Embedding]
    F --&gt; G[向量数据库]
    E --&gt; H[关键词索引]
    I[员工提问] --&gt; J[身份认证与权限确定]
    J --&gt; K[问题处理]
    K --&gt; L[BM25 关键词检索]
    K --&gt; M[向量检索]
    L --&gt; N[合并去重]
    M --&gt; N
    N --&gt; O[Rerank]
    O --&gt; P[上下文组装]
    P --&gt; Q[大语言模型]
    Q --&gt; R[答案与引用来源]
</code></pre>

<p>图中的关键词索引和向量数据库属于两种不同的检索基础设施，可以使用不同的存储系统，也可以使用支持混合检索的统一系统实现。</p>

<p>在线请求并不一定要执行所有环节。例如，简单查询可以跳过 Query 改写；如果基础检索的排序质量已经足够好，也可以不使用 Rerank。</p>

<h3 id="23-为什么要区分离线处理和在线问答">2.3 为什么要区分离线处理和在线问答？</h3>

<p>离线处理负责将原始资料转换为可以检索的知识。</p>

<p>例如：</p>

<ul>
  <li>读取员工手册。</li>
  <li>提取章节、段落和表格。</li>
  <li>生成 Chunk。</li>
  <li>添加文档版本与权限元数据。</li>
  <li>生成 Embedding。</li>
  <li>建立向量索引和关键词索引。</li>
</ul>

<p>在线问答负责使用这些知识回答员工问题。</p>

<p>例如：</p>

<ul>
  <li>确认当前员工身份和权限。</li>
  <li>理解员工的问题。</li>
  <li>从知识库中召回候选 Chunk。</li>
  <li>对候选内容排序。</li>
  <li>将相关制度交给 LLM。</li>
  <li>输出答案及其出处。</li>
</ul>

<p>这种分工可以避免每次用户提问时都重新解析所有文档和生成全部向量，从而降低在线处理成本。</p>

<p>制度发生变化时，系统通常只需要处理受影响的文档或片段，并更新相应索引。具体如何增量更新，取决于系统是否能够可靠识别文档版本和内容变更。</p>

<hr />

<h2 id="三详细示例将员工手册切分为-chunk">三、详细示例：将员工手册切分为 Chunk</h2>

<h3 id="31-原始员工制度">3.1 原始员工制度</h3>

<p>假设企业当前有效的员工手册中存在以下示例条款：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>第三章：休假管理

3.1 年假额度
符合公司规定的正式员工，每年享有 10 天带薪年假。

3.2 年假申请
员工申请年假，应至少提前 3 个工作日提交申请，
经直属主管审批后方可休假。

3.3 年假结转
当年度未使用的年假，按照公司另行发布的结转规则处理。

第四章：费用报销

4.1 差旅住宿
员工因公出差产生的住宿费用，应符合对应职级的报销标准。

4.2 报销材料
员工提交住宿费报销时，应提供合规发票、费用明细
及符合公司要求的出差审批材料。
</code></pre></div></div>

<p>这里的具体条款和数字仅用于演示知识库设计，不代表任何真实企业的制度。</p>

<p>原始文档通常按照章节、条款、段落和表格组织。但检索系统需要将它们转换为适合查询的片段。</p>

<h3 id="32-设计-chunk">3.2 设计 Chunk</h3>

<p>可以按照制度主题和条款边界，将上述内容切分成以下 Chunk：</p>

<p><strong>Chunk 001：年假额度</strong></p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>符合公司规定的正式员工，每年享有 10 天带薪年假。
</code></pre></div></div>

<p><strong>Chunk 002：年假申请流程</strong></p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>员工申请年假，应至少提前 3 个工作日提交申请，
经直属主管审批后方可休假。
</code></pre></div></div>

<p><strong>Chunk 003：年假结转规则</strong></p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>当年度未使用的年假，按照公司另行发布的结转规则处理。
</code></pre></div></div>

<p><strong>Chunk 004：差旅住宿报销标准</strong></p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>员工因公出差产生的住宿费用，应符合对应职级的报销标准。
</code></pre></div></div>

<p><strong>Chunk 005：住宿费报销材料</strong></p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>员工提交住宿费报销时，应提供合规发票、费用明细
及符合公司要求的出差审批材料。
</code></pre></div></div>

<p>这些 Chunk 并非随机切分，而是尽量让每个片段表达一个相对完整的制度主题。</p>

<p>当用户询问年假额度时，Chunk 001 是主要候选；当用户询问申请时间和审批要求时，Chunk 002 更有价值。</p>

<h3 id="33-为什么不把整个章节放进一个-chunk">3.3 为什么不把整个章节放进一个 Chunk？</h3>

<p>假设把第三章全部内容合并为一个 Chunk：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Chunk A：
年假额度、年假申请流程、年假结转规则……
</code></pre></div></div>

<p>这种方式也能工作，但存在一些潜在问题：</p>

<ul>
  <li>一个 Chunk 中可能包含多个不同问题的答案。</li>
  <li>检索结果可能包含较多无关文本。</li>
  <li>上下文变长，增加生成成本。</li>
  <li>相关性排序可能更难判断具体条款是否直接回答了问题。</li>
</ul>

<p>不过，切分也不能过度细化。</p>

<p>例如，将年假申请条款拆成两个 Chunk：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Chunk A：员工申请年假，应至少提前 3 个工作日提交申请。

Chunk B：经直属主管审批后方可休假。
</code></pre></div></div>

<p>如果用户问“年假需要经过审批吗”，第二个片段可以独立回答。但如果问题是“年假申请需要提前多久，以及由谁审批”，系统就需要同时召回两个片段。</p>

<p>因此，对于实际制度文档，可以考虑按条款切分，并在条款包含多个紧密相关的条件时，将它们保留在同一个 Chunk 中。</p>

<p><strong>判断切分是否合理的标准，不是 Chunk 越短越好，而是它能否完整支持目标问题的回答。</strong></p>

<h3 id="34-为-chunk-添加元数据">3.4 为 Chunk 添加元数据</h3>

<p>仅保存 Chunk 的正文还不够。企业知识库还需要保存文档来源、版本、适用范围和权限等信息。</p>

<p>例如：</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"chunk_id"</span><span class="p">:</span><span class="w"> </span><span class="s2">"EMP-LEAVE-002"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"document_id"</span><span class="p">:</span><span class="w"> </span><span class="s2">"EMP-HANDBOOK-2026"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"document_title"</span><span class="p">:</span><span class="w"> </span><span class="s2">"员工手册"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"section"</span><span class="p">:</span><span class="w"> </span><span class="s2">"第三章 休假管理 / 3.2 年假申请"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"content"</span><span class="p">:</span><span class="w"> </span><span class="s2">"员工申请年假，应至少提前 3 个工作日提交申请，经直属主管审批后方可休假。"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"document_version"</span><span class="p">:</span><span class="w"> </span><span class="s2">"2026.1"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"effective_from"</span><span class="p">:</span><span class="w"> </span><span class="s2">"2026-01-01"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"department"</span><span class="p">:</span><span class="w"> </span><span class="s2">"all"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"access_scope"</span><span class="p">:</span><span class="w"> </span><span class="s2">"all_employees"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"chunk_index"</span><span class="p">:</span><span class="w"> </span><span class="mi">2</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>以上 JSON 是示例结构。实际字段应根据企业的数据治理要求设计。</p>

<p>这些字段可以支持：</p>

<ul>
  <li>按文档版本筛选当前有效制度。</li>
  <li>根据适用对象确定哪些条款可以使用。</li>
  <li>将答案关联回具体章节。</li>
  <li>在制度更新时定位需要替换的 Chunk。</li>
  <li>对访问受限的资料执行权限过滤。</li>
</ul>

<p>尤其需要注意：<strong>权限过滤不能只依赖大模型的提示词。</strong> 应在检索系统或其可信的服务端逻辑中执行访问控制，避免未授权内容进入模型上下文。</p>

<hr />

<h2 id="四从用户提问到检索结果">四、从用户提问到检索结果</h2>

<h3 id="41-用户提出问题">4.1 用户提出问题</h3>

<p>假设员工在 AI 助手中输入：</p>

<blockquote>
  <p>正式员工休年假需要提前多久申请？需要谁审批？</p>
</blockquote>

<p>系统首先需要理解问题中包含哪些信息：</p>

<ul>
  <li>主题：年假申请。</li>
  <li>目标信息：提前申请时间、审批人。</li>
  <li>适用对象：正式员工。</li>
  <li>可能涉及的制度章节：休假管理。</li>
</ul>

<p>这里不一定需要调用 LLM 改写查询。对于表述清晰的简单问题，可以直接使用原始查询进行检索。</p>

<p>只有在问题过于口语化、存在指代不清或需要拆分多个子问题时，Query 改写或查询拆分才可能带来收益。</p>

<h3 id="42-什么是召回">4.2 什么是召回？</h3>

<p>召回（Retrieval）是从知识库中找出可能与用户问题有关的资料。</p>

<p>假设企业知识库有 10 万个 Chunk。系统不可能每次都把全部 10 万个片段交给大模型，因此需要先用检索算法缩小候选范围。</p>

<p>例如：</p>

<pre><code class="language-mermaid">flowchart TD
    A[整个知识库：100,000 个 Chunk] --&gt; B[初步召回：100 个候选 Chunk]
    B --&gt; C[Rerank 重排序：选出最相关的 5 个 Chunk]
    C --&gt; D[将相关内容交给 LLM]
</code></pre>

<p>以上数量只是示例，不是固定配置。</p>

<p>召回阶段通常更关注 Recall，也就是尽可能找回所有真正相关的资料。</p>

<p>假设测试问题有 10 个真正相关的 Chunk：</p>

<ul>
  <li>找回 9 个，Recall 为 90%。</li>
  <li>找回 5 个，Recall 为 50%。</li>
  <li>找回 2 个，Recall 为 20%。</li>
</ul>

<p>召回率越高，漏掉有用资料的风险通常越低。</p>

<p>但这不意味着应该无限增加召回数量。候选内容越多，重复和无关信息也可能越多，增加后续排序与生成的成本。</p>

<h3 id="43-bm25根据关键词匹配进行检索">4.3 BM25：根据关键词匹配进行检索</h3>

<p>BM25 是一种经典的信息检索排序算法，用于评估查询词与文档之间的匹配程度。</p>

<p>例如，员工询问：</p>

<blockquote>
  <p>年假申请要提前几个工作日？</p>
</blockquote>

<p>知识库中的原文是：</p>

<blockquote>
  <p>员工申请年假，应至少提前 3 个工作日提交申请。</p>
</blockquote>

<p>BM25 可以利用“年假”“申请”“提前”“工作日”等词语的匹配情况，给这个 Chunk 较高的相关性分数。</p>

<p>BM25 通常会综合考虑：</p>

<ul>
  <li>查询词是否出现在文档中。</li>
  <li>某个词在文档中出现的频率。</li>
  <li>该词在整个文档集合中的区分能力。</li>
  <li>文档长度等因素。</li>
</ul>

<p>它的优势是适合精确词项匹配。例如：</p>

<ul>
  <li>报销制度编号。</li>
  <li>考勤异常代码。</li>
  <li>特定制度名称。</li>
  <li>明确的金额、型号或业务术语。</li>
</ul>

<p>但关键词检索也有局限。</p>

<p>例如：</p>

<blockquote>
  <p>我想请几天假，最晚要什么时候报备？</p>
</blockquote>

<p>如果原文使用的是“年假申请”，而不是“请假报备”，纯关键词检索可能无法稳定找到最相关的条款。</p>

<p>这就需要考虑向量检索。</p>

<h3 id="44-向量检索根据语义相似度进行检索">4.4 向量检索：根据语义相似度进行检索</h3>

<p>Embedding 模型可以将文本编码为向量表示。</p>

<p>例如：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>用户问题：
我想请几天假，最晚要什么时候报备？

知识库 Chunk：
员工申请年假，应至少提前 3 个工作日提交申请。
</code></pre></div></div>

<p>虽然两者使用的词语不完全相同，但它们表达的意思接近。</p>

<p>向量检索通过比较查询向量和 Chunk 向量之间的距离或相似度，找出语义上接近的候选片段。</p>

<p>通常可以使用余弦相似度或其他向量距离指标，但具体方法取决于 Embedding 模型和向量数据库的配置。</p>

<p>向量检索的优势是能够处理同义表达、自然语言问题和不同措辞之间的语义联系。</p>

<p>但必须区分：</p>

<ul>
  <li>语义相似，不代表事实相同。</li>
  <li>语义相似，不代表制度适用范围相同。</li>
  <li>语义相似，不代表某条制度当前仍然有效。</li>
</ul>

<p>例如，旧版员工手册中的年假规则可能与新版非常相似，但两者的有效期限不同。仅凭向量相似度，无法判断应该采用哪一个版本。</p>

<p>因此，企业知识库需要将语义检索与版本、权限和业务规则结合起来。</p>

<h3 id="45-为什么使用-bm25--向量检索混合召回">4.5 为什么使用 BM25 + 向量检索混合召回？</h3>

<p>两种检索方式擅长处理不同类型的查询。</p>

<table>
  <thead>
    <tr>
      <th>维度</th>
      <th>BM25</th>
      <th>向量检索</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>主要依据</td>
      <td>关键词匹配</td>
      <td>语义相似度</td>
    </tr>
    <tr>
      <td>精确术语</td>
      <td>通常表现较好</td>
      <td>取决于 Embedding 模型</td>
    </tr>
    <tr>
      <td>同义表达</td>
      <td>可能漏检</td>
      <td>通常更有优势</td>
    </tr>
    <tr>
      <td>数字、制度编号</td>
      <td>有助于精确匹配</td>
      <td>可能把含义相近但数字不同的文本召回</td>
    </tr>
    <tr>
      <td>主要风险</td>
      <td>无法覆盖不同措辞</td>
      <td>语义接近但事实不匹配</td>
    </tr>
  </tbody>
</table>

<p>混合召回的基本思路是：</p>

<pre><code class="language-mermaid">flowchart TD
    A[用户问题] --&gt; B[BM25 检索]
    A --&gt; C[向量检索]
    B --&gt; D[关键词候选]
    C --&gt; E[语义候选]
    D --&gt; F[合并与去重]
    E --&gt; F
    F --&gt; G[候选 Chunk 集合]
</code></pre>

<p>例如，BM25 找到了年假申请条款，而向量检索找到了使用“请假报备”措辞的相关内容。合并两路结果，可以提高找到有效答案的机会。</p>

<p>合并结果时，可以采用 Reciprocal Rank Fusion（RRF，倒数排名融合）等方法，根据候选在不同检索结果中的排名进行融合。</p>

<p>一个简化的 RRF 形式为：</p>

\[RRF(d)=\sum_{r \in R}\frac{1}{k+\operatorname{rank}_r(d)}\]

<p>其中：</p>

<ul>
  <li>$d$ 表示候选 Chunk。</li>
  <li>$R$ 表示不同检索器的结果集合。</li>
  <li>$\operatorname{rank}_r(d)$ 表示 Chunk 在某个检索结果中的排名。</li>
  <li>$k$ 是用于平滑排名影响的常数。</li>
</ul>

<p>RRF 不要求 BM25 分数和向量相似度必须处于相同数值范围，因此是一种常见的结果融合方式。</p>

<p>但混合检索不是必然优于单一检索。是否需要两路召回，应通过实际测试集比较 Recall@K、Precision@K、延迟和成本后决定。</p>

<h3 id="46-rerank对候选-chunk-进行精细排序">4.6 Rerank：对候选 Chunk 进行精细排序</h3>

<p>混合召回解决的是“哪些资料值得进一步考虑”，而 Rerank 解决的是“哪些资料最值得优先使用”。</p>

<p>假设初步召回了以下候选：</p>

<table>
  <thead>
    <tr>
      <th>Chunk</th>
      <th>内容</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>正式员工每年享有 10 天带薪年假。</td>
    </tr>
    <tr>
      <td>B</td>
      <td>员工申请年假，应至少提前 3 个工作日提交申请，经直属主管审批后方可休假。</td>
    </tr>
    <tr>
      <td>C</td>
      <td>员工请病假时，应及时通知直属主管。</td>
    </tr>
    <tr>
      <td>D</td>
      <td>员工提交年假结转申请时，应遵循当年度结转规则。</td>
    </tr>
  </tbody>
</table>

<p>对于问题：</p>

<blockquote>
  <p>正式员工休年假需要提前多久申请？需要谁审批？</p>
</blockquote>

<p>Chunk B 是最直接的答案。</p>

<p>其他 Chunk 可能包含“年假”“员工”“申请”等相关词语，但并不能完整回答问题。</p>

<p>Rerank 模型可以将用户问题与每个候选 Chunk 结合起来，对它们的相关性进行更精细的评估。</p>

<p>常见的实现方式是 Cross-Encoder 类模型：模型同时读取查询和候选文本，再输出相关性分数。</p>

<p>需要注意，Rerank 不一定是通用大语言模型。实践中常用专门训练的排序模型，因为它们更适合高效地比较查询与候选文本之间的相关性。</p>

<p>经过排序后，系统可以选取前几个 Chunk，交给后续生成模型。</p>

<p>Rerank 的优势是改善候选排序，但也会引入额外的计算成本和延迟。因此，是否启用、处理多少候选，以及选用哪种模型，都应该通过实际评测确定。</p>

<hr />

<h2 id="五从检索结果生成答案">五、从检索结果生成答案</h2>

<h3 id="51-组装上下文">5.1 组装上下文</h3>

<p>经过召回与排序后，系统获得与问题最相关的制度片段。</p>

<p>例如：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[来源：员工手册 / 第三章 休假管理 / 3.2 年假申请]

员工申请年假，应至少提前 3 个工作日提交申请，
经直属主管审批后方可休假。
</code></pre></div></div>

<p>接下来，系统将用户问题和检索到的资料一起提供给 LLM。</p>

<p>可以采用类似下面的提示词：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>你是企业员工制度问答助手。

请根据提供的制度资料回答员工问题。

要求：
1. 以提供的制度资料为主要依据。
2. 不要编造资料中没有的制度、数字或审批条件。
3. 如果资料不足以回答问题，请明确说明。
4. 如果存在适用范围或版本差异，请指出差异。
5. 在答案中注明制度来源。

用户问题：
正式员工休年假需要提前多久申请？需要谁审批？

制度资料：
员工申请年假，应至少提前 3 个工作日提交申请，
经直属主管审批后方可休假。
</code></pre></div></div>

<h3 id="52-生成最终答案">5.2 生成最终答案</h3>

<p>模型可以生成：</p>

<blockquote>
  <p>正式员工申请年假，应至少提前 3 个工作日提交申请，并经直属主管审批后方可休假。</p>

  <p>来源：员工手册，第三章“休假管理”，第 3.2 条“年假申请”。</p>
</blockquote>

<p>这比直接让模型根据通用知识回答更容易验证，因为答案中的具体规则可以追溯到原始制度。</p>

<p>但提示词本身并不能保证模型完全忠实于资料。生产环境还应检查引用是否真实存在、引用内容是否支持对应结论，以及模型是否遗漏重要的适用条件。</p>

<h3 id="53-如果检索不到答案怎么办">5.3 如果检索不到答案怎么办？</h3>

<p>假设员工询问：</p>

<blockquote>
  <p>年假最多可以连续休多少天？</p>
</blockquote>

<p>但当前知识库只包含年假额度和申请流程，没有连续休假天数的规定。</p>

<p>此时不应让模型根据常识自行补出一个数字。</p>

<p>更合理的回答是：</p>

<blockquote>
  <p>当前检索到的员工制度资料没有明确说明年假最多可以连续休多少天。建议查阅完整休假制度或向人力资源部门确认。</p>
</blockquote>

<p>在企业制度问答中，能够识别知识缺口和明确表达不确定性，同样是系统质量的重要组成部分。</p>

<hr />

<h2 id="六如何处理报销和考勤问题">六、如何处理报销和考勤问题？</h2>

<p>同一套 RAG 架构可以服务于不同的员工制度主题，但切分策略和检索条件需要根据具体业务调整。</p>

<h3 id="61-报销制度示例">6.1 报销制度示例</h3>

<p>用户问题：</p>

<blockquote>
  <p>出差住酒店报销需要哪些材料？</p>
</blockquote>

<p>知识库中有两个相关 Chunk：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Chunk 004：
员工因公出差产生的住宿费用，应符合对应职级的报销标准。

Chunk 005：
员工提交住宿费报销时，应提供合规发票、费用明细
及符合公司要求的出差审批材料。
</code></pre></div></div>

<p>这里，Chunk 005 可以直接回答材料要求，Chunk 004 则提供报销适用条件。</p>

<p>如果员工进一步询问：</p>

<blockquote>
  <p>我是 P5 级员工，住宿费每天最多能报销多少？</p>
</blockquote>

<p>系统需要检索对应职级的具体标准。如果知识库没有该标准，就不能只根据“对应职级的报销标准”推导出具体金额。</p>

<p>这说明企业 RAG 不只是要找到主题相关的文本，还要判断检索结果是否包含回答所需的全部信息。</p>

<h3 id="62-考勤制度示例">6.2 考勤制度示例</h3>

<p>用户问题：</p>

<blockquote>
  <p>忘记打卡怎么办？</p>
</blockquote>

<p>知识库可能包含：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Chunk 006：
员工上下班应按照公司要求完成考勤打卡。

Chunk 007：
员工因特殊情况未能正常打卡时，应按照考勤异常处理流程
提交说明及相关证明，并由对应负责人审批。
</code></pre></div></div>

<p>如果系统只召回 Chunk 006，虽然内容与考勤有关，但没有完整回答忘记打卡后的处理方法。</p>

<p>因此，在设计 Chunk 时，应尽量将操作流程、适用条件和审批要求保留完整；在评估检索质量时，也要测试系统是否能够找齐回答问题所需的多个片段。</p>

<hr />

<h2 id="七企业-rag-的关键工程问题">七、企业 RAG 的关键工程问题</h2>

<h3 id="71-制度版本与增量更新">7.1 制度版本与增量更新</h3>

<p>员工制度可能每年更新，部分制度也可能临时调整。</p>

<p>如果新版制度已经生效，但向量数据库中仍然存在旧版 Chunk，系统就可能召回过期规定。</p>

<p>因此，建议为每份文档保存：</p>

<ul>
  <li>文档 ID 和版本号。</li>
  <li>生效日期和失效日期。</li>
  <li>文档状态。</li>
  <li>适用对象。</li>
  <li>来源文件及章节定位。</li>
</ul>

<p>制度更新时，应识别变更内容，更新对应的 Chunk 和检索索引，并确保失效制度不再作为当前有效答案的依据。</p>

<p>对于重要制度，建议保留变更记录和索引更新时间，以便排查为什么系统在某个时间点返回了特定规则。</p>

<h3 id="72-权限与知识隔离">7.2 权限与知识隔离</h3>

<p>企业知识库不一定对所有员工开放。</p>

<p>例如：</p>

<ul>
  <li>普通员工可以查询通用年假和考勤制度。</li>
  <li>部门负责人可能可以访问部分部门级流程。</li>
  <li>人力资源人员可能可以访问受限的人事政策。</li>
</ul>

<p>系统应在检索阶段，根据已经验证的用户身份和授权范围限制候选文档。</p>

<p>不能先将所有敏感资料检索出来，再仅仅依靠提示词要求模型不要泄露。</p>

<p>权限过滤还应覆盖引用来源、缓存、日志和后续工具调用，避免未授权信息通过其他路径泄露。</p>

<h3 id="73-结构化数据不一定需要向量检索">7.3 结构化数据不一定需要向量检索</h3>

<p>不是所有员工问题都适合通过 RAG 解决。</p>

<p>例如：</p>

<ul>
  <li>“差旅住宿费的报销标准是什么？”适合检索制度文档。</li>
  <li>“我的报销单现在审批到哪一步了？”可能需要调用报销系统 API。</li>
  <li>“我本年度还剩几天年假？”可能需要查询 HR 系统中的个人余额。</li>
</ul>

<p>可以根据问题类型路由到不同的数据源：</p>

<table>
  <thead>
    <tr>
      <th>问题类型</th>
      <th>建议处理方式</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>查询制度条款</td>
      <td>RAG 文档检索</td>
    </tr>
    <tr>
      <td>查询个人年假余额</td>
      <td>调用 HR 系统 API</td>
    </tr>
    <tr>
      <td>查询报销审批状态</td>
      <td>调用报销系统 API</td>
    </tr>
    <tr>
      <td>计算报销金额</td>
      <td>使用明确的业务规则和计算逻辑</td>
    </tr>
    <tr>
      <td>需要综合多个制度的复杂问题</td>
      <td>RAG 检索后由 LLM 综合分析</td>
    </tr>
  </tbody>
</table>

<p>需要注意，个人余额、审批状态等动态业务数据不应仅依靠静态员工手册回答。它们需要来自有权限控制的实时业务系统。</p>

<hr />

<h2 id="八如何评估-rag-是否真正有效">八、如何评估 RAG 是否真正有效？</h2>

<p>不能因为系统能够返回一段看似合理的答案，就认为 RAG 已经搭建成功。</p>

<p>建议将评估拆分为检索质量、答案质量、性能与成本几个维度。</p>

<h3 id="81-检索指标">8.1 检索指标</h3>

<p><strong>Recall@K（前 K 个结果的召回率）</strong></p>

<p>衡量前 K 个检索结果找回了多少真正相关的资料。</p>

\[Recall@K =
\frac{\text{前 K 个结果中的相关资料数}}
{\text{全部相关资料数}}\]

<p>假设某个测试问题有 5 个相关 Chunk，系统前 10 个结果找到了其中 4 个：</p>

\[Recall@10 = \frac{4}{5}=80\%\]

<p>Recall@K 越高，通常表示系统漏掉的相关资料越少。</p>

<p><strong>Precision@K（前 K 个结果的精确率）</strong></p>

<p>衡量前 K 个结果中，有多少是真正相关的资料。</p>

\[Precision@K =
\frac{\text{前 K 个结果中的相关资料数}}{K}\]

<p>假设前 10 个结果中有 6 个相关：</p>

\[Precision@10 = \frac{6}{10}=60\%\]

<p>Recall 和 Precision 需要结合观察：只返回极少数结果可能很精确，却容易漏掉答案；返回大量结果可能找得更全，却带入许多无关资料。</p>

<p><strong>MRR（Mean Reciprocal Rank）</strong></p>

<p>衡量第一个相关结果出现得有多靠前。相关结果越早出现，MRR 通常越高。</p>

<p><strong>nDCG（Normalized Discounted Cumulative Gain）</strong></p>

<p>衡量排序结果的整体质量，并考虑不同排名位置的价值。越相关的结果排得越靠前，通常越有利。</p>

<h3 id="82-答案质量指标">8.2 答案质量指标</h3>

<p>检索正确不代表生成一定正确。</p>

<p>建议测试：</p>

<ul>
  <li><strong>答案正确率：</strong> 是否正确回答问题。</li>
  <li><strong>忠实度（Faithfulness）：</strong> 答案中的事实是否得到检索资料支持。</li>
  <li><strong>引用准确率：</strong> 引用是否指向真实存在、且能够支持结论的内容。</li>
  <li><strong>拒答合理性：</strong> 知识库缺少答案时，是否能够明确说明信息不足。</li>
  <li><strong>条件完整性：</strong> 是否遗漏审批人、适用对象、生效时间等关键条件。</li>
</ul>

<p>可以构建一组标准测试问题：</p>

<table>
  <thead>
    <tr>
      <th>测试问题</th>
      <th>主要验证目标</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>正式员工每年有多少天年假？</td>
      <td>精确数字检索</td>
    </tr>
    <tr>
      <td>年假需要提前多久申请？</td>
      <td>条款定位</td>
    </tr>
    <tr>
      <td>请假需要谁审批？</td>
      <td>条件与流程完整性</td>
    </tr>
    <tr>
      <td>住宿费报销需要哪些材料？</td>
      <td>多项要求召回</td>
    </tr>
    <tr>
      <td>忘记打卡应该怎么办？</td>
      <td>操作流程检索</td>
    </tr>
    <tr>
      <td>旧版和新版制度规定不同，应该按哪个执行？</td>
      <td>版本管理</td>
    </tr>
    <tr>
      <td>当前制度没有说明连续休假上限，能否回答具体天数？</td>
      <td>拒答与不确定性处理</td>
    </tr>
  </tbody>
</table>

<p>这些测试问题可以持续用于比较不同 Chunk 策略、检索参数和模型版本。</p>

<h3 id="83-延迟和成本">8.3 延迟和成本</h3>

<p>RAG 会增加检索、排序和上下文处理的开销。</p>

<p>例如，在线请求可能经过：</p>

<pre><code class="language-mermaid">flowchart TD
    A[问题处理] --&gt; B[BM25 与向量检索（并行）]
    B --&gt; C[合并去重]
    C --&gt; D[Rerank]
    D --&gt; E[组装上下文]
    E --&gt; F[LLM 生成]
</code></pre>

<p>其中，BM25 和向量检索可以并行执行；Query 改写和 Rerank 则不一定适合每个请求。</p>

<p>实际系统应监控：</p>

<ul>
  <li>首次输出延迟。</li>
  <li>完整回答延迟。</li>
  <li>P50、P95 等延迟分位数。</li>
  <li>输入与输出 Token 数量。</li>
  <li>单次请求成本。</li>
  <li>检索失败率和重试次数。</li>
</ul>

<p>不能只追求 Recall@K，而忽略线上延迟。也不能只追求低成本，而让系统经常漏掉真正的制度条款。</p>

<h3 id="84-通过对照实验选择检索方案">8.4 通过对照实验选择检索方案</h3>

<p>建议至少比较以下几种配置：</p>

<table>
  <thead>
    <tr>
      <th>方案</th>
      <th>检索方式</th>
      <th>主要目的</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>仅 BM25</td>
      <td>建立关键词检索基线</td>
    </tr>
    <tr>
      <td>B</td>
      <td>仅向量检索</td>
      <td>建立语义检索基线</td>
    </tr>
    <tr>
      <td>C</td>
      <td>混合召回</td>
      <td>验证两种检索方式是否互补</td>
    </tr>
    <tr>
      <td>D</td>
      <td>混合召回 + Rerank</td>
      <td>验证重排序能否提升最终质量</td>
    </tr>
  </tbody>
</table>

<p>在同一组测试问题、同一套制度快照和一致的评估条件下，比较各方案的 Recall@K、Precision@K、答案正确率、引用准确率、P95 延迟与请求成本。</p>

<p>如果混合召回的提升很小，而延迟和成本明显增加，就应考虑保留更简单的方案。</p>

<p>如果 Rerank 明显改善了关键制度问题的排序与回答质量，再决定是否将其纳入生产链路。</p>

<hr />

<h2 id="九总结从最小可用-rag-开始">九、总结：从最小可用 RAG 开始</h2>

<p>为企业搭建员工制度知识库，不需要一开始就引入所有复杂组件。</p>

<p>一个合理的实施顺序是：</p>

<ol>
  <li><strong>整理知识源：</strong> 收集当前有效的员工手册、报销制度和考勤规范。</li>
  <li><strong>设计 Chunk：</strong> 优先按照章节、条款和业务语义切分，避免破坏关键条件。</li>
  <li><strong>保存元数据：</strong> 记录来源、版本、生效时间、适用范围和访问权限。</li>
  <li><strong>建立检索索引：</strong> 根据查询特点选择关键词检索、向量检索或混合召回。</li>
  <li><strong>接入 LLM：</strong> 将相关制度片段交给模型生成答案，并要求提供来源。</li>
  <li><strong>建立测试集：</strong> 用真实员工问题验证召回质量、答案正确性和引用准确率。</li>
  <li><strong>持续优化：</strong> 根据漏检、误检、过期知识、延迟和成本数据调整系统。</li>
</ol>

<p>整个过程可以概括为：</p>

<p><strong>文档解析、Chunk 切分、元数据管理、检索召回、按需 Rerank、LLM 生成、引用验证与评测迭代。</strong></p>

<p>其中最重要的不是把每个技术名词都堆进系统，而是理解每个组件解决什么问题，以及它是否真正改善了业务结果。</p>

<p>对于员工制度问答，Chunk 决定知识如何组织，检索决定能否找到正确资料，Rerank 决定候选资料的优先级，LLM 负责根据资料组织答案，而版本管理、权限控制和评测决定系统能否可靠地运行在企业环境中。</p>]]></content><author><name>Cerostep</name></author><category term="AI 应用开发" /><summary type="html"><![CDATA[从 Chunk、Embedding、混合检索与 Rerank 出发，通过员工年假、报销和考勤场景，理解如何设计可追溯、可评估、可落地的企业 RAG 知识库。]]></summary></entry><entry xml:lang="en"><title type="html">Cross-Border E-Commerce AI Shopping Assistant: Retrieval, Agent Orchestration, and Context Management</title><link href="https://www.cerostep.com/en/2026/10/15/cross-border-ecommerce-ai-shopping-assistant/" rel="alternate" type="text/html" title="Cross-Border E-Commerce AI Shopping Assistant: Retrieval, Agent Orchestration, and Context Management" /><published>2026-10-15T16:00:00+00:00</published><updated>2026-10-15T16:00:00+00:00</updated><id>https://www.cerostep.com/en/2026/10/15/cross-border-ecommerce-ai-shopping-assistant-en</id><content type="html" xml:base="https://www.cerostep.com/en/2026/10/15/cross-border-ecommerce-ai-shopping-assistant/"><![CDATA[<h2 id="summary">Summary</h2>

<p>Consider a request such as:</p>

<blockquote>
  <p>Recommend camping gear in the low-to-mid price range and ship it to Sydney.</p>
</blockquote>

<p>This is more than a product search. It is a decision workflow that must interpret the request, retrieve products, evaluate candidates, verify prices and inventory, confirm shipping eligibility, and present useful results.</p>

<p>A reliable cross-border AI shopping assistant needs to address four core questions:</p>

<ol>
  <li>How can keyword and vector search work together to find products that match the user’s actual intent?</li>
  <li>When should the system call a tool, delegate to a sub-agent, or run tasks in parallel?</li>
  <li>How can context be compressed without losing the constraints, evidence, and execution state needed to complete the task?</li>
  <li>How should the system choose tools, execution strategies, and models based on task complexity, quality requirements, latency, and cost?</li>
</ol>

<p>This article explores these questions from both a system-design and an implementation perspective.</p>

<hr />

<h2 id="1-keyword-search-and-vector-search">1. Keyword Search and Vector Search</h2>

<h3 id="11-key-differences">1.1 Key differences</h3>

<p><strong>Keyword search</strong> retrieves results based on matches between query terms and terms in product content. Common implementations include inverted indexes and BM25. It works well for brands, model numbers, SKUs, explicit specifications, and exact attributes.</p>

<p><strong>Vector search</strong> encodes a query and product content as vectors using an embedding model, then retrieves candidates based on vector distance or similarity. It is useful for synonyms, conversational descriptions, implicit needs, and related concepts expressed with different wording.</p>

<table>
  <thead>
    <tr>
      <th>Retrieval method</th>
      <th>Main strengths</th>
      <th>Main limitations</th>
      <th>Typical use cases</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Keyword search</td>
      <td>Precise and explainable; effective for explicit terms and structured fields</td>
      <td>Limited recall for synonyms and cross-language paraphrases</td>
      <td>Brands, model numbers, SKUs, specifications</td>
    </tr>
    <tr>
      <td>Vector search</td>
      <td>Captures semantic similarity and supports natural-language queries</td>
      <td>Semantic similarity does not prove a fact; irrelevant candidates may be retrieved</td>
      <td>Conversational needs, synonyms, cross-language retrieval</td>
    </tr>
    <tr>
      <td>Hybrid retrieval</td>
      <td>Combines term matching and semantic recall</td>
      <td>Requires candidate merging, deduplication, and ranking</td>
      <td>General product discovery and recommendations</td>
    </tr>
  </tbody>
</table>

<h3 id="12-why-can-rugged-and-drop-resistant-match-a-product-that-uses-different-wording">1.2 Why can “rugged and drop-resistant” match a product that uses different wording?</h3>

<p>Suppose a user searches for “rugged and drop-resistant,” but a product page does not use those exact words. Instead, it says:</p>

<ul>
  <li>“Impact-resistant ABS housing”</li>
  <li>“Passed a 1.5-meter drop test”</li>
  <li>“Reinforced structural design”</li>
  <li>“Durability optimized for outdoor use”</li>
</ul>

<p>Vector search may retrieve the product because embedding models learn statistical relationships between words, sentences, and contexts during training. Terms such as “drop-resistant,” “impact-resistant,” and “drop-tested” may be close in vector space.</p>

<p>However, three concepts must remain distinct:</p>

<ol>
  <li><strong>Semantic similarity does not mean equivalent attributes.</strong> “Waterproof” and “suitable for rainy weather” may be semantically related, but they do not imply the same protection rating.</li>
  <li><strong>Semantic similarity does not establish a fact.</strong> “Military-grade design” does not necessarily mean the product has passed a particular standard or certification test.</li>
  <li><strong>Retrieval is not performance verification.</strong> Vector search can discover candidates; it cannot by itself prove that a product is drop-resistant.</li>
</ol>

<p>In cross-border commerce, users may describe their needs in Chinese while product titles, specifications, and certifications are in English or another language. Multilingual embeddings can help with cross-language retrieval, but key specifications and supporting evidence still need to be verified.</p>

<h3 id="13-recommended-approach-hybrid-retrieval-and-reranking">1.3 Recommended approach: hybrid retrieval and reranking</h3>

<p>Use <strong>hybrid retrieval</strong> rather than choosing between keyword and vector search.</p>

<p>A recommended workflow:</p>

<ol>
  <li><strong>Parse the request:</strong> extract product categories, budget, destination, hard constraints, and soft preferences.</li>
  <li><strong>Retrieve candidates in parallel:</strong> use keyword and vector search independently.</li>
  <li><strong>Merge and deduplicate:</strong> reconcile product IDs, SKUs, and variants to avoid duplicate candidates.</li>
  <li><strong>Rerank for relevance:</strong> use BM25 scores, vector similarity, a Cross-Encoder, or another reranker to assess query-product relevance.</li>
  <li><strong>Filter hard constraints:</strong> verify price limits, inventory, and destination shipping eligibility.</li>
  <li><strong>Validate evidence:</strong> for attributes such as durability, water resistance, or load capacity, prefer specifications, test reports, or trustworthy product records.</li>
  <li><strong>Generate recommendations:</strong> present the rationale, price, evidence for performance claims, shipping information, and relevant caveats.</li>
</ol>

<p>An important principle is: <strong>validate or filter hard constraints first; use soft preferences mainly for ranking.</strong></p>

<p>For example, a product that cannot be shipped to Sydney should not make the final recommendation list, even if its semantic similarity score is high.</p>

<hr />

<h2 id="2-sub-agent-delegation-and-parallel-execution">2. Sub-Agent Delegation and Parallel Execution</h2>

<h3 id="21-distinguishing-tool-calls-sub-agents-and-parallel-execution">2.1 Distinguishing tool calls, sub-agents, and parallel execution</h3>

<ul>
  <li><strong>Tool calling</strong> performs a specific operation, such as querying a product API, checking inventory, or calculating a total.</li>
  <li>A <strong>sub-agent</strong> receives a relatively self-contained subgoal and works with its own context, tool permissions, or execution strategy.</li>
  <li><strong>Parallel execution</strong> runs multiple tasks at the same time. It does not require a multi-agent architecture; one agent can issue several tool calls in parallel.</li>
</ul>

<p>Not every tool call should be wrapped in an agent. Querying the price of one product usually requires only a product API call. Searching for several products does not mean that each product needs its own agent.</p>

<h3 id="22-when-is-it-worth-delegating-to-a-sub-agent">2.2 When is it worth delegating to a sub-agent?</h3>

<p>Evaluate four factors:</p>

<ol>
  <li><strong>Decomposability:</strong> Can the task be split into relatively independent subtasks, such as researching tents, sleep systems, and lighting?</li>
  <li><strong>Dependencies:</strong> Can a subtask make progress without waiting for the results of another?</li>
  <li><strong>Specialization benefit:</strong> Do different subtasks need different tools, retrieval strategies, prompts, or validation logic?</li>
  <li><strong>Cost-benefit:</strong> Do the latency or quality gains from parallel work outweigh startup, coordination, aggregation, and duplicated-reasoning costs?</li>
</ol>

<p>For a camping-gear recommendation:</p>

<table>
  <thead>
    <tr>
      <th>Subtask</th>
      <th>Suggested approach</th>
      <th>Reason</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Look up the price of one tent</td>
      <td>Call a tool directly</td>
      <td>The input and operation are well defined</td>
    </tr>
    <tr>
      <td>Compare the construction and durability of several tents</td>
      <td>Consider a product-research agent</td>
      <td>Requires synthesizing information across candidates</td>
    </tr>
    <tr>
      <td>Check inventory for tents and sleeping bags</td>
      <td>Call APIs in parallel</td>
      <td>Independent tasks with structured results</td>
    </tr>
    <tr>
      <td>Calculate the total cost of a gear bundle</td>
      <td>Calculate directly or use a calculation tool</td>
      <td>Deterministic; no separate reasoning agent is needed</td>
    </tr>
    <tr>
      <td>Verify shipping restrictions for Australia</td>
      <td>Use a logistics tool or delegate shipping verification</td>
      <td>Depends on data-source complexity and verification needs</td>
    </tr>
    <tr>
      <td>Merge recommendations and remove duplicates</td>
      <td>Keep this with the main agent</td>
      <td>Requires global consistency and a final decision</td>
    </tr>
  </tbody>
</table>

<p>Delegation should depend on task complexity, dependencies, and execution cost—not on the task’s name.</p>

<h3 id="23-why-are-two-agents-running-in-parallel-not-necessarily-faster">2.3 Why are two agents running in parallel not necessarily faster?</h3>

<p>Parallelism reduces waiting only for the portion that can run concurrently. It cannot eliminate dependencies or coordination overhead.</p>

<p>Suppose:</p>

<ul>
  <li>Agent A searches for tents and takes 4 seconds.</li>
  <li>Agent B searches for sleeping bags and takes 5 seconds.</li>
  <li>The main agent takes 2 seconds to aggregate, deduplicate, and verify results.</li>
</ul>

<p>If the tasks run sequentially:</p>

\[T_{\text{serial}} = 4 + 5 + 2 = 11\text{ seconds}\]

<p>If the first two tasks run in parallel:</p>

\[T_{\text{parallel}} = \max(4,5) + 2 = 7\text{ seconds}\]

<p>Under ideal conditions, parallel execution reduces the total time from 11 to 7 seconds, or about 36%.</p>

<p>But if parallel work adds 1.5 seconds of startup and coordination overhead plus 1 second to resolve conflicting data, then:</p>

\[T_{\text{parallel}} = 5 + 1.5 + 2 + 1 = 9.5\text{ seconds}\]

<p>The benefit is much smaller. These numbers illustrate the calculation; they are not production benchmarks.</p>

<p>Common parallel-execution bottlenecks include:</p>

<ul>
  <li><strong>Shared-resource contention:</strong> multiple agents call the same rate-limited API, causing throttling or queues.</li>
  <li><strong>Dependency blocking:</strong> shipping verification requires an SKU that has not yet been selected.</li>
  <li><strong>Duplicate work:</strong> agents find the same product and repeat tool calls.</li>
  <li><strong>Coordination cost:</strong> the main agent must reconcile prices, currencies, shipping terms, and product identifiers.</li>
  <li><strong>Tail latency:</strong> the final response must wait for the slowest required task.</li>
  <li><strong>Conflicting results:</strong> agents may disagree, requiring additional verification.</li>
</ul>

<p>More parallelism does not necessarily mean greater throughput. Shared resources, rate limits, and coordination overhead can offset the gains.</p>

<h3 id="24-use-a-task-dependency-graph-to-plan-execution">2.4 Use a task dependency graph to plan execution</h3>

<p>First parse the request, then plan work according to its dependencies. For example:</p>

<pre><code class="language-mermaid">flowchart TD
    A[Parse user request] --&gt; B[Identify budget and shipping constraints]
    B --&gt; C[Retrieve candidate products]
    C --&gt; D[Group candidates by category]
    D --&gt; E[Research tents]
    D --&gt; F[Research sleep systems]
    D --&gt; G[Research lighting and cookware]
    E --&gt; H[Merge candidates]
    F --&gt; H
    G --&gt; H
    H --&gt; I[Verify prices and product performance]
    I --&gt; J[Check Sydney shipping and total cost]
    J --&gt; K[Optimize for budget and produce recommendations]
</code></pre>

<p>Researching independent product categories is suitable for parallel execution. Budget optimization and final shipping verification depend on aggregated results, so they should not be performed prematurely.</p>

<hr />

<h2 id="3-context-compression-and-preserving-task-information">3. Context Compression and Preserving Task Information</h2>

<h3 id="31-the-goal-is-to-reduce-cost-not-merely-shorten-text">3.1 The goal is to reduce cost, not merely shorten text</h3>

<p>Context compression should reduce token usage while preserving task completion, factual accuracy, and constraint adherence as much as possible.</p>

<p>A shopping assistant should preserve:</p>

<table>
  <thead>
    <tr>
      <th>Information type</th>
      <th>Example</th>
      <th>Recommended handling</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Hard constraints</td>
      <td>Destination is Sydney, a firm budget cap, item must be in stock</td>
      <td>Preserve exactly; do not casually rewrite</td>
    </tr>
    <tr>
      <td>Soft preferences</td>
      <td>Low-to-mid budget, durable, lightweight</td>
      <td>Keep their meaning and priority</td>
    </tr>
    <tr>
      <td>Execution state</td>
      <td>SKUs already queried, verification results, unfinished tasks</td>
      <td>Preserve results, evidence sources, and validity</td>
    </tr>
    <tr>
      <td>Dynamic information</td>
      <td>Prices, inventory, shipping estimates</td>
      <td>Keep timestamps or expiry; re-query when needed</td>
    </tr>
    <tr>
      <td>Evidence and uncertainty</td>
      <td>Seller claims, independent tests, unverified attributes</td>
      <td>Distinguish evidence types; never overstate certainty</td>
    </tr>
  </tbody>
</table>

<p>If a user gives an exact budget, preserve the amount and currency rather than summarizing it as “limited budget.” If the user only says “low-to-mid budget,” do not silently turn that into an unconfirmed price cap. The system can state a transparent default assumption or ask the user when necessary.</p>

<p>Likewise, compression must not turn “the seller claims impact resistance” into “passed an impact-resistance test,” or remove the currency from an Australian-dollar price.</p>

<h3 id="32-evaluate-compression-quality-through-task-performance">3.2 Evaluate compression quality through task performance</h3>

<p>A summary that looks semantically similar to the original conversation may still have dropped information needed for execution. A better evaluation is to give the compressed context to the system and test whether it can complete the original task correctly.</p>

<p>A basic metric is task completion rate:</p>

\[Q_{\text{compression}} =
\frac{\text{test tasks completed correctly after compression}}
{\text{all test tasks}}\]

<p>Evaluation should also track hard-constraint violation rate, factual error rate, tool-call accuracy, and final recommendation quality.</p>

<p>Useful test scenarios include:</p>

<ul>
  <li>After the user specifies a maximum budget, does the system still filter out products that exceed it?</li>
  <li>After the user specifies Sydney as the destination, does the system still verify shipping there?</li>
  <li>When the user requests drop resistance, does the system distinguish seller claims from test evidence?</li>
  <li>After the user rejects a product, does the system avoid recommending it again?</li>
  <li>When a product’s price changes, does the system query it again rather than rely on stale information?</li>
</ul>

<p>Hard-constraint violations should be tracked independently; correct results elsewhere must not cancel them out.</p>

<p>For example:</p>

\[R_{\text{violation}} =
\frac{\text{tasks violating at least one hard constraint}}
{\text{all tasks}}\]

<p>If a compression strategy reduces token cost by 40% but noticeably increases shipping errors, it should not be considered successful. The 40% figure is illustrative, not a universal threshold.</p>

<h3 id="33-use-structured-state-and-on-demand-summaries">3.3 Use structured state and on-demand summaries</h3>

<p>Avoid compressing all task state into one paragraph of natural language. A more robust approach is to preserve critical state in structured form and summarize repetitive conversation or low-value logs on demand.</p>

<p>For example:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"intent"</span><span class="p">:</span><span class="w"> </span><span class="s2">"camping_gear_recommendation"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"destination"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"city"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Sydney"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"country"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Australia"</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"budget"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"level"</span><span class="p">:</span><span class="w"> </span><span class="s2">"low_to_mid"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"currency"</span><span class="p">:</span><span class="w"> </span><span class="s2">"AUD"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"exact_cap"</span><span class="p">:</span><span class="w"> </span><span class="kc">null</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"preferences"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
    </span><span class="s2">"durable"</span><span class="p">,</span><span class="w">
    </span><span class="s2">"value_for_money"</span><span class="w">
  </span><span class="p">],</span><span class="w">
  </span><span class="nl">"constraints"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"shipping_to_destination_required"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"evidence"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"product_specs"</span><span class="p">:</span><span class="w"> </span><span class="p">[],</span><span class="w">
    </span><span class="nl">"shipping_checks"</span><span class="p">:</span><span class="w"> </span><span class="p">[],</span><span class="w">
    </span><span class="nl">"price_checks"</span><span class="p">:</span><span class="w"> </span><span class="p">[]</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"pending_tasks"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
    </span><span class="s2">"retrieve_products"</span><span class="p">,</span><span class="w">
    </span><span class="s2">"verify_shipping"</span><span class="p">,</span><span class="w">
    </span><span class="s2">"compare_total_cost"</span><span class="w">
  </span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>This is an example only; define the actual fields to fit the business requirements.</p>

<p>Structured state helps to:</p>

<ul>
  <li>Reduce the risk of losing critical constraints in a summary.</li>
  <li>Separate user preferences, product facts, and evidence sources.</li>
  <li>Track task progress and outstanding work.</li>
  <li>Identify results that have expired and need to be queried again.</li>
  <li>Give the main agent and sub-agents a shared state definition.</li>
</ul>

<p>Prices, inventory, and shipping eligibility are dynamic. Even correctly compressed context can contain outdated query results. Information completeness and data freshness must therefore be managed separately.</p>

<h3 id="34-establish-layered-evaluation">3.4 Establish layered evaluation</h3>

<p>Evaluate a compression strategy at three levels:</p>

<ol>
  <li><strong>Constraint-preservation tests:</strong> compare hard constraints, soft preferences, currency, destination, rejected items, and unfinished tasks before and after compression. Missing a critical field is a failure.</li>
  <li><strong>Execution replay:</strong> with the same product snapshot, tool responses, and task conditions, compare tool choices, filtering, and final recommendations before and after compression.</li>
  <li><strong>Online quality monitoring:</strong> track budget violations, shipping errors, factual errors, task completion, latency, and token cost; analyze results by task type.</li>
</ol>

<p>Adaptive compression is also useful: compress repetitive conversation and low-value logs first, preserve hard constraints, key evidence, and execution state, and recover relevant details from the original record when missing information is detected.</p>

<hr />

<h2 id="4-automatic-routing-tool-calls-sub-agents-and-model-selection">4. Automatic Routing: Tool Calls, Sub-Agents, and Model Selection</h2>

<h3 id="41-define-three-types-of-action">4.1 Define three types of action</h3>

<p><strong>Action A: Call a tool directly</strong></p>

<p>Use this when the input is clear, the operation is deterministic, and the output is structured—for example, looking up an SKU price, checking inventory, or calculating a total.</p>

<p><strong>Action B: Delegate to a sub-agent</strong></p>

<p>Use this for multi-step research that can run independently or has a clear specialist boundary—for example, comparing the construction, durability, and value of several tents.</p>

<p><strong>Action C: Switch models</strong></p>

<p>Use this when the current model cannot meet quality requirements for reasoning, tool planning, multilingual understanding, long-context processing, or structured output. Examples include complex budget optimization, conflicting evidence, and decisions across product bundles.</p>

<p>These actions are not mutually exclusive. A complex task can use a stronger model to plan, delegate independent research to sub-agents, and then call tools to verify prices and inventory.</p>

<h3 id="42-choose-a-strategy-based-on-cost-latency-and-risk">4.2 Choose a strategy based on cost, latency, and risk</h3>

<p>A router should consider:</p>

<table>
  <thead>
    <tr>
      <th>Feature</th>
      <th>Question</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Task complexity</td>
      <td>How many reasoning steps are needed? Are there several viable options?</td>
    </tr>
    <tr>
      <td>Decomposability</td>
      <td>Are there independent subtasks?</td>
    </tr>
    <tr>
      <td>Tool determinism</td>
      <td>Is there a directly applicable API or function?</td>
    </tr>
    <tr>
      <td>Failure risk</td>
      <td>Could an error cause a budget breach, shipping mistake, or false promise?</td>
    </tr>
    <tr>
      <td>Current model capability</td>
      <td>Can the current model complete the task reliably?</td>
    </tr>
    <tr>
      <td>Latency budget</td>
      <td>How quickly does the user need a response?</td>
    </tr>
    <tr>
      <td>Cost budget</td>
      <td>What are the token, tool-call, and agent-startup costs?</td>
    </tr>
    <tr>
      <td>Information completeness</td>
      <td>Are the key constraints and required parameters available?</td>
    </tr>
  </tbody>
</table>

<p>Routing can be modeled as a quality-constrained cost optimization problem:</p>

\[a^* = \arg\min_{a \in A}
\left[
C(a) + \lambda L(a) + \mu R(a)
\right]\]

<p>where:</p>

<ul>
  <li>$a$ is a candidate execution strategy;</li>
  <li>$C(a)$ is its expected cost;</li>
  <li>$L(a)$ is its expected latency;</li>
  <li>$R(a)$ is its expected error risk;</li>
  <li>$\lambda$ and $\mu$ are business-defined weights.</li>
</ul>

<p>The system should also enforce a minimum quality threshold; it must not choose an obviously unreliable strategy just to reduce cost. Weights and thresholds should be calibrated through offline evaluation and online experiments, not fixed by intuition alone.</p>

<h3 id="43-example-routing-flow">4.3 Example routing flow</h3>

<pre><code class="language-mermaid">flowchart TD
    A[Receive user task] --&gt; B[Extract constraints and task state]
    B --&gt; C{Is required information complete?}
    C -- No --&gt; D[Ask for clarification or use an explicit default]
    D --&gt; B
    C -- Yes --&gt; E{Is there a deterministic tool operation?}
    E -- Yes --&gt; F[Call the tool directly]
    E -- No --&gt; G{Are there independent complex subtasks?}
    G -- Yes --&gt; H[Build a dependency graph and estimate parallel benefit]
    H --&gt; I{Does parallel benefit exceed its overhead?}
    I -- Yes --&gt; J[Delegate to sub-agents]
    I -- No --&gt; K[Use one agent sequentially]
    G -- No --&gt; K
    F --&gt; L{Can the current model make the remaining decisions reliably?}
    J --&gt; L
    K --&gt; L
    L -- No --&gt; M[Escalate to a stronger or specialized model]
    L -- Yes --&gt; N[Continue execution]
    M --&gt; N
    N --&gt; O[Validate results and hard constraints]
    O --&gt; P{Did validation pass?}
    P -- No --&gt; Q[Retry selectively or recover missing information]
    Q --&gt; O
    P -- Yes --&gt; R[Present the final recommendation]
</code></pre>

<p>The guiding principle is: <strong>perform deterministic, lower-cost operations before spending resources on more expensive reasoning.</strong></p>

<p>For example, first filter a structured product database for reasonable prices and shipping eligibility; then ask a model to analyze durability, use cases, and bundle value. This division is generally easier to verify and control than relying on a large language model to infer products, prices, and shipping eligibility from scratch.</p>

<h3 id="44-when-should-the-system-switch-models">4.4 When should the system switch models?</h3>

<p>Model escalation should be triggered by clear failure signals or capability requirements—not simply because a task is long or appears complex.</p>

<p>Possible triggers include:</p>

<ul>
  <li>Repeated failure to produce output that matches a schema.</li>
  <li>Repeatedly incorrect tool-call parameters.</li>
  <li>Inability to reliably resolve complex constraint conflicts between candidates.</li>
  <li>A requirement for more effective context than the current model can reliably handle.</li>
  <li>Evaluation results showing that the current model performs significantly worse on similar tasks than a stronger model.</li>
</ul>

<p>Distinguish model limitations from infrastructure failures. If a product API times out, switching to a more capable language model will not usually fix the network or service. Consider retries, another data source, or a defined fallback instead.</p>

<p>Choose models based on evaluated task performance, not solely on a model’s own assessment of its abilities.</p>

<h3 id="45-improve-routing-continuously-with-execution-logs">4.5 Improve routing continuously with execution logs</h3>

<p>Start with rule-based routing:</p>

<ul>
  <li>Structured, deterministic tasks: call a tool directly.</li>
  <li>Independent, complex subtasks: evaluate whether agent delegation is worthwhile.</li>
  <li>High uncertainty, complex reasoning, or repeated failures: consider a stronger model.</li>
  <li>Missing critical inputs: ask for clarification or use a documented default.</li>
</ul>

<p>Then collect execution logs, including task type, routing action, actual latency, token and tool costs, success rate, retries, and hard-constraint violations.</p>

<p>Offline replay, A/B tests, or a calibrated routing model can help learn effective strategies for different task types. Continuously calibrate routing against real outcomes; do not rely only on static rules or a model’s self-assessment.</p>

<hr />

<h2 id="5-recommended-production-architecture">5. Recommended Production Architecture</h2>

<p>Consider dividing the system into these modules:</p>

<ol>
  <li><strong>Intent parsing and state management:</strong> extract budget, destination, preferences, hard constraints, and task state.</li>
  <li><strong>Task router:</strong> decide whether to call a tool directly, delegate to sub-agents, or switch models.</li>
  <li><strong>Product retrieval:</strong> retrieve candidates with keyword search, vector search, and reranking.</li>
  <li><strong>Product verification:</strong> validate specifications, inventory, price, shipping eligibility, and information freshness.</li>
  <li><strong>Result aggregation and constraint checks:</strong> reconcile currency, price basis, performance evidence, and shipping terms.</li>
  <li><strong>Recommendation generation and quality monitoring:</strong> explain recommendations with evidence and monitor failure modes.</li>
</ol>

<pre><code class="language-mermaid">flowchart TD
    A[Intent parsing and state management] --&gt; B[Task router]
    B --&gt; C[Product retrieval: keywords, vectors, and reranking]
    B --&gt; D[Product verification: specifications, price, inventory, and shipping]
    C --&gt; E[Result aggregation and constraint checks]
    D --&gt; E
    E --&gt; F[Recommendation generation]
    F --&gt; G[Quality monitoring and feedback]
    G --&gt; B
</code></pre>

<p>Responsibilities should be clear:</p>

<ul>
  <li>The retrieval layer discovers candidate products.</li>
  <li>The orchestration layer assigns work and manages dependencies.</li>
  <li>Context management preserves the state needed to complete the task.</li>
  <li>The verification layer prevents unsupported or stale information from reaching the final answer.</li>
  <li>The monitoring layer evaluates quality, latency, and cost, and informs future routing improvements.</li>
</ul>

<hr />

<h2 id="6-implementation-roadmap-and-conclusion">6. Implementation Roadmap and Conclusion</h2>

<p>Proceed in stages:</p>

<h3 id="stage-1-establish-retrieval-and-constraint-validation">Stage 1: Establish retrieval and constraint validation</h3>

<p>Implement hybrid keyword and vector retrieval, candidate deduplication, relevance reranking, and validation of hard constraints such as price, inventory, and shipping eligibility. Prioritize retrieval quality and factual accuracy.</p>

<h3 id="stage-2-establish-structured-task-state-and-compression-evaluation">Stage 2: Establish structured task state and compression evaluation</h3>

<p>Define what information must be preserved, distinguishing user preferences, product facts, evidence sources, and dynamic state. Use test sets and execution replay to evaluate performance after compression.</p>

<h3 id="stage-3-introduce-conditional-agent-parallelism">Stage 3: Introduce conditional agent parallelism</h3>

<p>Split work using a task dependency graph and prioritize parallel execution for independent subtasks. Use measured latency, failure rates, and coordination costs to determine whether parallelism is beneficial.</p>

<h3 id="stage-4-improve-automatic-routing-and-model-selection">Stage 4: Improve automatic routing and model selection</h3>

<p>Continuously calibrate tool use, sub-agent delegation, and model escalation based on real task completion, latency, cost, and error risk.</p>

<p>The system should not optimize for the number of agents, model size, or compression ratio. A better goal is to <strong>choose the least costly and fastest verifiable path that still meets quality and safety requirements</strong>.</p>

<p>A reliable cross-border shopping assistant must do more than retrieve semantically relevant products. It should support important claims with evidence, use current price and shipping information, and ensure the entire workflow respects the user’s budget and destination constraints.</p>]]></content><author><name>Cerostep</name></author><category term="AI" /><category term="E-Commerce" /><summary type="html"><![CDATA[A practical design for a cross-border AI shopping assistant, covering hybrid retrieval, agent orchestration, context management, and execution routing.]]></summary></entry><entry xml:lang="zh"><title type="html">跨境电商 AI 购物助手：检索、Agent 编排与上下文管理</title><link href="https://www.cerostep.com/2026/10/15/cross-border-ecommerce-ai-shopping-assistant/" rel="alternate" type="text/html" title="跨境电商 AI 购物助手：检索、Agent 编排与上下文管理" /><published>2026-10-15T16:00:00+00:00</published><updated>2026-10-15T16:00:00+00:00</updated><id>https://www.cerostep.com/2026/10/15/cross-border-ecommerce-ai-shopping-assistant</id><content type="html" xml:base="https://www.cerostep.com/2026/10/15/cross-border-ecommerce-ai-shopping-assistant/"><![CDATA[<h2 id="摘要">摘要</h2>

<p>以用户提出的需求为例：</p>

<blockquote>
  <p>推荐露营装备，预算中低，寄到悉尼。</p>
</blockquote>

<p>这不是单一的商品搜索任务，而是一个需要协同完成需求理解、商品检索、候选评估、价格与库存核验、配送资格确认及结果生成的决策流程。</p>

<p>要构建可靠的跨境电商 AI 购物助手，需要解决四个核心问题：</p>

<ol>
  <li>如何结合关键词检索与向量检索，找到符合用户真实意图的商品？</li>
  <li>什么时候应调用工具，什么时候应派发子 Agent，以及并行执行是否值得？</li>
  <li>如何压缩上下文，同时保留完成任务所需的关键约束、证据和执行状态？</li>
  <li>如何根据任务复杂度、质量要求、延迟和成本，自动选择执行策略与模型？</li>
</ol>

<p>本文从系统设计和工程落地的角度逐一说明。</p>

<hr />

<h2 id="一关键词检索与向量检索">一、关键词检索与向量检索</h2>

<h3 id="11-核心区别">1.1 核心区别</h3>

<p><strong>关键词检索（Keyword Search）</strong> 根据查询词与商品文本中的词项匹配程度进行检索。常见实现包括倒排索引和 BM25。它适合品牌、型号、SKU、明确规格及精确属性等场景。</p>

<p><strong>向量检索（Vector Search）</strong> 使用 Embedding 模型将查询与商品文本编码为向量，再依据向量之间的距离或相似度召回候选。它适合处理同义表达、口语描述、隐含需求以及不同措辞表达的相近概念。</p>

<table>
  <thead>
    <tr>
      <th>检索方式</th>
      <th>主要优势</th>
      <th>主要局限</th>
      <th>典型场景</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>关键词检索</td>
      <td>精确、可解释，适合明确词项和结构化字段</td>
      <td>对同义表达和跨语言改写的召回能力有限</td>
      <td>品牌、型号、SKU、规格</td>
    </tr>
    <tr>
      <td>向量检索</td>
      <td>能识别语义接近的表达，支持自然语言查询</td>
      <td>语义相似不等于事实成立，可能召回不相关结果</td>
      <td>口语需求、同义表达、跨语言语义检索</td>
    </tr>
    <tr>
      <td>混合检索</td>
      <td>兼顾词项匹配与语义召回</td>
      <td>需要合并、去重和排序策略</td>
      <td>综合商品发现与推荐</td>
    </tr>
  </tbody>
</table>

<h3 id="12-为什么抗造耐摔可以匹配到没有这些原词的商品">1.2 为什么“抗造耐摔”可以匹配到没有这些原词的商品？</h3>

<p>假设用户查询“抗造耐摔”，商品页面中没有这两个词，但包含以下描述：</p>

<ul>
  <li>“采用抗冲击 ABS 外壳”</li>
  <li>“通过 1.5 米跌落测试”</li>
  <li>“强化结构设计”</li>
  <li>“针对户外使用进行了耐久性优化”</li>
</ul>

<p>向量检索有机会将这些商品召回，因为 Embedding 模型在训练过程中学习了词语、句子和上下文之间的统计语义关系。“耐摔”“抗冲击”和“跌落测试”等表达可能在向量空间中具有较高相似度。</p>

<p>不过，必须区分三个概念：</p>

<ol>
  <li><strong>语义相似不等于属性等价。</strong> “防水”与“适合雨天使用”可能语义接近，但不代表具备相同的防护等级。</li>
  <li><strong>语义相似不等于事实成立。</strong> “军规级设计”不一定代表商品通过了某项具体标准的认证或测试。</li>
  <li><strong>检索召回不等于性能验证。</strong> 向量检索只能帮助发现候选商品，不能单独证明商品确实耐摔。</li>
</ol>

<p>在跨境电商场景中，用户可能用中文描述需求，而商品标题、规格和认证信息采用英文或其他语言。多语言 Embedding 有助于跨语言召回，但仍需要对关键规格和证据进行核验。</p>

<h3 id="13-推荐方案混合检索与重排">1.3 推荐方案：混合检索与重排</h3>

<p>建议采用 <strong>Hybrid Retrieval（混合检索）</strong>，而不是在关键词检索与向量检索之间二选一。</p>

<p>推荐流程：</p>

<ol>
  <li><strong>解析用户需求</strong>：提取商品类别、预算、目的地、硬约束和软偏好。</li>
  <li><strong>并行召回候选</strong>：通过关键词检索与向量检索分别获取候选商品。</li>
  <li><strong>合并与去重</strong>：统一商品 ID、SKU 和变体信息，避免重复候选。</li>
  <li><strong>相关性重排</strong>：使用 BM25 分数、向量相似度、Cross-Encoder 或其他重排模型评估查询与商品的相关性。</li>
  <li><strong>硬约束过滤</strong>：核验价格上限、库存、目的地配送资格等不可违反的条件。</li>
  <li><strong>证据验证</strong>：对耐用性、防水等级、承重等关键属性，优先使用规格表、测试报告或可信商品资料。</li>
  <li><strong>生成推荐</strong>：展示推荐理由、价格、性能依据、配送信息和必要的限制说明。</li>
</ol>

<p>一个重要原则是：<strong>硬约束应先过滤或验证，软偏好主要用于排序。</strong></p>

<p>例如，无法配送到悉尼的商品，即使语义相似度很高，也不应进入最终推荐清单。</p>

<hr />

<h2 id="二子-agent-的派发与并行执行">二、子 Agent 的派发与并行执行</h2>

<h3 id="21-区分工具调用子-agent-与并行执行">2.1 区分工具调用、子 Agent 与并行执行</h3>

<ul>
  <li><strong>工具调用（Tool Calling）</strong>：执行一个明确的操作，例如查询商品 API、检查库存或计算总价。</li>
  <li><strong>子 Agent（Sub-Agent）</strong>：接收一个相对完整的子目标，并使用独立上下文、工具权限或执行策略完成任务。</li>
  <li><strong>并行执行（Parallel Execution）</strong>：同时启动多个任务。并行执行不要求一定采用多 Agent 架构；单个 Agent 也可以并行发起多个工具调用。</li>
</ul>

<p>不应将每一次工具调用都包装成一个 Agent。查询单个商品价格通常只需要调用商品 API；查询多个商品，也不意味着每个商品都需要一个独立 Agent。</p>

<h3 id="22-什么时候值得派发子-agent">2.2 什么时候值得派发子 Agent？</h3>

<p>可以从四个方面评估：</p>

<ol>
  <li><strong>可分解性</strong>：任务能否拆分为相对独立的子任务，例如帐篷、睡眠系统和照明装备的研究。</li>
  <li><strong>依赖程度</strong>：子任务能否在不等待其他任务结果的情况下先行推进。</li>
  <li><strong>专业化收益</strong>：不同子任务是否需要不同工具、检索策略、提示词或验证逻辑。</li>
  <li><strong>成本收益</strong>：并行带来的延迟或质量收益，是否超过启动、协调、汇总和重复推理的开销。</li>
</ol>

<p>以露营装备推荐为例：</p>

<table>
  <thead>
    <tr>
      <th>子任务</th>
      <th>建议执行方式</th>
      <th>原因</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>查询单个帐篷的价格</td>
      <td>直接调用工具</td>
      <td>输入明确、操作确定</td>
    </tr>
    <tr>
      <td>比较多款帐篷的结构与耐用性</td>
      <td>可派发商品研究 Agent</td>
      <td>需要综合分析大量候选</td>
    </tr>
    <tr>
      <td>查询帐篷和睡袋的库存</td>
      <td>并行调用 API</td>
      <td>子任务独立，结果结构化</td>
    </tr>
    <tr>
      <td>计算整套装备总价</td>
      <td>直接计算或调用计算工具</td>
      <td>规则确定，无需独立推理</td>
    </tr>
    <tr>
      <td>核验澳洲配送限制</td>
      <td>调用物流工具，或派发配送核验 Agent</td>
      <td>取决于数据源复杂度与验证需求</td>
    </tr>
    <tr>
      <td>合并推荐清单并消除重复</td>
      <td>由主 Agent 负责</td>
      <td>需要全局一致性与最终决策</td>
    </tr>
  </tbody>
</table>

<p>派发决策应由任务复杂度、依赖关系和执行成本决定，而不是由任务名称决定。</p>

<h3 id="23-为什么两个-agent-并行不一定更快">2.3 为什么两个 Agent 并行不一定更快？</h3>

<p>并行只能减少可并行部分的等待时间，无法消除依赖关系和协调成本。</p>

<p>假设：</p>

<ul>
  <li>Agent A 检索帐篷，耗时 4 秒；</li>
  <li>Agent B 检索睡袋，耗时 5 秒；</li>
  <li>主 Agent 汇总、去重和核验，耗时 2 秒。</li>
</ul>

<p>如果串行执行：</p>

\[T_{\text{serial}} = 4 + 5 + 2 = 11\text{ 秒}\]

<p>如果前两个任务并行执行：</p>

\[T_{\text{parallel}} = \max(4,5) + 2 = 7\text{ 秒}\]

<p>在理想条件下，并行可将总耗时从 11 秒降至 7 秒，约减少 36%。</p>

<p>但如果并行任务增加了 1.5 秒的启动与协调成本，以及 1 秒的数据冲突处理成本，则：</p>

\[T_{\text{parallel}} = 5 + 1.5 + 2 + 1 = 9.5\text{ 秒}\]

<p>并行收益就会显著下降。以上数字仅用于说明计算方式，不代表实际系统基准。</p>

<p>常见的并行瓶颈包括：</p>

<ul>
  <li><strong>共享资源竞争</strong>：多个 Agent 同时访问同一个受限 API，导致限流或排队。</li>
  <li><strong>依赖阻塞</strong>：配送核验需要 SKU，但 SKU 尚未确定。</li>
  <li><strong>重复工作</strong>：多个 Agent 检索到相同商品，重复执行工具调用。</li>
  <li><strong>协调成本</strong>：主 Agent 需要统一价格、币种、配送条件和商品标识。</li>
  <li><strong>尾部延迟</strong>：最终响应必须等待所有必要任务中的最慢者。</li>
  <li><strong>结果冲突</strong>：不同 Agent 可能给出不一致的结论，需要额外验证。</li>
</ul>

<p>因此，并行度越高，并不意味着吞吐量必然越高。共享资源、限流和协调开销可能抵消并行收益。</p>

<h3 id="24-使用任务依赖图设计执行计划">2.4 使用任务依赖图设计执行计划</h3>

<p>建议先解析需求，再根据依赖关系制定执行计划。例如：</p>

<pre><code class="language-mermaid">flowchart TD
    A[解析用户需求] --&gt; B[确定预算和配送约束]
    B --&gt; C[检索候选商品]
    C --&gt; D[按类别拆分候选]
    D --&gt; E[帐篷研究]
    D --&gt; F[睡眠装备研究]
    D --&gt; G[照明与炊具研究]
    E --&gt; H[合并候选]
    F --&gt; H
    G --&gt; H
    H --&gt; I[统一价格与性能核验]
    I --&gt; J[核验悉尼配送和总成本]
    J --&gt; K[预算优化与最终推荐]
</code></pre>

<p>独立的商品类别研究适合并行；预算优化和最终配送核验则需要使用汇总后的信息，不能无条件提前完成。</p>

<hr />

<h2 id="三上下文压缩与任务信息保留">三、上下文压缩与任务信息保留</h2>

<h3 id="31-压缩的目标是降低成本而不是单纯缩短文本">3.1 压缩的目标是降低成本，而不是单纯缩短文本</h3>

<p>上下文压缩应在减少 Token 使用量的同时，尽可能保持任务完成率、事实准确性和约束遵循能力。</p>

<p>对于购物助手，需要特别保留以下信息：</p>

<table>
  <thead>
    <tr>
      <th>信息类型</th>
      <th>示例</th>
      <th>建议处理方式</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>硬约束</td>
      <td>目的地为悉尼、明确预算上限、必须有货</td>
      <td>必须保留，不可随意改写</td>
    </tr>
    <tr>
      <td>软偏好</td>
      <td>中低预算、耐用、轻便</td>
      <td>保留语义和优先级</td>
    </tr>
    <tr>
      <td>执行状态</td>
      <td>已查询的 SKU、核验结果、未完成任务</td>
      <td>保留结果、证据来源和有效性</td>
    </tr>
    <tr>
      <td>动态信息</td>
      <td>价格、库存、配送时效</td>
      <td>保留时间戳或有效期，必要时重新查询</td>
    </tr>
    <tr>
      <td>证据与不确定性</td>
      <td>商家宣称、独立测试、尚未验证的属性</td>
      <td>区分证据类型，不得提升确定性</td>
    </tr>
  </tbody>
</table>

<p>如果用户给出了明确预算上限，应保留具体金额和币种，而不是仅保留“预算有限”。如果用户只说“中低预算”，则不应擅自将其压缩成未经确认的精确价格上限；系统可以使用透明的默认假设，或在必要时询问用户。</p>

<p>同样，压缩不能把“商家宣称耐冲击”改写成“已通过耐冲击测试”，也不能把“价格为澳元”简化成不含币种的价格字段。</p>

<h3 id="32-通过任务表现评估压缩质量">3.2 通过任务表现评估压缩质量</h3>

<p>摘要与原始对话在语义上相似，并不代表保留了所有执行所需的信息。更有效的方式是将压缩后的上下文交给执行系统，测试其能否正确完成原任务。</p>

<p>一个基础指标是任务完成率：</p>

\[Q_{\text{compression}} =
\frac{\text{压缩后仍能正确完成的测试任务数}}
{\text{全部测试任务数}}\]

<p>实际评估还应单独跟踪硬约束违规率、事实错误率、工具调用正确率和最终推荐质量。</p>

<p>建议构造以下测试场景：</p>

<ul>
  <li>用户指定最高预算后，系统是否仍能过滤超预算商品？</li>
  <li>用户指定悉尼为目的地后，系统是否仍会核验目的地配送？</li>
  <li>用户要求耐摔时，系统是否区分商家宣传和测试证据？</li>
  <li>用户已拒绝某商品后，系统是否避免再次推荐？</li>
  <li>商品价格发生变化后，系统是否重新查询，而非继续使用过期数据？</li>
</ul>

<p>硬约束违规应独立统计，不应被其他正确结果抵消。</p>

<p>例如，可以定义：</p>

\[R_{\text{violation}} =
\frac{\text{违反至少一项硬约束的任务数}}
{\text{全部任务数}}\]

<p>如果压缩后 Token 成本降低了 40%，但配送误判率明显上升，那么该压缩策略不能被视为成功。这里的 40% 仅为示例，不是通用阈值。</p>

<h3 id="33-采用结构化状态与按需摘要">3.3 采用结构化状态与按需摘要</h3>

<p>不建议将所有任务状态压缩为单段自然语言。更稳健的方式是将关键状态结构化保存，将重复对话和低价值日志按需摘要。</p>

<p>例如：</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"intent"</span><span class="p">:</span><span class="w"> </span><span class="s2">"camping_gear_recommendation"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"destination"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"city"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Sydney"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"country"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Australia"</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"budget"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"level"</span><span class="p">:</span><span class="w"> </span><span class="s2">"low_to_mid"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"currency"</span><span class="p">:</span><span class="w"> </span><span class="s2">"AUD"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"exact_cap"</span><span class="p">:</span><span class="w"> </span><span class="kc">null</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"preferences"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
    </span><span class="s2">"durable"</span><span class="p">,</span><span class="w">
    </span><span class="s2">"value_for_money"</span><span class="w">
  </span><span class="p">],</span><span class="w">
  </span><span class="nl">"constraints"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"shipping_to_destination_required"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"evidence"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"product_specs"</span><span class="p">:</span><span class="w"> </span><span class="p">[],</span><span class="w">
    </span><span class="nl">"shipping_checks"</span><span class="p">:</span><span class="w"> </span><span class="p">[],</span><span class="w">
    </span><span class="nl">"price_checks"</span><span class="p">:</span><span class="w"> </span><span class="p">[]</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"pending_tasks"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
    </span><span class="s2">"retrieve_products"</span><span class="p">,</span><span class="w">
    </span><span class="s2">"verify_shipping"</span><span class="p">,</span><span class="w">
    </span><span class="s2">"compare_total_cost"</span><span class="w">
  </span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>该结构仅为示例，实际字段应根据业务需求定义。</p>

<p>结构化状态有助于：</p>

<ul>
  <li>降低关键约束被摘要遗漏的风险；</li>
  <li>分离用户偏好、商品事实与证据来源；</li>
  <li>追踪任务进度和未完成事项；</li>
  <li>判断哪些结果已过期，需要重新查询；</li>
  <li>让主 Agent 与子 Agent 共享统一的状态定义。</li>
</ul>

<p>需要注意，价格、库存和配送资格都属于动态信息。即使上下文压缩正确，历史查询结果也可能失效。因此，信息完整性与数据时效性必须分别管理。</p>

<h3 id="34-建立分层评估机制">3.4 建立分层评估机制</h3>

<p>建议从三个层面评估压缩策略：</p>

<ol>
  <li><strong>约束保留测试</strong>：对比压缩前后的硬约束、软偏好、币种、目的地、拒绝项和未完成任务。关键字段缺失时，应判定失败。</li>
  <li><strong>执行回放测试</strong>：在相同商品快照、工具响应和任务条件下，对比压缩前后的工具选择、过滤结果和最终推荐。</li>
  <li><strong>线上质量监控</strong>：持续跟踪预算违规率、配送误判率、事实错误率、任务完成率、延迟和 Token 成本，并按任务类型分析。</li>
</ol>

<p>还可以采用自适应压缩：优先压缩重复对话和低价值日志，保留硬约束、关键证据及执行状态；当检测到信息缺失时，从原始记录中恢复相关内容。</p>

<hr />

<h2 id="四自动路由工具调用子-agent-与模型选择">四、自动路由：工具调用、子 Agent 与模型选择</h2>

<h3 id="41-定义三类执行动作">4.1 定义三类执行动作</h3>

<p><strong>动作 A：直接调用工具</strong></p>

<p>适用于输入明确、操作确定、输出结构化的任务。例如查询 SKU 售价、检查库存、计算总价。</p>

<p><strong>动作 B：派发子 Agent</strong></p>

<p>适用于需要多步骤研究、可以独立执行或具有明确专业边界的子任务。例如比较多款帐篷的结构、耐用性和性价比。</p>

<p><strong>动作 C：更换模型</strong></p>

<p>适用于当前模型在推理、工具规划、多语言理解、长上下文处理或结构化输出方面无法满足质量要求的任务。例如复杂预算优化、冲突证据分析和跨商品组合决策。</p>

<p>三类动作并非互斥。复杂任务可以先由能力更强的模型制定计划，再派发子 Agent 并行研究，最后调用工具核验价格和库存。</p>

<h3 id="42-根据成本延迟和风险选择策略">4.2 根据成本、延迟和风险选择策略</h3>

<p>路由器应考虑以下特征：</p>

<table>
  <thead>
    <tr>
      <th>特征</th>
      <th>评估问题</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>任务复杂度</td>
      <td>需要多少步推理？是否存在多个可行方案？</td>
    </tr>
    <tr>
      <td>可分解性</td>
      <td>是否存在相互独立的子任务？</td>
    </tr>
    <tr>
      <td>工具确定性</td>
      <td>是否有直接对应的 API 或函数？</td>
    </tr>
    <tr>
      <td>失败风险</td>
      <td>错误是否会导致超预算、配送误判或错误承诺？</td>
    </tr>
    <tr>
      <td>当前模型能力</td>
      <td>当前模型能否可靠完成任务？</td>
    </tr>
    <tr>
      <td>延迟预算</td>
      <td>用户对响应时间的要求是什么？</td>
    </tr>
    <tr>
      <td>成本预算</td>
      <td>Token、工具调用和 Agent 启动成本是多少？</td>
    </tr>
    <tr>
      <td>信息完整度</td>
      <td>关键约束和必要参数是否齐全？</td>
    </tr>
  </tbody>
</table>

<p>可将路由建模为受质量约束的成本优化问题：</p>

\[a^* = \arg\min_{a \in A}
\left[
C(a) + \lambda L(a) + \mu R(a)
\right]\]

<p>其中：</p>

<ul>
  <li>$a$ 表示候选执行策略；</li>
  <li>$C(a)$ 表示预计执行成本；</li>
  <li>$L(a)$ 表示预计延迟；</li>
  <li>$R(a)$ 表示预计错误风险；</li>
  <li>$\lambda$ 与 $\mu$ 是业务设定的权重。</li>
</ul>

<p>实际系统还应设置最低质量门槛，不能为了降低成本而采用明显不可靠的策略。权重和阈值需要通过离线评估与线上实验校准，而不应凭经验直接固定。</p>

<h3 id="43-参考路由流程">4.3 参考路由流程</h3>

<pre><code class="language-mermaid">flowchart TD
    A[接收用户任务] --&gt; B[提取约束与任务状态]
    B --&gt; C{关键信息是否完整？}
    C -- 否 --&gt; D[澄清或采用明确的默认值]
    D --&gt; B
    C -- 是 --&gt; E{是否存在确定性工具操作？}
    E -- 是 --&gt; F[直接调用工具]
    E -- 否 --&gt; G{是否存在独立的复杂子任务？}
    G -- 是 --&gt; H[生成依赖图并评估并行收益]
    H --&gt; I{并行收益是否大于开销？}
    I -- 是 --&gt; J[派发子 Agent]
    I -- 否 --&gt; K[单 Agent 顺序执行]
    G -- 否 --&gt; K
    F --&gt; L{当前模型能否可靠完成后续决策？}
    J --&gt; L
    K --&gt; L
    L -- 否 --&gt; M[升级模型或采用专门模型]
    L -- 是 --&gt; N[继续执行]
    M --&gt; N
    N --&gt; O[验证结果与硬约束]
    O --&gt; P{是否通过验证？}
    P -- 否 --&gt; Q[定向重试或恢复缺失信息]
    Q --&gt; O
    P -- 是 --&gt; R[输出最终推荐]
</code></pre>

<p>流程的基本原则是：<strong>优先执行确定性强、成本较低的操作，再投入更昂贵的推理资源。</strong></p>

<p>例如，可以先从结构化商品数据库中筛选价格合理且符合配送条件的候选，再让模型分析耐用性、用途和组合价值。与完全依赖大模型从零推断商品、价格和配送资格相比，这种分工通常更容易验证，也更便于控制成本。</p>

<h3 id="44-什么时候应该更换模型">4.4 什么时候应该更换模型？</h3>

<p>模型升级应由明确的失败信号或能力需求触发，而不是单纯因为任务较长或看起来复杂。</p>

<p>可能的触发条件包括：</p>

<ul>
  <li>多次无法生成符合 Schema 的输出；</li>
  <li>工具调用参数反复错误；</li>
  <li>当前模型无法稳定解决多个候选方案之间的复杂约束冲突；</li>
  <li>任务需要的有效上下文超出当前模型的可靠处理能力；</li>
  <li>经评估的同类任务数据显示，当前模型成功率明显低于更强的模型。</li>
</ul>

<p>同时，要区分模型能力问题与基础设施问题。如果商品 API 超时，换成更强的语言模型通常不能解决网络或服务端故障。此时应优先考虑重试、切换数据源或采用降级策略。</p>

<p>模型选择应以经过评估的任务表现为依据，而不是仅依赖模型对自身能力的判断。</p>

<h3 id="45-通过执行日志持续优化路由">4.5 通过执行日志持续优化路由</h3>

<p>初期可以采用规则路由：</p>

<ul>
  <li>结构化、确定性任务：直接调用工具；</li>
  <li>独立且复杂的子任务：评估是否派发 Agent；</li>
  <li>高不确定性、复杂推理或持续失败：考虑升级模型；</li>
  <li>关键输入缺失：请求澄清或采用经过定义的默认值。</li>
</ul>

<p>随后积累执行日志，记录任务类型、路由动作、实际延迟、Token 与工具成本、成功率、重试次数及硬约束违规情况。</p>

<p>可以通过离线回放、A/B 测试或经校准的路由模型，学习不同任务类型下的有效策略。路由策略必须使用实际执行结果持续校准，不能只依赖静态规则或模型自我评估。</p>

<hr />

<h2 id="五推荐的生产架构">五、推荐的生产架构</h2>

<p>建议将系统划分为以下模块：</p>

<ol>
  <li><strong>意图解析与状态管理</strong>：提取预算、目的地、偏好、硬约束和任务状态。</li>
  <li><strong>任务路由器</strong>：决定直接调用工具、派发子 Agent 或升级模型。</li>
  <li><strong>商品检索层</strong>：结合关键词检索、向量检索与重排，召回候选商品。</li>
  <li><strong>商品核验层</strong>：验证规格、库存、价格、配送资格和信息时效。</li>
  <li><strong>结果合并与约束校验层</strong>：统一币种、价格口径、性能证据和配送条件。</li>
  <li><strong>推荐生成与质量监控层</strong>：解释推荐理由，标明依据，并持续监控失败模式。</li>
</ol>

<pre><code class="language-mermaid">flowchart TD
    A[意图解析与状态管理] --&gt; B[任务路由器]
    B --&gt; C[商品检索：关键词、向量与重排]
    B --&gt; D[商品核验：规格、价格、库存与配送]
    C --&gt; E[结果合并与约束校验]
    D --&gt; E
    E --&gt; F[推荐生成]
    F --&gt; G[质量监控与反馈]
    G --&gt; B
</code></pre>

<p>该架构中，各模块职责应明确：</p>

<ul>
  <li>检索层负责发现候选商品；</li>
  <li>编排层负责分配任务与控制依赖；</li>
  <li>上下文管理负责保留必要状态；</li>
  <li>核验层负责阻止未经证实或已过期的信息进入最终答案；</li>
  <li>监控层负责评估质量、延迟和成本，并为后续路由优化提供数据。</li>
</ul>

<hr />

<h2 id="六实施建议与结论">六、实施建议与结论</h2>

<p>建议按以下顺序推进：</p>

<h3 id="第一阶段建立检索与约束校验基础">第一阶段：建立检索与约束校验基础</h3>

<p>实现关键词与向量混合检索、候选去重、相关性重排，以及价格、库存和配送资格等硬约束校验。优先保证商品召回质量和事实准确性。</p>

<h3 id="第二阶段建立结构化任务状态与压缩评估">第二阶段：建立结构化任务状态与压缩评估</h3>

<p>明确哪些信息必须保留，区分用户偏好、商品事实、证据来源和动态状态。通过测试集与执行回放验证压缩后任务表现。</p>

<h3 id="第三阶段引入有条件的-agent-并行">第三阶段：引入有条件的 Agent 并行</h3>

<p>根据任务依赖图拆分工作，优先并行执行相互独立的子任务。通过实测延迟、失败率和协调成本判断并行是否真正有收益。</p>

<h3 id="第四阶段优化自动路由与模型选择">第四阶段：优化自动路由与模型选择</h3>

<p>基于真实任务完成率、延迟、成本和错误风险，持续校准工具调用、子 Agent 派发与模型升级策略。</p>

<p>最终，系统设计不应以 Agent 数量、模型规模或压缩比例作为主要目标。更合理的目标是：<strong>在满足质量和安全要求的前提下，选择成本更低、执行更快且结果可验证的任务完成路径。</strong></p>

<p>对于跨境电商 AI 购物助手，可靠的推荐不仅要找到语义相关的商品，还要证明关键属性有据可依、价格与配送信息有效，并确保整个执行流程遵守用户的预算和目的地约束。</p>]]></content><author><name>Cerostep</name></author><category term="AI" /><category term="跨境电商" /><summary type="html"><![CDATA[从混合检索、Agent 编排、上下文管理与自动路由出发，设计可验证、可落地的跨境电商 AI 购物助手。]]></summary></entry></feed>