diff --git a/offline_tasks/agent_tools/service.py b/offline_tasks/agent_tools/service.py index e023e30..310f92c 100644 --- a/offline_tasks/agent_tools/service.py +++ b/offline_tasks/agent_tools/service.py @@ -433,6 +433,19 @@ class RecommendationAgentTools(object): list_types=None, top_k=50, per_source_k=100, exclude_item_ids=None): + return self._recall_products_by_dimensions( + context=context, + interests=interests, + list_types=list_types, + top_k=top_k, + per_source_k=per_source_k, + exclude_item_ids=exclude_item_ids, + ) + + def _recall_products_by_dimensions( + self, context=None, interests=None, list_types=None, top_k=50, + per_source_k=100, exclude_item_ids=None, + additional_exclude_item_ids=None): top_k = _bounded_integer(top_k, 'top_k', 50, 1, 100) per_source_k = _bounded_integer( per_source_k, 'per_source_k', 100, 1, 500 @@ -440,6 +453,11 @@ class RecommendationAgentTools(object): selected_list_types = self._normalize_list_types(list_types) plans = self._plan_dimensions(context, interests) excluded = set(_unique_strings(exclude_item_ids, 'exclude_item_ids')) + excluded.update(_unique_strings( + additional_exclude_item_ids, + 'additional_exclude_item_ids', + maximum=20, + )) source_plans = [] for plan in plans: @@ -532,6 +550,11 @@ class RecommendationAgentTools(object): if collaborative_weight + dimension_weight <= 0: raise ToolInputError('At least one channel weight must be positive') + seed_item_ids = [] + if seed_items: + normalized_seeds = self._normalize_seed_items(seed_items) + seed_item_ids = [seed['item_id'] for seed in normalized_seeds] + pool_size = min(100, max(top_k * 4, 50)) channel_results = {} if seed_items and collaborative_weight > 0: @@ -543,13 +566,14 @@ class RecommendationAgentTools(object): exclude_item_ids=exclude_item_ids, ) if (context or interests) and dimension_weight > 0: - channel_results['dimension'] = self.recall_products_by_dimensions( + channel_results['dimension'] = self._recall_products_by_dimensions( context=context, interests=interests, list_types=list_types, top_k=pool_size, per_source_k=per_source_k, exclude_item_ids=exclude_item_ids, + additional_exclude_item_ids=seed_item_ids, ) if not channel_results: raise ToolInputError( diff --git a/offline_tasks/doc/智能导购Agent工具集.md b/offline_tasks/doc/智能导购Agent工具集.md index e15a0e4..f7588f9 100644 --- a/offline_tasks/doc/智能导购Agent工具集.md +++ b/offline_tasks/doc/智能导购Agent工具集.md @@ -41,7 +41,7 @@ ```json { - "item_id": "3385246", + "item_id": "3891002", "behavior": "purchase", "reason": "用户过去采购过同类商品" } @@ -56,9 +56,9 @@ ```json { "dimension": "category_level2", - "value": "29", + "value": "5", "weight": 2.0, - "reason": "画像显示用户持续采购玩具车辆" + "reason": "画像显示用户持续采购交通工具玩具" } ``` @@ -77,9 +77,621 @@ 工具会自动规划 `platform_category2`、`client_category2`、平台国家客户类型等组合 key,同时查询更宽泛的单维度。具体可用 key 见 [在线召回Redis Key清单.md](./在线召回Redis%20Key清单.md)。 -## 3. 排名与解释 +### 2.3 调用入口 -### 3.1 路内融合 +所有工具都可以通过同一个服务对象调用: + +```python +result = tools.call_tool(tool_name, arguments) +``` + +也可以通过 CLI 调试: + +```bash +cd offline_tasks +python3 scripts/agent_recommendation_tools.py call \ + \ + --arguments '' +``` + +CLI 默认读取环境变量连接 Redis。`recommendation_capabilities` 不读取索引;`resolve_recommendation_dimension` 只读取本地维度字典;三个召回工具会访问 Redis。 + +所有调用都返回 JSON object,不抛出供 Agent 直接处理的业务异常: + +| 字段 | 含义 | +| --- | --- | +| `ok` | 调用是否成功 | +| `items` | 按融合分降序排列的候选;仅召回工具返回 | +| `score` | 当前调用内归一化到 0-1 的融合分,不是概率 | +| `channels` | 候选来自 `collaborative`、`dimension` 或两者 | +| `source_count` | 贡献该候选的独立 Redis key 数 | +| `reasons` | 面向 Agent 的聚合理由 | +| `evidence` | 实际 key、路内排名、原始分及 RRF 贡献 | +| `diagnostics` | 计划、命中、缺失、格式异常、排除和候选数 | +| `error` | 失败时的 `code`、`message` 和 `retryable` | + +工具刻意只返回 SKU ID,不返回商品名称、价格和库存。调用方应批量补全商品详情;本文真实示例中的名称仅用于帮助阅读,不属于工具响应。 + +## 3. 五个工具的完整用法 + +### 3.1 真实示例的数据口径 + +以下示例不是虚构数据,取自本机 2026-08-22 的实际离线产出: + +```text +output/i2i_swing_20260822.txt +output/i2i_session_w2v_20260822.txt +output/i2i_deepwalk_20260822.txt +output/interest_aggregation_hot_20260822.txt +output/item_attributes_mappings.json +``` + +为避免把文档验证误写成生产联调,本次示例把上述文件中对应行原样装入 `MemoryIndexStore`,再调用同一个 `RecommendationAgentTools`。对于相同的 key/value 快照,`RedisIndexStore` 的工具结果一致。本次没有读取线上 Redis,也没有验证示例商品当前价格、库存和可售状态。 + +下文表格中的名称来自同日 `item_attributes_mappings.json`。为便于横向比较,省略了部分颜色、材质和包装尾缀;SKU、排名、分数及证据均保留真实工具结果。 + +示例场景: + +| 数据 | 真实值 | +| --- | --- | +| 种子 SKU | `3891002` | +| 种子名称 | 12PCS 1:36 回力 3开门 大众甲壳虫 | +| 自然语言兴趣 | 交通工具 | +| 解析后的二级分类 | `category_level2:5` | +| 请求上下文 | `platform=essaone`、`client_platform=pc` | +| 兴趣列表 | `hot` | + +### 3.2 `recommendation_capabilities` + +用途:在 Agent 初始化、工具版本变化或调用方不确定索引能力时,发现算法、维度、key 模式和融合语义。它不查询 Redis,不应在每轮对话重复调用。 + +参数:无。 + +调用: + +```bash +python3 scripts/agent_recommendation_tools.py call \ + recommendation_capabilities \ + --arguments '{}' +``` + +响应节选: + +```json +{ + "ok": true, + "version": "1.0.0", + "catalog_available": true, + "algorithms": [ + { + "name": "swing", + "primary_key_pattern": "item:similar:swing:{item_id}", + "fallback_key_patterns": [], + "signal": "time-aware co-interaction similarity" + }, + { + "name": "session_w2v", + "primary_key_pattern": "item:similar:session_w2v:{item_id}", + "fallback_key_patterns": ["item:similar:w2v:{item_id}"], + "signal": "session sequence similarity" + } + ], + "list_types": [ + {"name": "hot", "key_pattern": "interest:hot:{dimension_key}"}, + {"name": "cart", "key_pattern": "interest:cart:{dimension_key}"}, + {"name": "new", "key_pattern": "interest:new:{dimension_key}"}, + {"name": "global", "key_pattern": "interest:global:{dimension_key}"} + ], + "ranking": { + "recall_fusion": "weighted_reciprocal_rank_fusion", + "score_range": [0, 1] + } +} +``` + +使用者应据此: + +1. 只传 `algorithms` 中声明的算法名; +2. 使用 `session_w2v` 作为当前名称,不主动拼历史 `w2v` key; +3. 在 `catalog_available=false` 时跳过名称解析,改用商品目录提供的内部 ID; +4. 把 `version` 和实际工具参数记录到调用日志。 + +### 3.3 `resolve_recommendation_dimension` + +用途:把“交通工具”“桌面游戏”或供应商名称转换成离线兴趣索引使用的内部值。它只做字典匹配,不查询商品、不召回候选,也不会猜测不存在的 ID。 + +参数: + +| 参数 | 必填 | 范围/默认值 | 含义 | +| --- | --- | --- | --- | +| `dimension` | 是 | 支持的维度枚举 | 要解析的目标维度 | +| `query` | 是 | 1-200 字符 | ID、完整名称或名称片段 | +| `limit` | 否 | 1-20,默认 10 | 最多返回多少个候选 | + +支持的 `dimension`: + +```text +platform, client_platform, country_code, customer_type, supplier, +category_level1, category_level2, category_level3, category_level4 +``` + +默认生成的字典包含分类、供应商、平台和客户端。`country_code`、`customer_type` 如果未扩充到字典,会返回空匹配;此时应从客户画像或权威字典取得内部值。 + +真实调用: + +```bash +python3 scripts/agent_recommendation_tools.py call \ + resolve_recommendation_dimension \ + --arguments '{ + "dimension": "category_level2", + "query": "交通工具", + "limit": 3 + }' +``` + +真实响应: + +```json +{ + "ok": true, + "dimension": "category_level2", + "query": "交通工具", + "catalog_available": true, + "matches": [ + { + "value": "5", + "label": "交通工具", + "match_type": "exact_label", + "score": 0.99 + } + ], + "guidance": null +} +``` + +效果解读:调用方后续应传 `{"dimension":"category_level2","value":"5"}`,不能把“交通工具”直接拼成 Redis key。`matches[].score` 是字典匹配置信度,不是商品推荐分。 + +常见 `match_type` 从强到弱为: + +| 类型 | 含义 | +| --- | --- | +| `exact_value` | query 就是内部值 | +| `exact_label` | query 与名称完全一致 | +| `label_prefix` | 名称以前缀命中 | +| `label_contains` | 名称包含 query | +| `all_tokens` | query 的所有空格分词都出现在名称中 | + +### 3.4 `recall_similar_products` + +用途:当画像或当前会话里已有明确 SKU 时,从多种 I2I 索引召回相似商品。适用于“看了又看”“买过该商品的人还关注什么”和相似商品扩展;没有可信种子时不要调用。 + +参数: + +| 参数 | 必填 | 范围/默认值 | 含义 | +| --- | --- | --- | --- | +| `seed_items` | 是 | 1-20 个 | 种子商品及行为、权重、理由 | +| `algorithms` | 否 | 默认全部 7 路 | 限定使用的 I2I 算法 | +| `top_k` | 否 | 1-100,默认 50 | 最终候选数 | +| `per_seed_k` | 否 | 1-200,默认 50 | 每个种子、每种算法最多取多少项 | +| `exclude_item_ids` | 否 | 最多 500 个 | 已曝光、已购买、不可售等排除项 | + +`seed_items` 字段: + +| 字段 | 必填 | 含义 | +| --- | --- | --- | +| `item_id` | 是 | SKU ID,建议传字符串 | +| `behavior` | 否 | 默认 `click`;决定默认种子权重 | +| `weight` | 否 | `0 < weight <= 10`;提供后覆盖行为默认权重 | +| `reason` | 否 | 选择该种子的画像依据,进入返回证据 | + +行为默认权重: + +| behavior | 权重 | +| --- | ---: | +| `click` / `view` | 1 | +| `addToPool` | 2 | +| `addToCart` | 3 | +| `contactFactory` | 5 | +| `purchase` | 10 | + +真实调用: + +```bash +python3 scripts/agent_recommendation_tools.py call \ + recall_similar_products \ + --arguments '{ + "seed_items": [{ + "item_id": "3891002", + "behavior": "purchase", + "reason": "用户过去采购过回力合金车" + }], + "algorithms": ["swing", "session_w2v", "deepwalk"], + "top_k": 5, + "per_seed_k": 20 + }' +``` + +真实响应首项: + +```json +{ + "ok": true, + "items": [ + { + "item_id": "3890995", + "score": 1.0, + "channels": ["collaborative"], + "source_count": 2, + "reasons": [{ + "type": "similar_to_seed", + "seed_item_id": "3891002", + "algorithms": ["swing", "deepwalk"], + "profile_reason": "用户过去采购过回力合金车" + }], + "evidence": [ + { + "source": "swing", + "key": "item:similar:swing:3891002", + "rank": 7, + "raw_score": 0.1538, + "contribution": 0.14179104 + }, + { + "source": "deepwalk", + "key": "item:similar:deepwalk:3891002", + "rank": 8, + "raw_score": 0.9768, + "contribution": 0.125 + } + ] + } + ], + "diagnostics": { + "planned_source_count": 3, + "queried_key_count": 4, + "hit_source_count": 3, + "candidate_count_before_limit": 50 + } +} +``` + +`queried_key_count=4` 是因为 `session_w2v` 同时批量查询当前 key 和历史 `w2v` 后备 key,但只会选择第一个可解析的值作为该 source。 + +Top 5 结果补全名称后: + +| 排名 | SKU | 商品名称 | 融合分 | 命中来源 | +| ---: | --- | --- | ---: | --- | +| 1 | `3890995` | 12PCS 瓦兹旅行者 2色 回力 开门 1:36 | 1.000000 | Swing + DeepWalk | +| 2 | `3891001` | 3开门 M3 3色 回力 开门 1:36 | 0.991683 | Swing + DeepWalk | +| 3 | `3891004` | 12PCS 1:36 回力 4开门 道奇地狱猫 | 0.988255 | Swing + DeepWalk | +| 4 | `3890988` | 12PCS 宝马XM 3色 回力 开门 1:36 | 0.978798 | Swing + DeepWalk | +| 5 | `3907916` | 12PCS 六角蝾螈 捏捏乐 | 0.977290 | Swing + DeepWalk | + +效果解读: + +- 前四项与种子在商品名称上都是 1:36 回力车,多算法共识符合直觉; +- 第五项虽然被两路行为索引共同命中,但标题语义并不相关,说明协同相关性不能替代商品属性判断; +- 因此后续商品详情工具仍需校验类目、属性和当前意图,LLM 不能仅凭 `score` 直接展示全部候选; +- 种子 SKU 会被该工具自动排除。 + +### 3.5 `recall_products_by_dimensions` + +用途:没有强种子,或需要把平台、客户端、分类、供应商、国家、客户类型等画像转成候选时调用。工具优先查询更具体的组合 key,同时查询真实存在的单维度 key 做回退和共识增强。 + +参数: + +| 参数 | 必填 | 范围/默认值 | 含义 | +| --- | --- | --- | --- | +| `context` | 与 `interests` 至少一个 | object | 当前平台、客户端、国家和客户类型 | +| `interests` | 与 `context` 至少一个 | 最多 30 个 | 画像维度值、权重和推断理由 | +| `list_types` | 否 | 默认全部 4 类 | `hot`、`cart`、`new`、`global` | +| `top_k` | 否 | 1-100,默认 50 | 最终候选数 | +| `per_source_k` | 否 | 1-500,默认 100 | 每个 Redis key 最多参与融合的项数 | +| `exclude_item_ids` | 否 | 最多 500 个 | 需提前排除的 SKU | + +`context` 只接受: + +```json +{ + "platform": "essaone", + "client_platform": "pc", + "country_code": "344", + "customer_type": "is_ka_buyer" +} +``` + +`interests` 中的每一项包含 `dimension`、内部 `value`,以及可选的 `weight` 和 `reason`。`weight` 代表本次画像信号的相对强度,不是过滤条件;硬约束仍应在商品详情阶段执行。 + +真实调用: + +```bash +python3 scripts/agent_recommendation_tools.py call \ + recall_products_by_dimensions \ + --arguments '{ + "context": { + "platform": "essaone", + "client_platform": "pc" + }, + "interests": [{ + "dimension": "category_level2", + "value": "5", + "weight": 2, + "reason": "本轮需要交通工具玩具" + }], + "list_types": ["hot"], + "exclude_item_ids": ["3891002"], + "top_k": 5, + "per_source_k": 20 + }' +``` + +该输入自动规划并实际命中了 6 个 key: + +| 特异度 | 实际 key | 作用 | +| ---: | --- | --- | +| 2 | `interest:hot:platform_category2:essaone_5` | 平台 + 二级分类 | +| 2 | `interest:hot:client_category2:pc_5` | 客户端 + 二级分类 | +| 2 | `interest:hot:platform_client:essaone_pc` | 平台 + 客户端 | +| 1 | `interest:hot:category_level2:5` | 二级分类回退 | +| 1 | `interest:hot:client_platform:pc` | 客户端回退 | +| 1 | `interest:hot:platform:essaone` | 平台回退 | + +真实响应首项: + +```json +{ + "ok": true, + "items": [ + { + "item_id": "3992378", + "score": 1.0, + "channels": ["dimension"], + "source_count": 3, + "reasons": [{ + "type": "matched_dimension", + "dimension_key": "category_level2:5", + "list_types": ["hot"], + "matched": [{ + "dimension": "category_level2", + "value": "5", + "origin": "profile", + "reason": "本轮需要交通工具玩具" + }] + }], + "evidence": [ + { + "key": "interest:hot:category_level2:5", + "rank": 2, + "raw_score": 296.9498, + "contribution": 0.03225806 + }, + { + "key": "interest:hot:platform_category2:essaone_5", + "rank": 2, + "raw_score": 296.9498, + "contribution": 0.03145161 + } + ] + } + ], + "diagnostics": { + "dimension_plan_count": 6, + "hit_source_count": 6, + "missing_source_count": 0, + "candidate_count_before_limit": 40 + } +} +``` + +Top 5 结果补全名称后: + +| 排名 | SKU | 商品名称 | 融合分 | `source_count` | +| ---: | --- | --- | ---: | ---: | +| 1 | `3992378` | 环卫吊车 惯性 黑轮 | 1.000000 | 3 | +| 2 | `3890990` | 12PCS 拉达双灯 3色 回力 开门 1:36 | 0.984127 | 3 | +| 3 | `3866848` | 遥控水陆警车带灯光 | 0.968750 | 3 | +| 4 | `3891000` | 12PCS 1:36 回力 3开门 M3 | 0.953846 | 3 | +| 5 | `3805915` | 遥控战斗机 2通 灯光 | 0.934639 | 3 | + +效果解读:五项均属于“交通工具”语义范围,并同时出现在分类、平台分类和客户端分类索引中。`raw_score` 是离线行为聚合分;工具仍按排名做融合,不把 296.9498 与 I2I 相似度直接相加。 + +使用注意: + +- `country_code` 和 `customer_type` 没有单维度 key,只有提供 `platform=essa/essaone` 时才会规划地域组合; +- 父子分类 ID 不可通过字符串猜测,需要分别从分类树取得; +- `global` 仍然带 dimension,不代表无条件全站兜底; +- 该工具没有种子上下文,若某个已购 SKU 需要排除,必须显式放入 `exclude_item_ids`。 + +### 3.6 `build_recommendation_candidates` + +用途:常规智能导购的首选入口。它分别执行协同召回和维度召回,再按通道权重融合,适合同时拥有历史 SKU 和本轮语义/画像的场景。 + +它接受前两个召回工具的全部参数,并增加: + +| 参数 | 默认值 | 含义 | +| --- | ---: | --- | +| `collaborative_weight` | 0.65 | 协同通道权重,范围 0-1 | +| `dimension_weight` | 0.35 | 维度通道权重,范围 0-1 | + +至少有一个权重必须大于 0,并且启用的通道要有对应输入。某个通道无候选时,权重会在成功通道间重新归一化。 + +真实调用: + +```bash +python3 scripts/agent_recommendation_tools.py call \ + build_recommendation_candidates \ + --arguments '{ + "seed_items": [{ + "item_id": "3891002", + "behavior": "purchase", + "reason": "用户过去采购过回力合金车" + }], + "context": { + "platform": "essaone", + "client_platform": "pc" + }, + "interests": [{ + "dimension": "category_level2", + "value": "5", + "weight": 2, + "reason": "本轮需要交通工具玩具" + }], + "algorithms": ["swing", "deepwalk"], + "list_types": ["hot"], + "top_k": 5, + "per_seed_k": 20, + "per_source_k": 20 + }' +``` + +混合工具会把所有种子 SKU 自动加入两个通道的排除集合,因此 `3891002` 不会从维度热门列表重新进入结果。`exclude_item_ids` 仍应用于补充已曝光、已拒绝、不可售等其他 SKU。 + +真实响应前两项: + +```json +{ + "ok": true, + "items": [ + { + "item_id": "3890990", + "score": 1.0, + "channels": ["collaborative", "dimension"], + "source_count": 4, + "channel_scores": { + "collaborative": 0.574329, + "dimension": 0.984127 + }, + "evidence": [ + { + "source": "swing", + "key": "item:similar:swing:3891002", + "rank": 2, + "raw_score": 0.1818, + "hybrid_channel_weight": 0.65 + }, + { + "source": "hot", + "key": "interest:hot:category_level2:5", + "rank": 3, + "raw_score": 231.8954, + "hybrid_channel_weight": 0.35 + } + ] + }, + { + "item_id": "3891000", + "score": 0.99376, + "channels": ["collaborative", "dimension"], + "source_count": 4, + "channel_scores": { + "collaborative": 0.583744, + "dimension": 0.953846 + } + } + ], + "diagnostics": { + "effective_channel_weights": { + "collaborative": 0.65, + "dimension": 0.35 + }, + "successful_channels": ["collaborative", "dimension"], + "candidate_count_before_limit": 63 + } +} +``` + +Top 5 结果补全名称后: + +| 排名 | SKU | 商品名称 | 融合分 | 通道 | +| ---: | --- | --- | ---: | --- | +| 1 | `3890990` | 12PCS 拉达双灯 3色 回力 开门 1:36 | 1.000000 | 协同 + 维度 | +| 2 | `3891000` | 12PCS 1:36 回力 3开门 M3 | 0.993760 | 协同 + 维度 | +| 3 | `3890998` | 12PCS X7 3色 回力 开门 1:36 | 0.926006 | 协同 + 维度 | +| 4 | `3890993` | 12PCS 1:36 回力 3开门 大奔300SL | 0.916008 | 协同 + 维度 | +| 5 | `3890995` | 12PCS 瓦兹旅行者 2色 回力 开门 1:36 | 0.905597 | 仅协同 | + +效果解读: + +- `3890990` 在 Swing 中排名 2,又同时命中 3 个交通工具维度 key,跨通道共识使其成为第一; +- `3891000` 在 Swing 中排名 1,但维度内排名 5,因此混合后略低于 `3890990`; +- `3890995` 的协同共识很强,但没有进入本次维度池,最终排在双通道候选之后; +- 这正是混合工具相对“取某一路 Top N”的价值:既利用具体 SKU 行为,也约束在本轮交通工具意图内。 + +### 3.7 一次完整的 Agent 编排 + +假设用户表达“继续找适合 essaone PC 客户的 1:36 回力交通工具”,且画像里有已购 SKU `3891002`。 + +第一步,解析自然语言分类: + +```python +resolved = tools.call_tool('resolve_recommendation_dimension', { + 'dimension': 'category_level2', + 'query': '交通工具', + 'limit': 3, +}) +if not resolved['ok'] or not resolved['matches']: + # 改由分类树或商品搜索服务取得内部 ID。 + raise LookupError('category dimension unresolved') + +category_id = resolved['matches'][0]['value'] +``` + +第二步,生成候选: + +```python +already_exposed_ids = [] +candidates = tools.call_tool('build_recommendation_candidates', { + 'seed_items': [{ + 'item_id': '3891002', + 'behavior': 'purchase', + 'reason': '用户过去采购过回力合金车', + }], + 'context': { + 'platform': 'essaone', + 'client_platform': 'pc', + }, + 'interests': [{ + 'dimension': 'category_level2', + 'value': category_id, + 'weight': 2, + 'reason': '本轮明确需要交通工具', + }], + 'algorithms': ['swing', 'deepwalk'], + 'list_types': ['hot'], + 'exclude_item_ids': already_exposed_ids, + 'top_k': 50, +}) +``` + +第三步,批量补全并执行确定性过滤。下面是编排伪代码,`product_catalog` 不是本仓库实现: + +```python +candidate_ids = [item['item_id'] for item in candidates['items']] +products = product_catalog.batch_get(candidate_ids) + +eligible_products = [ + product for product in products + if product.is_on_sale + and product.stock_available + and product.visible_to_customer + and product.can_ship_to_country +] +``` + +第四步,把候选的 `reasons` / `evidence` 与权威商品事实合并后交给 LLM 重排。LLM 可以说“与你采购过的 1:36 回力车相似,并且在当前平台交通工具中热度较高”,但价格、材质、尺寸和库存必须来自 `product_catalog`,不能从协同证据推断。 + +若结果不符合预期,按以下顺序定位: + +1. `resolve` 是否返回了正确内部 ID; +2. `diagnostics.hit_source_count` 是否为 0; +3. `missing_keys_sample` 是否显示生产/消费 key 不一致; +4. `malformed_source_count` 是否说明 value 格式异常; +5. 候选是否在实时商品过滤阶段被全部删除; +6. LLM 是否错误地把低置信画像当成硬约束。 + +## 4. 排名与解释 + +### 4.1 路内融合 Swing、W2V、DeepWalk、向量相似和兴趣聚合的原始 score 量纲不同。直接相加会让数值范围大的算法支配结果,因此工具使用加权 Reciprocal Rank Fusion: @@ -92,7 +704,7 @@ candidate_score = sum(contribution) 每一路融合后把本次调用的最高分归一化为 1。这个 `score` 只能在同一次工具调用内比较,不是点击率或购买概率。 -### 3.2 两通道融合 +### 4.2 两通道融合 `build_recommendation_candidates` 默认使用: @@ -102,7 +714,7 @@ candidate_score = sum(contribution) 如果某一路没有候选,权重会在成功通道之间重新归一化,避免可用结果被无效通道无故压低。调用方可按实验配置调整两个权重,但不应根据单次对话随意改变离线算法内部权重。 -### 3.3 证据 +### 4.3 证据 候选示例: @@ -120,7 +732,7 @@ candidate_score = sum(contribution) }, { "type": "matched_dimension", - "dimension_key": "platform_category2:essaone_29", + "dimension_key": "platform_category2:essaone_5", "list_types": ["hot"] } ], @@ -139,9 +751,9 @@ candidate_score = sum(contribution) LLM 可以把 `reasons` 转成用户可理解的推荐依据,但不能把“相似/热门”虚构成商品属性。属性描述必须来自后续商品详情工具。 -## 4. 运行方式 +## 5. 运行方式 -### 4.1 生成维度字典 +### 5.1 生成维度字典 正常运行 `fetch_item_attributes.py` 时会额外生成: @@ -151,7 +763,7 @@ output/agent_dimension_catalog.json 它只包含分类、供应商、平台和客户端映射,不包含约 300 万商品名称,适合在线进程加载。该文件是生成数据,保持在 `.gitignore` 中并随离线任务更新。 -### 4.2 列出工具 schema +### 5.2 列出工具 schema ```bash cd offline_tasks @@ -160,7 +772,7 @@ python3 scripts/agent_recommendation_tools.py list-tools 输出可直接注册到支持 JSON Schema function tools 的 Agent 框架。 -### 4.3 配置 Redis +### 5.3 配置 Redis 工具不读取仓库中的明文连接配置。使用以下环境变量之一: @@ -180,21 +792,22 @@ RECOMMENDATION_DIMENSION_CATALOG 不要把密码写进 tool arguments、日志、文档或模型上下文。 -### 4.4 单次调用 +### 5.4 单次调用 + +下面是最小混合调用;逐工具参数及完整真实响应见第 3 节。 ```bash python3 scripts/agent_recommendation_tools.py call \ build_recommendation_candidates \ --arguments '{ - "seed_items":[{"item_id":"3385246","behavior":"click"}], + "seed_items":[{"item_id":"3891002","behavior":"purchase"}], "context":{"platform":"essaone","client_platform":"pc"}, - "interests":[{"dimension":"category_level2","value":"29","weight":2}], - "exclude_item_ids":["3385246"], - "top_k":30 + "interests":[{"dimension":"category_level2","value":"5","weight":2}], + "top_k":5 }' ``` -### 4.5 长驻 stdio +### 5.5 长驻 stdio ```bash python3 scripts/agent_recommendation_tools.py serve-stdio @@ -203,7 +816,7 @@ python3 scripts/agent_recommendation_tools.py serve-stdio 每行一个请求: ```json -{"id":"req-1","tool":"recall_similar_products","arguments":{"seed_items":[{"item_id":"3385246"}]}} +{"id":"req-1","tool":"recall_similar_products","arguments":{"seed_items":[{"item_id":"3891002"}]}} ``` 每行一个响应: @@ -214,7 +827,7 @@ python3 scripts/agent_recommendation_tools.py serve-stdio 这不是特定厂商协议;可由现有 Agent 网关包装成 MCP、HTTP 或框架原生 Tool。 -### 4.6 Python 集成 +### 5.6 Python 集成 ```python import redis @@ -239,7 +852,7 @@ result = tools.call_tool(tool_name, tool_arguments) 上述导入方式从仓库根目录运行;若在线项目只把 `offline_tasks/` 加入 `PYTHONPATH`,则改为从 `agent_tools` 导入。正式跨仓库复用时建议将该目录构建成内部 Python 包并锁定版本。 -## 5. 错误与诊断 +## 6. 错误与诊断 Tool 调用永远返回顶层 `ok`。错误结构: @@ -266,7 +879,7 @@ Tool 调用永远返回顶层 `ok`。错误结构: 这些字段用于日志和指标,不建议原样展示给最终用户。 -## 6. Agent 编排建议 +## 7. Agent 编排建议 1. 从画像中选择最近、高强度且能代表当前意图的 3 到 10 个种子,不要把全部历史灌给工具。 2. 对 LLM 推断出的兴趣保留置信度;低置信推断应降低 `weight`,硬约束不能只靠 weight 表达。 @@ -276,7 +889,7 @@ Tool 调用永远返回顶层 `ok`。错误结构: 6. 最终理由区分“画像依据”“协同证据”和“商品事实”,避免把统计相关性写成因果关系。 7. 无候选时读取 diagnostics,区分无种子、维度 ID 错、key 缺失、格式异常和实时过滤清空。 -## 7. 评估与上线 +## 8. 评估与上线 离线回放至少比较: @@ -294,7 +907,7 @@ Tool 调用永远返回顶层 `ok`。错误结构: 发布时把算法权重、通道权重和候选池大小纳入实验配置;工具 schema 与 Redis 契约版本应进入日志,便于归因和回滚。 -## 8. 后续扩展 +## 9. 后续扩展 按收益和依赖关系建议继续建设: diff --git a/offline_tasks/test_agent_recommendation_tools.py b/offline_tasks/test_agent_recommendation_tools.py index d1ca223..c5f9eb5 100644 --- a/offline_tasks/test_agent_recommendation_tools.py +++ b/offline_tasks/test_agent_recommendation_tools.py @@ -218,6 +218,29 @@ class RecommendationAgentToolsTest(unittest.TestCase): {'collaborative', 'dimension'}, ) + def test_hybrid_recall_excludes_seed_from_dimension_channel(self): + self.store.set( + 'interest:hot:platform:essaone', + '100:100,304:90,305:80', + ) + result = self.tools.build_recommendation_candidates( + seed_items=[{'item_id': '100'}], + context={'platform': 'essaone'}, + algorithms=['swing'], + list_types=['hot'], + top_k=10, + exclude_item_ids=[ + 'already-excluded-%s' % index for index in range(500) + ], + ) + self.assertNotIn('100', [item['item_id'] for item in result['items']]) + self.assertGreater( + result['diagnostics']['channel_diagnostics']['dimension'][ + 'excluded_occurrence_count' + ], + 0, + ) + def test_catalog_resolution_and_tool_dispatch(self): resolved = self.tools.call_tool( 'resolve_recommendation_dimension', -- libgit2 0.21.2