Commit 6dbcb70e4d5c4631513bd20de928cef6a4a0fd1f

Authored by tangwang
1 parent b4f7574f

docs(agent): add real recommendation tool examples

修改缘由:
现有工具文档仅列出能力名称,缺少逐工具参数、调用方式、响应语义和可感知结果;同时 Redis key/value 描述已与实际离线产出发生漂移,使用者无法据此可靠接入或判断召回效果。

修改内容:
- 补全 recommendation_capabilities、resolve_recommendation_dimension、recall_similar_products、recall_products_by_dimensions 和 build_recommendation_candidates 的适用场景、参数约束、CLI/Python 调用及响应字段。
- 使用 2026-08-22 离线产出快照和真实 SKU 3891002,展示相似召回、维度召回、混合召回的排名、分数和证据,并明确未访问线上 Redis、商品实时价格、库存及可售状态的验证边界。
- 增加从意图解析、维度映射、双路召回、商品详情补全、实时过滤到 LLM 重排的完整 Agent 编排示例,并记录负面样例和上线评估建议。
- 修复混合召回的维度通道可能重新返回种子商品的问题;种子排除作为内部附加集合处理,不占用公开 exclude_item_ids 的 500 项上限。
- 新增边界测试,覆盖 500 个公开排除项与种子自动排除同时生效的场景。

验证:
- cd offline_tasks && python3 test_agent_recommendation_tools.py:19 项测试通过。
- Python 3.6 语法编译通过。
- 文档中的 13 个 JSON 示例均可解析,5 个 Python 示例均可编译,35 组 Markdown 代码围栏完整。
- 本地链接、真实快照 Top 5/分数/种子排除断言以及 git diff --check 均通过。
offline_tasks/agent_tools/service.py
... ... @@ -433,6 +433,19 @@ class RecommendationAgentTools(object):
433 433 list_types=None, top_k=50,
434 434 per_source_k=100,
435 435 exclude_item_ids=None):
  436 + return self._recall_products_by_dimensions(
  437 + context=context,
  438 + interests=interests,
  439 + list_types=list_types,
  440 + top_k=top_k,
  441 + per_source_k=per_source_k,
  442 + exclude_item_ids=exclude_item_ids,
  443 + )
  444 +
  445 + def _recall_products_by_dimensions(
  446 + self, context=None, interests=None, list_types=None, top_k=50,
  447 + per_source_k=100, exclude_item_ids=None,
  448 + additional_exclude_item_ids=None):
436 449 top_k = _bounded_integer(top_k, 'top_k', 50, 1, 100)
437 450 per_source_k = _bounded_integer(
438 451 per_source_k, 'per_source_k', 100, 1, 500
... ... @@ -440,6 +453,11 @@ class RecommendationAgentTools(object):
440 453 selected_list_types = self._normalize_list_types(list_types)
441 454 plans = self._plan_dimensions(context, interests)
442 455 excluded = set(_unique_strings(exclude_item_ids, 'exclude_item_ids'))
  456 + excluded.update(_unique_strings(
  457 + additional_exclude_item_ids,
  458 + 'additional_exclude_item_ids',
  459 + maximum=20,
  460 + ))
443 461  
444 462 source_plans = []
445 463 for plan in plans:
... ... @@ -532,6 +550,11 @@ class RecommendationAgentTools(object):
532 550 if collaborative_weight + dimension_weight <= 0:
533 551 raise ToolInputError('At least one channel weight must be positive')
534 552  
  553 + seed_item_ids = []
  554 + if seed_items:
  555 + normalized_seeds = self._normalize_seed_items(seed_items)
  556 + seed_item_ids = [seed['item_id'] for seed in normalized_seeds]
  557 +
535 558 pool_size = min(100, max(top_k * 4, 50))
536 559 channel_results = {}
537 560 if seed_items and collaborative_weight > 0:
... ... @@ -543,13 +566,14 @@ class RecommendationAgentTools(object):
543 566 exclude_item_ids=exclude_item_ids,
544 567 )
545 568 if (context or interests) and dimension_weight > 0:
546   - channel_results['dimension'] = self.recall_products_by_dimensions(
  569 + channel_results['dimension'] = self._recall_products_by_dimensions(
547 570 context=context,
548 571 interests=interests,
549 572 list_types=list_types,
550 573 top_k=pool_size,
551 574 per_source_k=per_source_k,
552 575 exclude_item_ids=exclude_item_ids,
  576 + additional_exclude_item_ids=seed_item_ids,
553 577 )
554 578 if not channel_results:
555 579 raise ToolInputError(
... ...
offline_tasks/doc/智能导购Agent工具集.md
... ... @@ -41,7 +41,7 @@
41 41  
42 42 ```json
43 43 {
44   - "item_id": "3385246",
  44 + "item_id": "3891002",
45 45 "behavior": "purchase",
46 46 "reason": "用户过去采购过同类商品"
47 47 }
... ... @@ -56,9 +56,9 @@
56 56 ```json
57 57 {
58 58 "dimension": "category_level2",
59   - "value": "29",
  59 + "value": "5",
60 60 "weight": 2.0,
61   - "reason": "画像显示用户持续采购玩具车辆"
  61 + "reason": "画像显示用户持续采购交通工具玩具"
62 62 }
63 63 ```
64 64  
... ... @@ -77,9 +77,621 @@
77 77  
78 78 工具会自动规划 `platform_category2`、`client_category2`、平台国家客户类型等组合 key,同时查询更宽泛的单维度。具体可用 key 见 [在线召回Redis Key清单.md](./在线召回Redis%20Key清单.md)。
79 79  
80   -## 3. 排名与解释
  80 +### 2.3 调用入口
81 81  
82   -### 3.1 路内融合
  82 +所有工具都可以通过同一个服务对象调用:
  83 +
  84 +```python
  85 +result = tools.call_tool(tool_name, arguments)
  86 +```
  87 +
  88 +也可以通过 CLI 调试:
  89 +
  90 +```bash
  91 +cd offline_tasks
  92 +python3 scripts/agent_recommendation_tools.py call \
  93 + <tool_name> \
  94 + --arguments '<JSON object>'
  95 +```
  96 +
  97 +CLI 默认读取环境变量连接 Redis。`recommendation_capabilities` 不读取索引;`resolve_recommendation_dimension` 只读取本地维度字典;三个召回工具会访问 Redis。
  98 +
  99 +所有调用都返回 JSON object,不抛出供 Agent 直接处理的业务异常:
  100 +
  101 +| 字段 | 含义 |
  102 +| --- | --- |
  103 +| `ok` | 调用是否成功 |
  104 +| `items` | 按融合分降序排列的候选;仅召回工具返回 |
  105 +| `score` | 当前调用内归一化到 0-1 的融合分,不是概率 |
  106 +| `channels` | 候选来自 `collaborative`、`dimension` 或两者 |
  107 +| `source_count` | 贡献该候选的独立 Redis key 数 |
  108 +| `reasons` | 面向 Agent 的聚合理由 |
  109 +| `evidence` | 实际 key、路内排名、原始分及 RRF 贡献 |
  110 +| `diagnostics` | 计划、命中、缺失、格式异常、排除和候选数 |
  111 +| `error` | 失败时的 `code`、`message` 和 `retryable` |
  112 +
  113 +工具刻意只返回 SKU ID,不返回商品名称、价格和库存。调用方应批量补全商品详情;本文真实示例中的名称仅用于帮助阅读,不属于工具响应。
  114 +
  115 +## 3. 五个工具的完整用法
  116 +
  117 +### 3.1 真实示例的数据口径
  118 +
  119 +以下示例不是虚构数据,取自本机 2026-08-22 的实际离线产出:
  120 +
  121 +```text
  122 +output/i2i_swing_20260822.txt
  123 +output/i2i_session_w2v_20260822.txt
  124 +output/i2i_deepwalk_20260822.txt
  125 +output/interest_aggregation_hot_20260822.txt
  126 +output/item_attributes_mappings.json
  127 +```
  128 +
  129 +为避免把文档验证误写成生产联调,本次示例把上述文件中对应行原样装入 `MemoryIndexStore`,再调用同一个 `RecommendationAgentTools`。对于相同的 key/value 快照,`RedisIndexStore` 的工具结果一致。本次没有读取线上 Redis,也没有验证示例商品当前价格、库存和可售状态。
  130 +
  131 +下文表格中的名称来自同日 `item_attributes_mappings.json`。为便于横向比较,省略了部分颜色、材质和包装尾缀;SKU、排名、分数及证据均保留真实工具结果。
  132 +
  133 +示例场景:
  134 +
  135 +| 数据 | 真实值 |
  136 +| --- | --- |
  137 +| 种子 SKU | `3891002` |
  138 +| 种子名称 | 12PCS 1:36 回力 3开门 大众甲壳虫 |
  139 +| 自然语言兴趣 | 交通工具 |
  140 +| 解析后的二级分类 | `category_level2:5` |
  141 +| 请求上下文 | `platform=essaone`、`client_platform=pc` |
  142 +| 兴趣列表 | `hot` |
  143 +
  144 +### 3.2 `recommendation_capabilities`
  145 +
  146 +用途:在 Agent 初始化、工具版本变化或调用方不确定索引能力时,发现算法、维度、key 模式和融合语义。它不查询 Redis,不应在每轮对话重复调用。
  147 +
  148 +参数:无。
  149 +
  150 +调用:
  151 +
  152 +```bash
  153 +python3 scripts/agent_recommendation_tools.py call \
  154 + recommendation_capabilities \
  155 + --arguments '{}'
  156 +```
  157 +
  158 +响应节选:
  159 +
  160 +```json
  161 +{
  162 + "ok": true,
  163 + "version": "1.0.0",
  164 + "catalog_available": true,
  165 + "algorithms": [
  166 + {
  167 + "name": "swing",
  168 + "primary_key_pattern": "item:similar:swing:{item_id}",
  169 + "fallback_key_patterns": [],
  170 + "signal": "time-aware co-interaction similarity"
  171 + },
  172 + {
  173 + "name": "session_w2v",
  174 + "primary_key_pattern": "item:similar:session_w2v:{item_id}",
  175 + "fallback_key_patterns": ["item:similar:w2v:{item_id}"],
  176 + "signal": "session sequence similarity"
  177 + }
  178 + ],
  179 + "list_types": [
  180 + {"name": "hot", "key_pattern": "interest:hot:{dimension_key}"},
  181 + {"name": "cart", "key_pattern": "interest:cart:{dimension_key}"},
  182 + {"name": "new", "key_pattern": "interest:new:{dimension_key}"},
  183 + {"name": "global", "key_pattern": "interest:global:{dimension_key}"}
  184 + ],
  185 + "ranking": {
  186 + "recall_fusion": "weighted_reciprocal_rank_fusion",
  187 + "score_range": [0, 1]
  188 + }
  189 +}
  190 +```
  191 +
  192 +使用者应据此:
  193 +
  194 +1. 只传 `algorithms` 中声明的算法名;
  195 +2. 使用 `session_w2v` 作为当前名称,不主动拼历史 `w2v` key;
  196 +3. 在 `catalog_available=false` 时跳过名称解析,改用商品目录提供的内部 ID;
  197 +4. 把 `version` 和实际工具参数记录到调用日志。
  198 +
  199 +### 3.3 `resolve_recommendation_dimension`
  200 +
  201 +用途:把“交通工具”“桌面游戏”或供应商名称转换成离线兴趣索引使用的内部值。它只做字典匹配,不查询商品、不召回候选,也不会猜测不存在的 ID。
  202 +
  203 +参数:
  204 +
  205 +| 参数 | 必填 | 范围/默认值 | 含义 |
  206 +| --- | --- | --- | --- |
  207 +| `dimension` | 是 | 支持的维度枚举 | 要解析的目标维度 |
  208 +| `query` | 是 | 1-200 字符 | ID、完整名称或名称片段 |
  209 +| `limit` | 否 | 1-20,默认 10 | 最多返回多少个候选 |
  210 +
  211 +支持的 `dimension`:
  212 +
  213 +```text
  214 +platform, client_platform, country_code, customer_type, supplier,
  215 +category_level1, category_level2, category_level3, category_level4
  216 +```
  217 +
  218 +默认生成的字典包含分类、供应商、平台和客户端。`country_code`、`customer_type` 如果未扩充到字典,会返回空匹配;此时应从客户画像或权威字典取得内部值。
  219 +
  220 +真实调用:
  221 +
  222 +```bash
  223 +python3 scripts/agent_recommendation_tools.py call \
  224 + resolve_recommendation_dimension \
  225 + --arguments '{
  226 + "dimension": "category_level2",
  227 + "query": "交通工具",
  228 + "limit": 3
  229 + }'
  230 +```
  231 +
  232 +真实响应:
  233 +
  234 +```json
  235 +{
  236 + "ok": true,
  237 + "dimension": "category_level2",
  238 + "query": "交通工具",
  239 + "catalog_available": true,
  240 + "matches": [
  241 + {
  242 + "value": "5",
  243 + "label": "交通工具",
  244 + "match_type": "exact_label",
  245 + "score": 0.99
  246 + }
  247 + ],
  248 + "guidance": null
  249 +}
  250 +```
  251 +
  252 +效果解读:调用方后续应传 `{"dimension":"category_level2","value":"5"}`,不能把“交通工具”直接拼成 Redis key。`matches[].score` 是字典匹配置信度,不是商品推荐分。
  253 +
  254 +常见 `match_type` 从强到弱为:
  255 +
  256 +| 类型 | 含义 |
  257 +| --- | --- |
  258 +| `exact_value` | query 就是内部值 |
  259 +| `exact_label` | query 与名称完全一致 |
  260 +| `label_prefix` | 名称以前缀命中 |
  261 +| `label_contains` | 名称包含 query |
  262 +| `all_tokens` | query 的所有空格分词都出现在名称中 |
  263 +
  264 +### 3.4 `recall_similar_products`
  265 +
  266 +用途:当画像或当前会话里已有明确 SKU 时,从多种 I2I 索引召回相似商品。适用于“看了又看”“买过该商品的人还关注什么”和相似商品扩展;没有可信种子时不要调用。
  267 +
  268 +参数:
  269 +
  270 +| 参数 | 必填 | 范围/默认值 | 含义 |
  271 +| --- | --- | --- | --- |
  272 +| `seed_items` | 是 | 1-20 个 | 种子商品及行为、权重、理由 |
  273 +| `algorithms` | 否 | 默认全部 7 路 | 限定使用的 I2I 算法 |
  274 +| `top_k` | 否 | 1-100,默认 50 | 最终候选数 |
  275 +| `per_seed_k` | 否 | 1-200,默认 50 | 每个种子、每种算法最多取多少项 |
  276 +| `exclude_item_ids` | 否 | 最多 500 个 | 已曝光、已购买、不可售等排除项 |
  277 +
  278 +`seed_items` 字段:
  279 +
  280 +| 字段 | 必填 | 含义 |
  281 +| --- | --- | --- |
  282 +| `item_id` | 是 | SKU ID,建议传字符串 |
  283 +| `behavior` | 否 | 默认 `click`;决定默认种子权重 |
  284 +| `weight` | 否 | `0 < weight <= 10`;提供后覆盖行为默认权重 |
  285 +| `reason` | 否 | 选择该种子的画像依据,进入返回证据 |
  286 +
  287 +行为默认权重:
  288 +
  289 +| behavior | 权重 |
  290 +| --- | ---: |
  291 +| `click` / `view` | 1 |
  292 +| `addToPool` | 2 |
  293 +| `addToCart` | 3 |
  294 +| `contactFactory` | 5 |
  295 +| `purchase` | 10 |
  296 +
  297 +真实调用:
  298 +
  299 +```bash
  300 +python3 scripts/agent_recommendation_tools.py call \
  301 + recall_similar_products \
  302 + --arguments '{
  303 + "seed_items": [{
  304 + "item_id": "3891002",
  305 + "behavior": "purchase",
  306 + "reason": "用户过去采购过回力合金车"
  307 + }],
  308 + "algorithms": ["swing", "session_w2v", "deepwalk"],
  309 + "top_k": 5,
  310 + "per_seed_k": 20
  311 + }'
  312 +```
  313 +
  314 +真实响应首项:
  315 +
  316 +```json
  317 +{
  318 + "ok": true,
  319 + "items": [
  320 + {
  321 + "item_id": "3890995",
  322 + "score": 1.0,
  323 + "channels": ["collaborative"],
  324 + "source_count": 2,
  325 + "reasons": [{
  326 + "type": "similar_to_seed",
  327 + "seed_item_id": "3891002",
  328 + "algorithms": ["swing", "deepwalk"],
  329 + "profile_reason": "用户过去采购过回力合金车"
  330 + }],
  331 + "evidence": [
  332 + {
  333 + "source": "swing",
  334 + "key": "item:similar:swing:3891002",
  335 + "rank": 7,
  336 + "raw_score": 0.1538,
  337 + "contribution": 0.14179104
  338 + },
  339 + {
  340 + "source": "deepwalk",
  341 + "key": "item:similar:deepwalk:3891002",
  342 + "rank": 8,
  343 + "raw_score": 0.9768,
  344 + "contribution": 0.125
  345 + }
  346 + ]
  347 + }
  348 + ],
  349 + "diagnostics": {
  350 + "planned_source_count": 3,
  351 + "queried_key_count": 4,
  352 + "hit_source_count": 3,
  353 + "candidate_count_before_limit": 50
  354 + }
  355 +}
  356 +```
  357 +
  358 +`queried_key_count=4` 是因为 `session_w2v` 同时批量查询当前 key 和历史 `w2v` 后备 key,但只会选择第一个可解析的值作为该 source。
  359 +
  360 +Top 5 结果补全名称后:
  361 +
  362 +| 排名 | SKU | 商品名称 | 融合分 | 命中来源 |
  363 +| ---: | --- | --- | ---: | --- |
  364 +| 1 | `3890995` | 12PCS 瓦兹旅行者 2色 回力 开门 1:36 | 1.000000 | Swing + DeepWalk |
  365 +| 2 | `3891001` | 3开门 M3 3色 回力 开门 1:36 | 0.991683 | Swing + DeepWalk |
  366 +| 3 | `3891004` | 12PCS 1:36 回力 4开门 道奇地狱猫 | 0.988255 | Swing + DeepWalk |
  367 +| 4 | `3890988` | 12PCS 宝马XM 3色 回力 开门 1:36 | 0.978798 | Swing + DeepWalk |
  368 +| 5 | `3907916` | 12PCS 六角蝾螈 捏捏乐 | 0.977290 | Swing + DeepWalk |
  369 +
  370 +效果解读:
  371 +
  372 +- 前四项与种子在商品名称上都是 1:36 回力车,多算法共识符合直觉;
  373 +- 第五项虽然被两路行为索引共同命中,但标题语义并不相关,说明协同相关性不能替代商品属性判断;
  374 +- 因此后续商品详情工具仍需校验类目、属性和当前意图,LLM 不能仅凭 `score` 直接展示全部候选;
  375 +- 种子 SKU 会被该工具自动排除。
  376 +
  377 +### 3.5 `recall_products_by_dimensions`
  378 +
  379 +用途:没有强种子,或需要把平台、客户端、分类、供应商、国家、客户类型等画像转成候选时调用。工具优先查询更具体的组合 key,同时查询真实存在的单维度 key 做回退和共识增强。
  380 +
  381 +参数:
  382 +
  383 +| 参数 | 必填 | 范围/默认值 | 含义 |
  384 +| --- | --- | --- | --- |
  385 +| `context` | 与 `interests` 至少一个 | object | 当前平台、客户端、国家和客户类型 |
  386 +| `interests` | 与 `context` 至少一个 | 最多 30 个 | 画像维度值、权重和推断理由 |
  387 +| `list_types` | 否 | 默认全部 4 类 | `hot`、`cart`、`new`、`global` |
  388 +| `top_k` | 否 | 1-100,默认 50 | 最终候选数 |
  389 +| `per_source_k` | 否 | 1-500,默认 100 | 每个 Redis key 最多参与融合的项数 |
  390 +| `exclude_item_ids` | 否 | 最多 500 个 | 需提前排除的 SKU |
  391 +
  392 +`context` 只接受:
  393 +
  394 +```json
  395 +{
  396 + "platform": "essaone",
  397 + "client_platform": "pc",
  398 + "country_code": "344",
  399 + "customer_type": "is_ka_buyer"
  400 +}
  401 +```
  402 +
  403 +`interests` 中的每一项包含 `dimension`、内部 `value`,以及可选的 `weight` 和 `reason`。`weight` 代表本次画像信号的相对强度,不是过滤条件;硬约束仍应在商品详情阶段执行。
  404 +
  405 +真实调用:
  406 +
  407 +```bash
  408 +python3 scripts/agent_recommendation_tools.py call \
  409 + recall_products_by_dimensions \
  410 + --arguments '{
  411 + "context": {
  412 + "platform": "essaone",
  413 + "client_platform": "pc"
  414 + },
  415 + "interests": [{
  416 + "dimension": "category_level2",
  417 + "value": "5",
  418 + "weight": 2,
  419 + "reason": "本轮需要交通工具玩具"
  420 + }],
  421 + "list_types": ["hot"],
  422 + "exclude_item_ids": ["3891002"],
  423 + "top_k": 5,
  424 + "per_source_k": 20
  425 + }'
  426 +```
  427 +
  428 +该输入自动规划并实际命中了 6 个 key:
  429 +
  430 +| 特异度 | 实际 key | 作用 |
  431 +| ---: | --- | --- |
  432 +| 2 | `interest:hot:platform_category2:essaone_5` | 平台 + 二级分类 |
  433 +| 2 | `interest:hot:client_category2:pc_5` | 客户端 + 二级分类 |
  434 +| 2 | `interest:hot:platform_client:essaone_pc` | 平台 + 客户端 |
  435 +| 1 | `interest:hot:category_level2:5` | 二级分类回退 |
  436 +| 1 | `interest:hot:client_platform:pc` | 客户端回退 |
  437 +| 1 | `interest:hot:platform:essaone` | 平台回退 |
  438 +
  439 +真实响应首项:
  440 +
  441 +```json
  442 +{
  443 + "ok": true,
  444 + "items": [
  445 + {
  446 + "item_id": "3992378",
  447 + "score": 1.0,
  448 + "channels": ["dimension"],
  449 + "source_count": 3,
  450 + "reasons": [{
  451 + "type": "matched_dimension",
  452 + "dimension_key": "category_level2:5",
  453 + "list_types": ["hot"],
  454 + "matched": [{
  455 + "dimension": "category_level2",
  456 + "value": "5",
  457 + "origin": "profile",
  458 + "reason": "本轮需要交通工具玩具"
  459 + }]
  460 + }],
  461 + "evidence": [
  462 + {
  463 + "key": "interest:hot:category_level2:5",
  464 + "rank": 2,
  465 + "raw_score": 296.9498,
  466 + "contribution": 0.03225806
  467 + },
  468 + {
  469 + "key": "interest:hot:platform_category2:essaone_5",
  470 + "rank": 2,
  471 + "raw_score": 296.9498,
  472 + "contribution": 0.03145161
  473 + }
  474 + ]
  475 + }
  476 + ],
  477 + "diagnostics": {
  478 + "dimension_plan_count": 6,
  479 + "hit_source_count": 6,
  480 + "missing_source_count": 0,
  481 + "candidate_count_before_limit": 40
  482 + }
  483 +}
  484 +```
  485 +
  486 +Top 5 结果补全名称后:
  487 +
  488 +| 排名 | SKU | 商品名称 | 融合分 | `source_count` |
  489 +| ---: | --- | --- | ---: | ---: |
  490 +| 1 | `3992378` | 环卫吊车 惯性 黑轮 | 1.000000 | 3 |
  491 +| 2 | `3890990` | 12PCS 拉达双灯 3色 回力 开门 1:36 | 0.984127 | 3 |
  492 +| 3 | `3866848` | 遥控水陆警车带灯光 | 0.968750 | 3 |
  493 +| 4 | `3891000` | 12PCS 1:36 回力 3开门 M3 | 0.953846 | 3 |
  494 +| 5 | `3805915` | 遥控战斗机 2通 灯光 | 0.934639 | 3 |
  495 +
  496 +效果解读:五项均属于“交通工具”语义范围,并同时出现在分类、平台分类和客户端分类索引中。`raw_score` 是离线行为聚合分;工具仍按排名做融合,不把 296.9498 与 I2I 相似度直接相加。
  497 +
  498 +使用注意:
  499 +
  500 +- `country_code` 和 `customer_type` 没有单维度 key,只有提供 `platform=essa/essaone` 时才会规划地域组合;
  501 +- 父子分类 ID 不可通过字符串猜测,需要分别从分类树取得;
  502 +- `global` 仍然带 dimension,不代表无条件全站兜底;
  503 +- 该工具没有种子上下文,若某个已购 SKU 需要排除,必须显式放入 `exclude_item_ids`。
  504 +
  505 +### 3.6 `build_recommendation_candidates`
  506 +
  507 +用途:常规智能导购的首选入口。它分别执行协同召回和维度召回,再按通道权重融合,适合同时拥有历史 SKU 和本轮语义/画像的场景。
  508 +
  509 +它接受前两个召回工具的全部参数,并增加:
  510 +
  511 +| 参数 | 默认值 | 含义 |
  512 +| --- | ---: | --- |
  513 +| `collaborative_weight` | 0.65 | 协同通道权重,范围 0-1 |
  514 +| `dimension_weight` | 0.35 | 维度通道权重,范围 0-1 |
  515 +
  516 +至少有一个权重必须大于 0,并且启用的通道要有对应输入。某个通道无候选时,权重会在成功通道间重新归一化。
  517 +
  518 +真实调用:
  519 +
  520 +```bash
  521 +python3 scripts/agent_recommendation_tools.py call \
  522 + build_recommendation_candidates \
  523 + --arguments '{
  524 + "seed_items": [{
  525 + "item_id": "3891002",
  526 + "behavior": "purchase",
  527 + "reason": "用户过去采购过回力合金车"
  528 + }],
  529 + "context": {
  530 + "platform": "essaone",
  531 + "client_platform": "pc"
  532 + },
  533 + "interests": [{
  534 + "dimension": "category_level2",
  535 + "value": "5",
  536 + "weight": 2,
  537 + "reason": "本轮需要交通工具玩具"
  538 + }],
  539 + "algorithms": ["swing", "deepwalk"],
  540 + "list_types": ["hot"],
  541 + "top_k": 5,
  542 + "per_seed_k": 20,
  543 + "per_source_k": 20
  544 + }'
  545 +```
  546 +
  547 +混合工具会把所有种子 SKU 自动加入两个通道的排除集合,因此 `3891002` 不会从维度热门列表重新进入结果。`exclude_item_ids` 仍应用于补充已曝光、已拒绝、不可售等其他 SKU。
  548 +
  549 +真实响应前两项:
  550 +
  551 +```json
  552 +{
  553 + "ok": true,
  554 + "items": [
  555 + {
  556 + "item_id": "3890990",
  557 + "score": 1.0,
  558 + "channels": ["collaborative", "dimension"],
  559 + "source_count": 4,
  560 + "channel_scores": {
  561 + "collaborative": 0.574329,
  562 + "dimension": 0.984127
  563 + },
  564 + "evidence": [
  565 + {
  566 + "source": "swing",
  567 + "key": "item:similar:swing:3891002",
  568 + "rank": 2,
  569 + "raw_score": 0.1818,
  570 + "hybrid_channel_weight": 0.65
  571 + },
  572 + {
  573 + "source": "hot",
  574 + "key": "interest:hot:category_level2:5",
  575 + "rank": 3,
  576 + "raw_score": 231.8954,
  577 + "hybrid_channel_weight": 0.35
  578 + }
  579 + ]
  580 + },
  581 + {
  582 + "item_id": "3891000",
  583 + "score": 0.99376,
  584 + "channels": ["collaborative", "dimension"],
  585 + "source_count": 4,
  586 + "channel_scores": {
  587 + "collaborative": 0.583744,
  588 + "dimension": 0.953846
  589 + }
  590 + }
  591 + ],
  592 + "diagnostics": {
  593 + "effective_channel_weights": {
  594 + "collaborative": 0.65,
  595 + "dimension": 0.35
  596 + },
  597 + "successful_channels": ["collaborative", "dimension"],
  598 + "candidate_count_before_limit": 63
  599 + }
  600 +}
  601 +```
  602 +
  603 +Top 5 结果补全名称后:
  604 +
  605 +| 排名 | SKU | 商品名称 | 融合分 | 通道 |
  606 +| ---: | --- | --- | ---: | --- |
  607 +| 1 | `3890990` | 12PCS 拉达双灯 3色 回力 开门 1:36 | 1.000000 | 协同 + 维度 |
  608 +| 2 | `3891000` | 12PCS 1:36 回力 3开门 M3 | 0.993760 | 协同 + 维度 |
  609 +| 3 | `3890998` | 12PCS X7 3色 回力 开门 1:36 | 0.926006 | 协同 + 维度 |
  610 +| 4 | `3890993` | 12PCS 1:36 回力 3开门 大奔300SL | 0.916008 | 协同 + 维度 |
  611 +| 5 | `3890995` | 12PCS 瓦兹旅行者 2色 回力 开门 1:36 | 0.905597 | 仅协同 |
  612 +
  613 +效果解读:
  614 +
  615 +- `3890990` 在 Swing 中排名 2,又同时命中 3 个交通工具维度 key,跨通道共识使其成为第一;
  616 +- `3891000` 在 Swing 中排名 1,但维度内排名 5,因此混合后略低于 `3890990`;
  617 +- `3890995` 的协同共识很强,但没有进入本次维度池,最终排在双通道候选之后;
  618 +- 这正是混合工具相对“取某一路 Top N”的价值:既利用具体 SKU 行为,也约束在本轮交通工具意图内。
  619 +
  620 +### 3.7 一次完整的 Agent 编排
  621 +
  622 +假设用户表达“继续找适合 essaone PC 客户的 1:36 回力交通工具”,且画像里有已购 SKU `3891002`。
  623 +
  624 +第一步,解析自然语言分类:
  625 +
  626 +```python
  627 +resolved = tools.call_tool('resolve_recommendation_dimension', {
  628 + 'dimension': 'category_level2',
  629 + 'query': '交通工具',
  630 + 'limit': 3,
  631 +})
  632 +if not resolved['ok'] or not resolved['matches']:
  633 + # 改由分类树或商品搜索服务取得内部 ID。
  634 + raise LookupError('category dimension unresolved')
  635 +
  636 +category_id = resolved['matches'][0]['value']
  637 +```
  638 +
  639 +第二步,生成候选:
  640 +
  641 +```python
  642 +already_exposed_ids = []
  643 +candidates = tools.call_tool('build_recommendation_candidates', {
  644 + 'seed_items': [{
  645 + 'item_id': '3891002',
  646 + 'behavior': 'purchase',
  647 + 'reason': '用户过去采购过回力合金车',
  648 + }],
  649 + 'context': {
  650 + 'platform': 'essaone',
  651 + 'client_platform': 'pc',
  652 + },
  653 + 'interests': [{
  654 + 'dimension': 'category_level2',
  655 + 'value': category_id,
  656 + 'weight': 2,
  657 + 'reason': '本轮明确需要交通工具',
  658 + }],
  659 + 'algorithms': ['swing', 'deepwalk'],
  660 + 'list_types': ['hot'],
  661 + 'exclude_item_ids': already_exposed_ids,
  662 + 'top_k': 50,
  663 +})
  664 +```
  665 +
  666 +第三步,批量补全并执行确定性过滤。下面是编排伪代码,`product_catalog` 不是本仓库实现:
  667 +
  668 +```python
  669 +candidate_ids = [item['item_id'] for item in candidates['items']]
  670 +products = product_catalog.batch_get(candidate_ids)
  671 +
  672 +eligible_products = [
  673 + product for product in products
  674 + if product.is_on_sale
  675 + and product.stock_available
  676 + and product.visible_to_customer
  677 + and product.can_ship_to_country
  678 +]
  679 +```
  680 +
  681 +第四步,把候选的 `reasons` / `evidence` 与权威商品事实合并后交给 LLM 重排。LLM 可以说“与你采购过的 1:36 回力车相似,并且在当前平台交通工具中热度较高”,但价格、材质、尺寸和库存必须来自 `product_catalog`,不能从协同证据推断。
  682 +
  683 +若结果不符合预期,按以下顺序定位:
  684 +
  685 +1. `resolve` 是否返回了正确内部 ID;
  686 +2. `diagnostics.hit_source_count` 是否为 0;
  687 +3. `missing_keys_sample` 是否显示生产/消费 key 不一致;
  688 +4. `malformed_source_count` 是否说明 value 格式异常;
  689 +5. 候选是否在实时商品过滤阶段被全部删除;
  690 +6. LLM 是否错误地把低置信画像当成硬约束。
  691 +
  692 +## 4. 排名与解释
  693 +
  694 +### 4.1 路内融合
83 695  
84 696 Swing、W2V、DeepWalk、向量相似和兴趣聚合的原始 score 量纲不同。直接相加会让数值范围大的算法支配结果,因此工具使用加权 Reciprocal Rank Fusion:
85 697  
... ... @@ -92,7 +704,7 @@ candidate_score = sum(contribution)
92 704  
93 705 每一路融合后把本次调用的最高分归一化为 1。这个 `score` 只能在同一次工具调用内比较,不是点击率或购买概率。
94 706  
95   -### 3.2 两通道融合
  707 +### 4.2 两通道融合
96 708  
97 709 `build_recommendation_candidates` 默认使用:
98 710  
... ... @@ -102,7 +714,7 @@ candidate_score = sum(contribution)
102 714  
103 715 如果某一路没有候选,权重会在成功通道之间重新归一化,避免可用结果被无效通道无故压低。调用方可按实验配置调整两个权重,但不应根据单次对话随意改变离线算法内部权重。
104 716  
105   -### 3.3 证据
  717 +### 4.3 证据
106 718  
107 719 候选示例:
108 720  
... ... @@ -120,7 +732,7 @@ candidate_score = sum(contribution)
120 732 },
121 733 {
122 734 "type": "matched_dimension",
123   - "dimension_key": "platform_category2:essaone_29",
  735 + "dimension_key": "platform_category2:essaone_5",
124 736 "list_types": ["hot"]
125 737 }
126 738 ],
... ... @@ -139,9 +751,9 @@ candidate_score = sum(contribution)
139 751  
140 752 LLM 可以把 `reasons` 转成用户可理解的推荐依据,但不能把“相似/热门”虚构成商品属性。属性描述必须来自后续商品详情工具。
141 753  
142   -## 4. 运行方式
  754 +## 5. 运行方式
143 755  
144   -### 4.1 生成维度字典
  756 +### 5.1 生成维度字典
145 757  
146 758 正常运行 `fetch_item_attributes.py` 时会额外生成:
147 759  
... ... @@ -151,7 +763,7 @@ output/agent_dimension_catalog.json
151 763  
152 764 它只包含分类、供应商、平台和客户端映射,不包含约 300 万商品名称,适合在线进程加载。该文件是生成数据,保持在 `.gitignore` 中并随离线任务更新。
153 765  
154   -### 4.2 列出工具 schema
  766 +### 5.2 列出工具 schema
155 767  
156 768 ```bash
157 769 cd offline_tasks
... ... @@ -160,7 +772,7 @@ python3 scripts/agent_recommendation_tools.py list-tools
160 772  
161 773 输出可直接注册到支持 JSON Schema function tools 的 Agent 框架。
162 774  
163   -### 4.3 配置 Redis
  775 +### 5.3 配置 Redis
164 776  
165 777 工具不读取仓库中的明文连接配置。使用以下环境变量之一:
166 778  
... ... @@ -180,21 +792,22 @@ RECOMMENDATION_DIMENSION_CATALOG
180 792  
181 793 不要把密码写进 tool arguments、日志、文档或模型上下文。
182 794  
183   -### 4.4 单次调用
  795 +### 5.4 单次调用
  796 +
  797 +下面是最小混合调用;逐工具参数及完整真实响应见第 3 节。
184 798  
185 799 ```bash
186 800 python3 scripts/agent_recommendation_tools.py call \
187 801 build_recommendation_candidates \
188 802 --arguments '{
189   - "seed_items":[{"item_id":"3385246","behavior":"click"}],
  803 + "seed_items":[{"item_id":"3891002","behavior":"purchase"}],
190 804 "context":{"platform":"essaone","client_platform":"pc"},
191   - "interests":[{"dimension":"category_level2","value":"29","weight":2}],
192   - "exclude_item_ids":["3385246"],
193   - "top_k":30
  805 + "interests":[{"dimension":"category_level2","value":"5","weight":2}],
  806 + "top_k":5
194 807 }'
195 808 ```
196 809  
197   -### 4.5 长驻 stdio
  810 +### 5.5 长驻 stdio
198 811  
199 812 ```bash
200 813 python3 scripts/agent_recommendation_tools.py serve-stdio
... ... @@ -203,7 +816,7 @@ python3 scripts/agent_recommendation_tools.py serve-stdio
203 816 每行一个请求:
204 817  
205 818 ```json
206   -{"id":"req-1","tool":"recall_similar_products","arguments":{"seed_items":[{"item_id":"3385246"}]}}
  819 +{"id":"req-1","tool":"recall_similar_products","arguments":{"seed_items":[{"item_id":"3891002"}]}}
207 820 ```
208 821  
209 822 每行一个响应:
... ... @@ -214,7 +827,7 @@ python3 scripts/agent_recommendation_tools.py serve-stdio
214 827  
215 828 这不是特定厂商协议;可由现有 Agent 网关包装成 MCP、HTTP 或框架原生 Tool。
216 829  
217   -### 4.6 Python 集成
  830 +### 5.6 Python 集成
218 831  
219 832 ```python
220 833 import redis
... ... @@ -239,7 +852,7 @@ result = tools.call_tool(tool_name, tool_arguments)
239 852  
240 853 上述导入方式从仓库根目录运行;若在线项目只把 `offline_tasks/` 加入 `PYTHONPATH`,则改为从 `agent_tools` 导入。正式跨仓库复用时建议将该目录构建成内部 Python 包并锁定版本。
241 854  
242   -## 5. 错误与诊断
  855 +## 6. 错误与诊断
243 856  
244 857 Tool 调用永远返回顶层 `ok`。错误结构:
245 858  
... ... @@ -266,7 +879,7 @@ Tool 调用永远返回顶层 `ok`。错误结构:
266 879  
267 880 这些字段用于日志和指标,不建议原样展示给最终用户。
268 881  
269   -## 6. Agent 编排建议
  882 +## 7. Agent 编排建议
270 883  
271 884 1. 从画像中选择最近、高强度且能代表当前意图的 3 到 10 个种子,不要把全部历史灌给工具。
272 885 2. 对 LLM 推断出的兴趣保留置信度;低置信推断应降低 `weight`,硬约束不能只靠 weight 表达。
... ... @@ -276,7 +889,7 @@ Tool 调用永远返回顶层 `ok`。错误结构:
276 889 6. 最终理由区分“画像依据”“协同证据”和“商品事实”,避免把统计相关性写成因果关系。
277 890 7. 无候选时读取 diagnostics,区分无种子、维度 ID 错、key 缺失、格式异常和实时过滤清空。
278 891  
279   -## 7. 评估与上线
  892 +## 8. 评估与上线
280 893  
281 894 离线回放至少比较:
282 895  
... ... @@ -294,7 +907,7 @@ Tool 调用永远返回顶层 `ok`。错误结构:
294 907  
295 908 发布时把算法权重、通道权重和候选池大小纳入实验配置;工具 schema 与 Redis 契约版本应进入日志,便于归因和回滚。
296 909  
297   -## 8. 后续扩展
  910 +## 9. 后续扩展
298 911  
299 912 按收益和依赖关系建议继续建设:
300 913  
... ...
offline_tasks/test_agent_recommendation_tools.py
... ... @@ -218,6 +218,29 @@ class RecommendationAgentToolsTest(unittest.TestCase):
218 218 {'collaborative', 'dimension'},
219 219 )
220 220  
  221 + def test_hybrid_recall_excludes_seed_from_dimension_channel(self):
  222 + self.store.set(
  223 + 'interest:hot:platform:essaone',
  224 + '100:100,304:90,305:80',
  225 + )
  226 + result = self.tools.build_recommendation_candidates(
  227 + seed_items=[{'item_id': '100'}],
  228 + context={'platform': 'essaone'},
  229 + algorithms=['swing'],
  230 + list_types=['hot'],
  231 + top_k=10,
  232 + exclude_item_ids=[
  233 + 'already-excluded-%s' % index for index in range(500)
  234 + ],
  235 + )
  236 + self.assertNotIn('100', [item['item_id'] for item in result['items']])
  237 + self.assertGreater(
  238 + result['diagnostics']['channel_diagnostics']['dimension'][
  239 + 'excluded_occurrence_count'
  240 + ],
  241 + 0,
  242 + )
  243 +
221 244 def test_catalog_resolution_and_tool_dispatch(self):
222 245 resolved = self.tools.call_tool(
223 246 'resolve_recommendation_dimension',
... ...