Commit b4f7574f55b4866bb029b67a836a35ef147ae2b6

Authored by tangwang
1 parent 62ec5f97

feat(agent): add collaborative recommendation toolset

背景与缘由:
智能导购需要把 LLM 从公共知识和用户画像中推导出的种子商品、分类与上下文,稳定地映射到现有协同索引。此前调用方必须理解多种 Redis key 和不一致的历史 value 格式,而且文档仍把当前 value 描述成 JSON、把 Session W2V 主 key 写成 w2v,并记录了过期的 TTL、品牌及全局兜底约定,容易造成线上空召回和错误解析。

主要实现:
- 新增 5 个框架无关的 JSON Schema tools,覆盖能力发现、维度解析、多算法 I2I 召回、画像维度召回和混合候选生成。
- 新增 Redis 与内存存储适配器,统一解析当前 item_id:score 文本,并只为迁移读取兼容历史 JSON value 和 item:similar:w2v key。
- 采用加权 RRF 融合不同量纲的 Swing、Session W2V、DeepWalk、内容及行为索引;混合召回默认按协同 0.65、维度 0.35 融合,并在通道缺失时重新归一化。
- 支持组合维度规划、单维度回退、排除列表、来源证据、诊断信息、CLI 与 JSONL stdio 服务。
- 在 fetch_item_attributes 中生成精简 Agent 维度字典,不复制大体量商品名称映射。

文档与示例修正:
- 以 load_index_to_redis.py 的实际行为为权威,统一 I2I 与兴趣索引 value 为 item_id:score,...,默认 TTL 为 60 天。
- 明确 Session W2V 当前 key 为 item:similar:session_w2v:*,w2v 仅是历史读取后备。
- 明确 global 是 list type 而非无条件 dimension,当前不会产出 interest:global:global;当前也没有品牌索引生产逻辑。
- 校正平台、客户端、国家和客户类型维度来源,标注 essaone 使用 buy_buyer_extend_option.code 的现有语义限制。
- 更新在线 key 清单、故障排查、详细设计、内容相似说明和 Redis 查询示例,并从触及的文档中移除真实凭据。

兼容性与运行边界:
保持 Python 3.6 兼容且不新增依赖。工具只负责高召回候选及证据,价格、库存、可售、地域和合规仍需由实时商品服务校验。本次没有连接或写入生产 Redis、数据库或 Elasticsearch。

验证:
- cd offline_tasks && python3 test_agent_recommendation_tools.py:18 项通过。
- Python 3.6 py_compile:全部变更 Python 文件通过。
- CLI 输出 5 个可序列化 tool schemas。
- 2026-08-22 实际 Swing 与 interest 产出样本分别成功解析 50 和 1000 个候选。
- git diff --cached --check:通过。
CLAUDE.md
... ... @@ -136,7 +136,7 @@ python3 offline_tasks/scripts/generate_session.py --lookback_days 730 --debug
136 136 cd offline_tasks/collaboration && bash run.sh
137 137  
138 138 # Load indices to Redis
139   -python3 offline_tasks/scripts/load_index_to_redis.py --redis-host localhost --redis-port 6379
  139 +python3 offline_tasks/scripts/load_index_to_redis.py --redis-host localhost --redis-port 6479
140 140 ```
141 141  
142 142 ### Algorithm Execution Order
... ... @@ -185,20 +185,22 @@ behavior_weights = {
185 185  
186 186 #### Database Configuration (`config.py`)
187 187 ```python
188   -# External database
  188 +# Redacted shape only. Legacy tasks still read offline_config.py; do not copy
  189 +# real credentials into documentation. New deployments should inject secrets.
189 190 DB_CONFIG = {
190   - 'host': 'selectdb-cn-wuf3vsokg05-public.selectdbfe.rds.aliyuncs.com',
  191 + 'host': 'your_db_host',
191 192 'port': '9030',
192   - 'database': 'datacenter',
193   - 'username': 'readonly',
194   - 'password': 'essa1234'
  193 + 'database': 'your_database',
  194 + 'username': 'your_username',
  195 + 'password': 'from_secret_store'
195 196 }
196 197  
197 198 # Redis for online serving
198 199 REDIS_CONFIG = {
199 200 'host': 'localhost',
200   - 'port': 6379,
201   - 'cache_expire_days': 180
  201 + 'port': 6479,
  202 + 'db': 0,
  203 + 'expire_days': 60
202 204 }
203 205 ```
204 206  
... ... @@ -231,7 +233,7 @@ REDIS_CONFIG = {
231 233 **Multi-dimensional Support**:
232 234 - **7 single dimensions**: platform, client_platform, supplier, category_level1-4
233 235 - **4 combined dimensions**: platform_client, platform_category2/3, client_category2
234   -- **3 list types**: hot (popular), cart (cart additions), new (recent), global (overall)
  236 +- **4 list types**: hot (popular), cart (cart additions), new (recent), global (overall)
235 237  
236 238 ## 📊 Data Pipeline
237 239  
... ... @@ -246,11 +248,11 @@ REDIS_CONFIG = {
246 248 item_id \t similar_id1:score1,similar_id2:score2,...
247 249  
248 250 # Interest Aggregation
249   -dimension:value \t item_id1,item_id2,item_id3,...
  251 +dimension:value \t item_id1:score1,item_id2:score2,...
250 252  
251 253 # Redis Keys
252 254 item:similar:swing_cpp:12345
253   -interest:hot:platform:pc
  255 +interest:hot:platform:essaone
254 256 ```
255 257  
256 258 ### Storage Architecture
... ...
offline_tasks/README.md
... ... @@ -220,6 +220,18 @@ tail -f logs/run_all_$(date +%Y%m%d).log
220 220 - **Hot**: `../hot/` - 热门推荐
221 221 - **Frontend**: `../frontend/` - 推荐接口
222 222  
  223 +## 🤖 智能导购 Agent 工具
  224 +
  225 +`agent_tools/` 将现有 I2I 和兴趣维度索引封装为 5 个可注册的 JSON Schema tools,支持多算法 RRF、组合维度回退、候选排除和来源证据。
  226 +
  227 +```bash
  228 +cd offline_tasks
  229 +python3 scripts/agent_recommendation_tools.py list-tools
  230 +python3 test_agent_recommendation_tools.py
  231 +```
  232 +
  233 +接入方式、环境变量和完整工具契约见 [doc/智能导购Agent工具集.md](./doc/智能导购Agent工具集.md)。
  234 +
223 235 ## 📞 更多信息
224 236  
225 237 - **完整文档**: [doc/README.md](./doc/README.md)
... ...
offline_tasks/agent_tools/__init__.py 0 → 100644
... ... @@ -0,0 +1,14 @@
  1 +"""Agent-facing recommendation recall tools."""
  2 +
  3 +from .catalog import DimensionCatalog, save_agent_dimension_catalog
  4 +from .service import RecommendationAgentTools, ToolInputError
  5 +from .store import MemoryIndexStore, RedisIndexStore
  6 +
  7 +__all__ = [
  8 + 'DimensionCatalog',
  9 + 'MemoryIndexStore',
  10 + 'RecommendationAgentTools',
  11 + 'RedisIndexStore',
  12 + 'ToolInputError',
  13 + 'save_agent_dimension_catalog',
  14 +]
... ...
offline_tasks/agent_tools/catalog.py 0 → 100644
... ... @@ -0,0 +1,114 @@
  1 +"""Small searchable catalog for turning names into index dimension values."""
  2 +
  3 +import json
  4 +import os
  5 +from datetime import datetime
  6 +
  7 +
  8 +_CATALOG_DIMENSION_ALIASES = {
  9 + 'category': 'category',
  10 + 'category_level1': 'category',
  11 + 'category_level2': 'category',
  12 + 'category_level3': 'category',
  13 + 'category_level4': 'category',
  14 + 'supplier': 'supplier',
  15 + 'platform': 'platform',
  16 + 'client_platform': 'client_platform',
  17 + 'country_code': 'country_code',
  18 + 'customer_type': 'customer_type',
  19 +}
  20 +
  21 +
  22 +def save_agent_dimension_catalog(mappings, output_dir, generated_at=None):
  23 + """Write the small Agent catalog without copying the item name mapping."""
  24 + os.makedirs(output_dir, exist_ok=True)
  25 + dimensions = {
  26 + 'category': mappings.get('category', {}),
  27 + 'supplier': mappings.get('supplier', {}),
  28 + 'platform': {
  29 + 'essa': 'essa',
  30 + 'essaone': 'essaone',
  31 + 'essabuy': 'essabuy',
  32 + },
  33 + 'client_platform': {
  34 + 'pc': 'PC',
  35 + },
  36 + }
  37 + catalog = {
  38 + 'schema_version': 1,
  39 + 'generated_at': generated_at or datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  40 + 'dimensions': dimensions,
  41 + }
  42 + catalog_file = os.path.join(output_dir, 'agent_dimension_catalog.json')
  43 + temporary_file = catalog_file + '.tmp'
  44 + with open(temporary_file, 'w', encoding='utf-8') as output_file:
  45 + json.dump(catalog, output_file, ensure_ascii=False, separators=(',', ':'))
  46 + os.replace(temporary_file, catalog_file)
  47 + return catalog_file
  48 +
  49 +
  50 +class DimensionCatalog(object):
  51 + """Resolve human-readable category or supplier names without a database call."""
  52 +
  53 + def __init__(self, dimensions=None, metadata=None):
  54 + self.dimensions = {}
  55 + for name, values in (dimensions or {}).items():
  56 + if isinstance(values, dict):
  57 + self.dimensions[name] = {
  58 + str(value): str(label)
  59 + for value, label in values.items()
  60 + if value is not None and label is not None
  61 + }
  62 + self.metadata = dict(metadata or {})
  63 +
  64 + @classmethod
  65 + def from_file(cls, path):
  66 + with open(path, 'r', encoding='utf-8') as catalog_file:
  67 + payload = json.load(catalog_file)
  68 + dimensions = payload.get('dimensions', {})
  69 + metadata = {
  70 + key: value for key, value in payload.items() if key != 'dimensions'
  71 + }
  72 + return cls(dimensions=dimensions, metadata=metadata)
  73 +
  74 + @property
  75 + def available(self):
  76 + return bool(self.dimensions)
  77 +
  78 + def resolve(self, dimension, query, limit=10):
  79 + catalog_dimension = _CATALOG_DIMENSION_ALIASES.get(dimension)
  80 + values = self.dimensions.get(catalog_dimension, {})
  81 + query_text = str(query or '').strip()
  82 + if not query_text or not values:
  83 + return []
  84 +
  85 + folded_query = query_text.casefold()
  86 + query_tokens = [token for token in folded_query.split() if token]
  87 + matches = []
  88 + for value, label in values.items():
  89 + folded_value = value.casefold()
  90 + folded_label = label.casefold()
  91 + match_type = None
  92 + score = 0.0
  93 + if folded_query == folded_value:
  94 + match_type, score = 'exact_value', 1.0
  95 + elif folded_query == folded_label:
  96 + match_type, score = 'exact_label', 0.99
  97 + elif folded_label.startswith(folded_query):
  98 + match_type, score = 'label_prefix', 0.90
  99 + elif folded_query in folded_label:
  100 + match_type, score = 'label_contains', 0.82
  101 + elif query_tokens and all(token in folded_label for token in query_tokens):
  102 + match_type, score = 'all_tokens', 0.75
  103 + if match_type:
  104 + matches.append({
  105 + 'value': value,
  106 + 'label': label,
  107 + 'match_type': match_type,
  108 + 'score': score,
  109 + })
  110 +
  111 + matches.sort(key=lambda match: (
  112 + -match['score'], len(match['label']), match['value']
  113 + ))
  114 + return matches[:limit]
... ...
offline_tasks/agent_tools/cli.py 0 → 100644
... ... @@ -0,0 +1,177 @@
  1 +"""Command-line and JSON-lines entry points for the agent toolset."""
  2 +
  3 +import argparse
  4 +import json
  5 +import os
  6 +import sys
  7 +
  8 +from .catalog import DimensionCatalog
  9 +from .service import RecommendationAgentTools
  10 +from .store import MemoryIndexStore, RedisIndexStore
  11 +
  12 +
  13 +DEFAULT_CATALOG_PATH = os.path.join(
  14 + os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  15 + 'output',
  16 + 'agent_dimension_catalog.json',
  17 +)
  18 +
  19 +
  20 +def _load_catalog(path):
  21 + if path and os.path.exists(path):
  22 + return DimensionCatalog.from_file(path)
  23 + return DimensionCatalog()
  24 +
  25 +
  26 +def _build_redis_store(args):
  27 + try:
  28 + import redis
  29 + except ImportError:
  30 + raise RuntimeError('redis-py is required for Redis-backed tool calls')
  31 +
  32 + redis_url = os.environ.get('RECOMMENDATION_REDIS_URL')
  33 + if redis_url:
  34 + client = redis.Redis.from_url(
  35 + redis_url,
  36 + decode_responses=True,
  37 + socket_connect_timeout=args.redis_timeout,
  38 + socket_timeout=args.redis_timeout,
  39 + )
  40 + else:
  41 + client = redis.Redis(
  42 + host=os.environ.get('RECOMMENDATION_REDIS_HOST', 'localhost'),
  43 + port=int(os.environ.get('RECOMMENDATION_REDIS_PORT', '6479')),
  44 + db=int(os.environ.get('RECOMMENDATION_REDIS_DB', '0')),
  45 + password=os.environ.get('RECOMMENDATION_REDIS_PASSWORD'),
  46 + decode_responses=True,
  47 + socket_connect_timeout=args.redis_timeout,
  48 + socket_timeout=args.redis_timeout,
  49 + )
  50 + return RedisIndexStore(client)
  51 +
  52 +
  53 +def _build_service(args, use_redis=True):
  54 + catalog_path = args.catalog or os.environ.get(
  55 + 'RECOMMENDATION_DIMENSION_CATALOG', DEFAULT_CATALOG_PATH
  56 + )
  57 + catalog = _load_catalog(catalog_path)
  58 + store = _build_redis_store(args) if use_redis else MemoryIndexStore()
  59 + return RecommendationAgentTools(store, dimension_catalog=catalog)
  60 +
  61 +
  62 +def _write_json(payload, compact=False):
  63 + if compact:
  64 + serialized = json.dumps(payload, ensure_ascii=False, separators=(',', ':'))
  65 + else:
  66 + serialized = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True)
  67 + sys.stdout.write(serialized + '\n')
  68 + sys.stdout.flush()
  69 +
  70 +
  71 +def _read_arguments(raw_arguments):
  72 + if raw_arguments == '-':
  73 + raw_arguments = sys.stdin.read()
  74 + try:
  75 + arguments = json.loads(raw_arguments)
  76 + except (TypeError, ValueError) as error:
  77 + raise ValueError('arguments must be valid JSON: %s' % error)
  78 + if not isinstance(arguments, dict):
  79 + raise ValueError('arguments must decode to a JSON object')
  80 + return arguments
  81 +
  82 +
  83 +def _serve_stdio(service):
  84 + for line in sys.stdin:
  85 + line = line.strip()
  86 + if not line:
  87 + continue
  88 + request_id = None
  89 + try:
  90 + request = json.loads(line)
  91 + if not isinstance(request, dict):
  92 + raise ValueError('request must be a JSON object')
  93 + request_id = request.get('id')
  94 + tool_name = request.get('tool', request.get('name'))
  95 + if not tool_name:
  96 + raise ValueError('request requires tool or name')
  97 + result = service.call_tool(tool_name, request.get('arguments', {}))
  98 + response = {'id': request_id, 'result': result}
  99 + except Exception as error:
  100 + response = {
  101 + 'id': request_id,
  102 + 'result': {
  103 + 'ok': False,
  104 + 'error': {
  105 + 'code': 'invalid_request',
  106 + 'message': str(error),
  107 + 'retryable': False,
  108 + },
  109 + },
  110 + }
  111 + _write_json(response, compact=True)
  112 + return 0
  113 +
  114 +
  115 +def build_parser():
  116 + parser = argparse.ArgumentParser(
  117 + description='Agent-facing tools over the offline recommendation indices'
  118 + )
  119 + parser.add_argument(
  120 + '--catalog', default=None,
  121 + help='Path to agent_dimension_catalog.json',
  122 + )
  123 + parser.add_argument(
  124 + '--redis-timeout', type=float, default=1.5,
  125 + help='Redis connect and read timeout in seconds (default: 1.5)',
  126 + )
  127 + subparsers = parser.add_subparsers(dest='command')
  128 +
  129 + list_parser = subparsers.add_parser(
  130 + 'list-tools', help='Print function-calling tool definitions'
  131 + )
  132 + list_parser.add_argument('--compact', action='store_true')
  133 +
  134 + call_parser = subparsers.add_parser('call', help='Call one tool')
  135 + call_parser.add_argument('tool_name')
  136 + call_parser.add_argument(
  137 + '--arguments', default='{}',
  138 + help='JSON object, or - to read JSON from stdin',
  139 + )
  140 + call_parser.add_argument('--compact', action='store_true')
  141 +
  142 + subparsers.add_parser(
  143 + 'serve-stdio',
  144 + help='Read one {id, tool, arguments} JSON request per line',
  145 + )
  146 + return parser
  147 +
  148 +
  149 +def main(argv=None):
  150 + parser = build_parser()
  151 + args = parser.parse_args(argv)
  152 + if not args.command:
  153 + parser.print_help()
  154 + return 2
  155 +
  156 + if args.command == 'list-tools':
  157 + service = _build_service(args, use_redis=False)
  158 + _write_json(service.tool_definitions(), compact=args.compact)
  159 + return 0
  160 +
  161 +
  162 + service = _build_service(args, use_redis=True)
  163 + if args.command == 'call':
  164 + try:
  165 + arguments = _read_arguments(args.arguments)
  166 + except ValueError as error:
  167 + parser.error(str(error))
  168 + result = service.call_tool(args.tool_name, arguments)
  169 + _write_json(result, compact=args.compact)
  170 + return 0 if result.get('ok') else 1
  171 + if args.command == 'serve-stdio':
  172 + return _serve_stdio(service)
  173 + return 2
  174 +
  175 +
  176 +if __name__ == '__main__':
  177 + sys.exit(main())
... ...
offline_tasks/agent_tools/parsing.py 0 → 100644
... ... @@ -0,0 +1,124 @@
  1 +"""Compatibility parsing for recommendation index values."""
  2 +
  3 +import json
  4 +import math
  5 +import re
  6 +
  7 +
  8 +_INTEGER_FLOAT_RE = re.compile(r'^([+-]?\d+)\.0+$')
  9 +
  10 +
  11 +def normalize_identifier(value):
  12 + """Return a stable string representation for an item or dimension ID."""
  13 + if value is None or isinstance(value, bool):
  14 + return None
  15 + if isinstance(value, int):
  16 + return str(value)
  17 + if isinstance(value, float):
  18 + if not math.isfinite(value):
  19 + return None
  20 + if value.is_integer():
  21 + return str(int(value))
  22 + return str(value)
  23 +
  24 + text = str(value).strip()
  25 + if not text or len(text) > 256:
  26 + return None
  27 + if any(char in text for char in ('\x00', '\r', '\n', '\t')):
  28 + return None
  29 + integer_match = _INTEGER_FLOAT_RE.match(text)
  30 + if integer_match:
  31 + return integer_match.group(1)
  32 + return text
  33 +
  34 +
  35 +def _parse_score(value):
  36 + if value is None or isinstance(value, bool):
  37 + return None
  38 + try:
  39 + score = float(value)
  40 + except (TypeError, ValueError, OverflowError):
  41 + return None
  42 + if not math.isfinite(score):
  43 + return None
  44 + return score
  45 +
  46 +
  47 +def _append_result(results, seen, item_id, score=None):
  48 + item_id = normalize_identifier(item_id)
  49 + if item_id is None or item_id in seen:
  50 + return
  51 + seen.add(item_id)
  52 + results.append((item_id, _parse_score(score)))
  53 +
  54 +
  55 +def _parse_json_value(parsed, results, seen):
  56 + if isinstance(parsed, dict):
  57 + for item_id, score in parsed.items():
  58 + _append_result(results, seen, item_id, score)
  59 + return True
  60 +
  61 + if not isinstance(parsed, list):
  62 + return False
  63 +
  64 + for entry in parsed:
  65 + if isinstance(entry, dict):
  66 + item_id = entry.get('item_id', entry.get('id'))
  67 + _append_result(results, seen, item_id, entry.get('score'))
  68 + elif isinstance(entry, (list, tuple)):
  69 + if entry:
  70 + score = entry[1] if len(entry) > 1 else None
  71 + _append_result(results, seen, entry[0], score)
  72 + else:
  73 + _append_result(results, seen, entry)
  74 + return True
  75 +
  76 +
  77 +def parse_ranked_items(value):
  78 + """Parse current and historical Redis value formats.
  79 +
  80 + Supported forms include ``id:score,id:score``, JSON pairs, JSON objects,
  81 + plain JSON ID lists, and a JSON-encoded legacy string.
  82 + """
  83 + if value is None:
  84 + return []
  85 + if isinstance(value, bytes):
  86 + try:
  87 + value = value.decode('utf-8')
  88 + except UnicodeDecodeError:
  89 + return []
  90 +
  91 + if isinstance(value, (list, dict)):
  92 + results = []
  93 + _parse_json_value(value, results, set())
  94 + return results
  95 +
  96 + text = str(value).strip()
  97 + if not text:
  98 + return []
  99 +
  100 + results = []
  101 + seen = set()
  102 + if text[0] in '[{"':
  103 + try:
  104 + parsed = json.loads(text)
  105 + except (TypeError, ValueError):
  106 + parsed = None
  107 + if isinstance(parsed, str) and parsed != text:
  108 + return parse_ranked_items(parsed)
  109 + if _parse_json_value(parsed, results, seen):
  110 + return results
  111 +
  112 + for token in text.split(','):
  113 + token = token.strip()
  114 + if not token:
  115 + continue
  116 + if ':' in token:
  117 + item_id, score = token.rsplit(':', 1)
  118 + parsed_score = _parse_score(score)
  119 + if parsed_score is None:
  120 + continue
  121 + _append_result(results, seen, item_id, parsed_score)
  122 + else:
  123 + _append_result(results, seen, token)
  124 + return results
... ...
offline_tasks/agent_tools/schemas.py 0 → 100644
... ... @@ -0,0 +1,259 @@
  1 +"""JSON Schema definitions for registering the recommendation tools."""
  2 +
  3 +import copy
  4 +
  5 +
  6 +ALGORITHM_NAMES = [
  7 + 'swing_cpp',
  8 + 'swing',
  9 + 'session_w2v',
  10 + 'deepwalk',
  11 + 'content_name',
  12 + 'content_pic',
  13 + 'item_behavior',
  14 +]
  15 +
  16 +DIMENSION_NAMES = [
  17 + 'platform',
  18 + 'client_platform',
  19 + 'country_code',
  20 + 'customer_type',
  21 + 'supplier',
  22 + 'category_level1',
  23 + 'category_level2',
  24 + 'category_level3',
  25 + 'category_level4',
  26 +]
  27 +
  28 +LIST_TYPE_NAMES = ['hot', 'cart', 'new', 'global']
  29 +
  30 +
  31 +SEED_ITEMS_SCHEMA = {
  32 + 'type': 'array',
  33 + 'minItems': 1,
  34 + 'maxItems': 20,
  35 + 'items': {
  36 + 'type': 'object',
  37 + 'additionalProperties': False,
  38 + 'properties': {
  39 + 'item_id': {
  40 + 'description': '商品 SKU ID,建议以字符串传递。',
  41 + 'oneOf': [{'type': 'string'}, {'type': 'integer'}],
  42 + },
  43 + 'weight': {
  44 + 'type': 'number',
  45 + 'exclusiveMinimum': 0,
  46 + 'maximum': 10,
  47 + 'description': '偏好强度;省略时按 behavior 推导。',
  48 + },
  49 + 'behavior': {
  50 + 'type': 'string',
  51 + 'enum': [
  52 + 'click', 'view', 'addToPool', 'addToCart',
  53 + 'contactFactory', 'purchase',
  54 + ],
  55 + },
  56 + 'reason': {
  57 + 'type': 'string',
  58 + 'maxLength': 200,
  59 + 'description': '画像中选择该种子商品的简短依据。',
  60 + },
  61 + },
  62 + 'required': ['item_id'],
  63 + },
  64 +}
  65 +
  66 +
  67 +CONTEXT_SCHEMA = {
  68 + 'type': 'object',
  69 + 'additionalProperties': False,
  70 + 'properties': {
  71 + 'platform': {'type': 'string'},
  72 + 'client_platform': {'type': 'string'},
  73 + 'country_code': {
  74 + 'oneOf': [{'type': 'string'}, {'type': 'integer'}],
  75 + },
  76 + 'customer_type': {'type': 'string'},
  77 + },
  78 + 'description': '当前请求上下文;组合维度会由工具自动规划。',
  79 +}
  80 +
  81 +
  82 +INTERESTS_SCHEMA = {
  83 + 'type': 'array',
  84 + 'maxItems': 30,
  85 + 'items': {
  86 + 'type': 'object',
  87 + 'additionalProperties': False,
  88 + 'properties': {
  89 + 'dimension': {'type': 'string', 'enum': DIMENSION_NAMES},
  90 + 'value': {
  91 + 'description': '内部维度值;名称应先通过维度解析工具转换。',
  92 + 'oneOf': [{'type': 'string'}, {'type': 'integer'}],
  93 + },
  94 + 'weight': {
  95 + 'type': 'number',
  96 + 'exclusiveMinimum': 0,
  97 + 'maximum': 10,
  98 + 'default': 1,
  99 + },
  100 + 'reason': {'type': 'string', 'maxLength': 200},
  101 + },
  102 + 'required': ['dimension', 'value'],
  103 + },
  104 +}
  105 +
  106 +
  107 +def _common_recall_properties():
  108 + return {
  109 + 'top_k': {
  110 + 'type': 'integer', 'minimum': 1, 'maximum': 100, 'default': 50,
  111 + },
  112 + 'exclude_item_ids': {
  113 + 'type': 'array',
  114 + 'maxItems': 500,
  115 + 'items': {'oneOf': [{'type': 'string'}, {'type': 'integer'}]},
  116 + 'description': '已曝光、已购买、不可售等需排除的商品 ID。',
  117 + },
  118 + }
  119 +
  120 +
  121 +def _similar_properties():
  122 + properties = _common_recall_properties()
  123 + properties.update({
  124 + 'seed_items': copy.deepcopy(SEED_ITEMS_SCHEMA),
  125 + 'algorithms': {
  126 + 'type': 'array',
  127 + 'uniqueItems': True,
  128 + 'items': {'type': 'string', 'enum': ALGORITHM_NAMES},
  129 + },
  130 + 'per_seed_k': {
  131 + 'type': 'integer', 'minimum': 1, 'maximum': 200, 'default': 50,
  132 + },
  133 + })
  134 + return properties
  135 +
  136 +
  137 +def _dimension_properties():
  138 + properties = _common_recall_properties()
  139 + properties.update({
  140 + 'context': copy.deepcopy(CONTEXT_SCHEMA),
  141 + 'interests': copy.deepcopy(INTERESTS_SCHEMA),
  142 + 'list_types': {
  143 + 'type': 'array',
  144 + 'minItems': 1,
  145 + 'uniqueItems': True,
  146 + 'items': {'type': 'string', 'enum': LIST_TYPE_NAMES},
  147 + },
  148 + 'per_source_k': {
  149 + 'type': 'integer', 'minimum': 1, 'maximum': 500, 'default': 100,
  150 + },
  151 + })
  152 + return properties
  153 +
  154 +
  155 +def get_tool_definitions():
  156 + """Return framework-neutral function tool definitions."""
  157 + hybrid_properties = _similar_properties()
  158 + hybrid_properties.update(_dimension_properties())
  159 + hybrid_properties.update({
  160 + 'collaborative_weight': {
  161 + 'type': 'number', 'minimum': 0, 'maximum': 1, 'default': 0.65,
  162 + },
  163 + 'dimension_weight': {
  164 + 'type': 'number', 'minimum': 0, 'maximum': 1, 'default': 0.35,
  165 + },
  166 + })
  167 + hybrid_properties['seed_items']['minItems'] = 0
  168 +
  169 + return [
  170 + {
  171 + 'type': 'function',
  172 + 'function': {
  173 + 'name': 'recommendation_capabilities',
  174 + 'description': (
  175 + '查看可用协同算法、画像维度、索引语义和推荐工具调用顺序。'
  176 + '首次接入或不确定参数时调用。'
  177 + ),
  178 + 'parameters': {
  179 + 'type': 'object', 'properties': {},
  180 + 'additionalProperties': False,
  181 + },
  182 + },
  183 + },
  184 + {
  185 + 'type': 'function',
  186 + 'function': {
  187 + 'name': 'resolve_recommendation_dimension',
  188 + 'description': (
  189 + '把分类、供应商、平台等自然语言名称解析为离线索引使用的内部维度值。'
  190 + '只返回候选映射,不做商品召回。'
  191 + ),
  192 + 'parameters': {
  193 + 'type': 'object',
  194 + 'additionalProperties': False,
  195 + 'properties': {
  196 + 'dimension': {'type': 'string', 'enum': DIMENSION_NAMES},
  197 + 'query': {'type': 'string', 'minLength': 1, 'maxLength': 200},
  198 + 'limit': {
  199 + 'type': 'integer', 'minimum': 1, 'maximum': 20,
  200 + 'default': 10,
  201 + },
  202 + },
  203 + 'required': ['dimension', 'query'],
  204 + },
  205 + },
  206 + },
  207 + {
  208 + 'type': 'function',
  209 + 'function': {
  210 + 'name': 'recall_similar_products',
  211 + 'description': (
  212 + '基于用户明确感兴趣的种子商品,从 Swing、序列、图和内容索引中'
  213 + '召回相似商品,并返回可追溯的多算法融合证据。'
  214 + ),
  215 + 'parameters': {
  216 + 'type': 'object',
  217 + 'additionalProperties': False,
  218 + 'properties': _similar_properties(),
  219 + 'required': ['seed_items'],
  220 + },
  221 + },
  222 + },
  223 + {
  224 + 'type': 'function',
  225 + 'function': {
  226 + 'name': 'recall_products_by_dimensions',
  227 + 'description': (
  228 + '根据平台、国家、客户类型、分类、供应商等画像维度召回热门、'
  229 + '高加购、新品和全局商品;自动使用组合维度并回退到单维度。'
  230 + ),
  231 + 'parameters': {
  232 + 'type': 'object',
  233 + 'additionalProperties': False,
  234 + 'properties': _dimension_properties(),
  235 + 'anyOf': [{'required': ['context']}, {'required': ['interests']}],
  236 + },
  237 + },
  238 + },
  239 + {
  240 + 'type': 'function',
  241 + 'function': {
  242 + 'name': 'build_recommendation_candidates',
  243 + 'description': (
  244 + '为智能导购生成高召回候选池:融合种子商品协同召回与画像维度召回,'
  245 + '去重、排除已知商品,并保留供 LLM 挑选的来源证据。'
  246 + ),
  247 + 'parameters': {
  248 + 'type': 'object',
  249 + 'additionalProperties': False,
  250 + 'properties': hybrid_properties,
  251 + 'anyOf': [
  252 + {'required': ['seed_items']},
  253 + {'required': ['context']},
  254 + {'required': ['interests']},
  255 + ],
  256 + },
  257 + },
  258 + },
  259 + ]
... ...
offline_tasks/agent_tools/service.py 0 → 100644
... ... @@ -0,0 +1,981 @@
  1 +"""Recommendation recall and fusion service exposed as LLM-callable tools."""
  2 +
  3 +import math
  4 +
  5 +from .catalog import DimensionCatalog
  6 +from .parsing import normalize_identifier, parse_ranked_items
  7 +from .schemas import (
  8 + ALGORITHM_NAMES, DIMENSION_NAMES, LIST_TYPE_NAMES, get_tool_definitions,
  9 +)
  10 +
  11 +
  12 +TOOLSET_VERSION = '1.0.0'
  13 +MAX_EVIDENCE_PER_ITEM = 8
  14 +MAX_DIMENSION_PLANS = 120
  15 +
  16 +BEHAVIOR_WEIGHTS = {
  17 + 'click': 1.0,
  18 + 'view': 1.0,
  19 + 'addToPool': 2.0,
  20 + 'addToCart': 3.0,
  21 + 'contactFactory': 5.0,
  22 + 'purchase': 10.0,
  23 +}
  24 +
  25 +ALGORITHMS = {
  26 + 'swing_cpp': {
  27 + 'prefixes': ['item:similar:swing_cpp'],
  28 + 'weight': 1.00,
  29 + 'signal': 'high-scale co-interaction similarity',
  30 + },
  31 + 'swing': {
  32 + 'prefixes': ['item:similar:swing'],
  33 + 'weight': 0.95,
  34 + 'signal': 'time-aware co-interaction similarity',
  35 + },
  36 + 'session_w2v': {
  37 + 'prefixes': ['item:similar:session_w2v', 'item:similar:w2v'],
  38 + 'weight': 0.90,
  39 + 'signal': 'session sequence similarity',
  40 + },
  41 + 'deepwalk': {
  42 + 'prefixes': ['item:similar:deepwalk'],
  43 + 'weight': 0.85,
  44 + 'signal': 'behavior graph proximity',
  45 + },
  46 + 'content_name': {
  47 + 'prefixes': ['item:similar:content_name'],
  48 + 'weight': 0.70,
  49 + 'signal': 'name embedding similarity',
  50 + },
  51 + 'content_pic': {
  52 + 'prefixes': ['item:similar:content_pic'],
  53 + 'weight': 0.65,
  54 + 'signal': 'image embedding similarity',
  55 + },
  56 + 'item_behavior': {
  57 + 'prefixes': ['item:similar:item_behavior'],
  58 + 'weight': 1.00,
  59 + 'signal': 'item behavior similarity',
  60 + },
  61 +}
  62 +
  63 +LIST_TYPE_WEIGHTS = {
  64 + 'hot': 1.00,
  65 + 'cart': 1.10,
  66 + 'new': 0.85,
  67 + 'global': 0.75,
  68 +}
  69 +
  70 +DIMENSION_ALIASES = {
  71 + 'platform': 'platform',
  72 + 'client': 'client_platform',
  73 + 'client_platform': 'client_platform',
  74 + 'country': 'country_code',
  75 + 'country_code': 'country_code',
  76 + 'customer_type': 'customer_type',
  77 + 'supplier': 'supplier',
  78 + 'supplier_id': 'supplier',
  79 + 'category_level1': 'category_level1',
  80 + 'category_level1_id': 'category_level1',
  81 + 'category_level2': 'category_level2',
  82 + 'category_level2_id': 'category_level2',
  83 + 'category_level3': 'category_level3',
  84 + 'category_level3_id': 'category_level3',
  85 + 'category_level4': 'category_level4',
  86 + 'category_level4_id': 'category_level4',
  87 +}
  88 +
  89 +DIRECT_DIMENSIONS = {
  90 + 'platform', 'client_platform', 'supplier',
  91 + 'category_level1', 'category_level2',
  92 + 'category_level3', 'category_level4',
  93 +}
  94 +
  95 +
  96 +class ToolInputError(ValueError):
  97 + """Raised when a tool call is well-formed JSON but semantically invalid."""
  98 +
  99 +
  100 +def _bounded_integer(value, name, default, minimum, maximum):
  101 + if value is None:
  102 + value = default
  103 + if isinstance(value, bool):
  104 + raise ToolInputError('%s must be an integer' % name)
  105 + try:
  106 + parsed = int(value)
  107 + except (TypeError, ValueError, OverflowError):
  108 + raise ToolInputError('%s must be an integer' % name)
  109 + if parsed < minimum or parsed > maximum:
  110 + raise ToolInputError(
  111 + '%s must be between %s and %s' % (name, minimum, maximum)
  112 + )
  113 + return parsed
  114 +
  115 +
  116 +def _bounded_weight(value, name, default=1.0, allow_zero=False, maximum=10.0):
  117 + if value is None:
  118 + return default
  119 + if isinstance(value, bool):
  120 + raise ToolInputError('%s must be a number' % name)
  121 + try:
  122 + parsed = float(value)
  123 + except (TypeError, ValueError, OverflowError):
  124 + raise ToolInputError('%s must be a number' % name)
  125 + minimum = 0.0 if allow_zero else 0.000001
  126 + if not math.isfinite(parsed) or parsed < minimum or parsed > maximum:
  127 + qualifier = 'non-negative' if allow_zero else 'positive'
  128 + raise ToolInputError('%s must be a %s number no greater than %s' % (
  129 + name, qualifier, maximum,
  130 + ))
  131 + return parsed
  132 +
  133 +
  134 +def _safe_text(value, name, lower=False, upper=False, max_length=200,
  135 + allow_separators=False):
  136 + if value is None:
  137 + return None
  138 + text = str(value).strip()
  139 + if not text:
  140 + raise ToolInputError('%s must not be empty' % name)
  141 + if len(text) > max_length:
  142 + raise ToolInputError('%s is too long' % name)
  143 + forbidden = ('\x00', '\r', '\n', '\t')
  144 + if not allow_separators:
  145 + forbidden += (':', ';')
  146 + if any(char in text for char in forbidden):
  147 + raise ToolInputError('%s contains an unsupported separator' % name)
  148 + if lower:
  149 + text = text.lower()
  150 + if upper:
  151 + text = text.upper()
  152 + return text
  153 +
  154 +
  155 +def _unique_strings(values, name, maximum=500):
  156 + if values is None:
  157 + return []
  158 + if not isinstance(values, (list, tuple)):
  159 + raise ToolInputError('%s must be an array' % name)
  160 + if len(values) > maximum:
  161 + raise ToolInputError('%s contains too many values' % name)
  162 + result = []
  163 + seen = set()
  164 + for value in values:
  165 + normalized = normalize_identifier(value)
  166 + if normalized is None:
  167 + raise ToolInputError('%s contains an invalid identifier' % name)
  168 + if normalized not in seen:
  169 + result.append(normalized)
  170 + seen.add(normalized)
  171 + return result
  172 +
  173 +
  174 +def _unique_in_order(values):
  175 + result = []
  176 + seen = set()
  177 + for value in values:
  178 + if value not in seen:
  179 + result.append(value)
  180 + seen.add(value)
  181 + return result
  182 +
  183 +
  184 +class RecommendationAgentTools(object):
  185 + """Framework-neutral tools backed by the repository's Redis indices."""
  186 +
  187 + def __init__(self, index_store, dimension_catalog=None, rrf_k=60):
  188 + if index_store is None:
  189 + raise ValueError('index_store is required')
  190 + self.index_store = index_store
  191 + self.dimension_catalog = dimension_catalog or DimensionCatalog()
  192 + self.rrf_k = _bounded_integer(rrf_k, 'rrf_k', 60, 1, 1000)
  193 +
  194 + def tool_definitions(self):
  195 + return get_tool_definitions()
  196 +
  197 + def call_tool(self, name, arguments=None):
  198 + handlers = {
  199 + 'recommendation_capabilities': self.recommendation_capabilities,
  200 + 'resolve_recommendation_dimension': self.resolve_recommendation_dimension,
  201 + 'recall_similar_products': self.recall_similar_products,
  202 + 'recall_products_by_dimensions': self.recall_products_by_dimensions,
  203 + 'build_recommendation_candidates': self.build_recommendation_candidates,
  204 + }
  205 + handler = handlers.get(name)
  206 + if handler is None:
  207 + return self._error('unknown_tool', 'Unknown tool: %s' % name)
  208 + if arguments is None:
  209 + arguments = {}
  210 + if not isinstance(arguments, dict):
  211 + return self._error('invalid_arguments', 'Tool arguments must be an object')
  212 + try:
  213 + return handler(**arguments)
  214 + except ToolInputError as error:
  215 + return self._error('invalid_arguments', str(error))
  216 + except TypeError as error:
  217 + return self._error('invalid_arguments', str(error))
  218 + except Exception as error:
  219 + return self._error(
  220 + 'index_unavailable',
  221 + 'Recommendation index query failed (%s)' % error.__class__.__name__,
  222 + retryable=True,
  223 + )
  224 +
  225 + @staticmethod
  226 + def _error(code, message, retryable=False):
  227 + return {
  228 + 'ok': False,
  229 + 'error': {
  230 + 'code': code,
  231 + 'message': message,
  232 + 'retryable': bool(retryable),
  233 + },
  234 + }
  235 +
  236 + def recommendation_capabilities(self):
  237 + algorithms = []
  238 + for name in ALGORITHM_NAMES:
  239 + config = ALGORITHMS[name]
  240 + algorithms.append({
  241 + 'name': name,
  242 + 'signal': config['signal'],
  243 + 'primary_key_pattern': '%s:{item_id}' % config['prefixes'][0],
  244 + 'fallback_key_patterns': [
  245 + '%s:{item_id}' % prefix for prefix in config['prefixes'][1:]
  246 + ],
  247 + })
  248 + return {
  249 + 'ok': True,
  250 + 'version': TOOLSET_VERSION,
  251 + 'catalog_available': self.dimension_catalog.available,
  252 + 'algorithms': algorithms,
  253 + 'list_types': [
  254 + {
  255 + 'name': name,
  256 + 'key_pattern': 'interest:%s:{dimension_key}' % name,
  257 + }
  258 + for name in LIST_TYPE_NAMES
  259 + ],
  260 + 'dimensions': [
  261 + {'name': 'platform', 'key': 'platform:{value}'},
  262 + {'name': 'client_platform', 'key': 'client_platform:{value}'},
  263 + {'name': 'supplier', 'key': 'supplier:{value}'},
  264 + {'name': 'category_level1', 'key': 'category_level1:{value}'},
  265 + {'name': 'category_level2', 'key': 'category_level2:{value}'},
  266 + {'name': 'category_level3', 'key': 'category_level3:{value}'},
  267 + {'name': 'category_level4', 'key': 'category_level4:{value}'},
  268 + {
  269 + 'name': 'platform_client',
  270 + 'key': 'platform_client:{platform}_{client_platform}',
  271 + 'planned_automatically': True,
  272 + },
  273 + {
  274 + 'name': 'platform_category2',
  275 + 'key': 'platform_category2:{platform}_{category_level2}',
  276 + 'planned_automatically': True,
  277 + },
  278 + {
  279 + 'name': 'platform_category3',
  280 + 'key': 'platform_category3:{platform}_{category_level3}',
  281 + 'planned_automatically': True,
  282 + },
  283 + {
  284 + 'name': 'client_category2',
  285 + 'key': 'client_category2:{client_platform}_{category_level2}',
  286 + 'planned_automatically': True,
  287 + },
  288 + {
  289 + 'name': 'platform_country',
  290 + 'key': 'platform:{platform};country_code:{country_code}',
  291 + 'requires_platform': ['essa', 'essaone'],
  292 + 'planned_automatically': True,
  293 + },
  294 + {
  295 + 'name': 'platform_country_customer',
  296 + 'key': (
  297 + 'platform:{platform};country_code:{country_code};'
  298 + 'customer_type:{customer_type}'
  299 + ),
  300 + 'requires_platform': ['essa', 'essaone'],
  301 + 'planned_automatically': True,
  302 + },
  303 + ],
  304 + 'recommended_flow': [
  305 + 'Resolve category or supplier names when only natural language is known.',
  306 + 'Build a hybrid candidate pool from strong seed items and profile dimensions.',
  307 + 'Fetch live product details, price, inventory and eligibility with catalog tools.',
  308 + 'Let the LLM compare the enriched products and explain the final choice.',
  309 + ],
  310 + 'ranking': {
  311 + 'recall_fusion': 'weighted_reciprocal_rank_fusion',
  312 + 'reason': 'Source scores have different scales and are not directly comparable.',
  313 + 'score_range': [0, 1],
  314 + },
  315 + }
  316 +
  317 + def resolve_recommendation_dimension(self, dimension, query, limit=10):
  318 + canonical = DIMENSION_ALIASES.get(str(dimension or '').strip())
  319 + if canonical not in DIMENSION_NAMES:
  320 + raise ToolInputError('Unsupported dimension: %s' % dimension)
  321 + limit = _bounded_integer(limit, 'limit', 10, 1, 20)
  322 + if query is None:
  323 + raise ToolInputError('query is required')
  324 + query = _safe_text(
  325 + query, 'query', max_length=200, allow_separators=True
  326 + )
  327 + matches = self.dimension_catalog.resolve(canonical, query, limit)
  328 + return {
  329 + 'ok': True,
  330 + 'dimension': canonical,
  331 + 'query': query,
  332 + 'matches': matches,
  333 + 'catalog_available': self.dimension_catalog.available,
  334 + 'guidance': (
  335 + None if matches else
  336 + 'No catalog match. Use an internal dimension ID returned by the product catalog.'
  337 + ),
  338 + }
  339 +
  340 + def recall_similar_products(self, seed_items, algorithms=None, top_k=50,
  341 + per_seed_k=50, exclude_item_ids=None):
  342 + top_k = _bounded_integer(top_k, 'top_k', 50, 1, 100)
  343 + per_seed_k = _bounded_integer(per_seed_k, 'per_seed_k', 50, 1, 200)
  344 + seeds = self._normalize_seed_items(seed_items)
  345 + selected_algorithms = self._normalize_algorithms(algorithms)
  346 + excluded = set(_unique_strings(exclude_item_ids, 'exclude_item_ids'))
  347 + excluded.update(seed['item_id'] for seed in seeds)
  348 +
  349 + candidates = {}
  350 + specifications = []
  351 + query_keys = []
  352 + for seed in seeds:
  353 + for algorithm in selected_algorithms:
  354 + aliases = [
  355 + '%s:%s' % (prefix, seed['item_id'])
  356 + for prefix in ALGORITHMS[algorithm]['prefixes']
  357 + ]
  358 + specifications.append({
  359 + 'seed': seed,
  360 + 'algorithm': algorithm,
  361 + 'aliases': aliases,
  362 + })
  363 + query_keys.extend(aliases)
  364 +
  365 + query_keys = _unique_in_order(query_keys)
  366 + values = self.index_store.get_many(query_keys)
  367 + hit_sources = 0
  368 + malformed_sources = 0
  369 + missing_keys = []
  370 + excluded_count = 0
  371 + for specification in specifications:
  372 + ranked_items = []
  373 + chosen_key = None
  374 + saw_value = False
  375 + for key in specification['aliases']:
  376 + value = values.get(key)
  377 + if value is None:
  378 + continue
  379 + saw_value = True
  380 + ranked_items = parse_ranked_items(value)
  381 + if ranked_items:
  382 + chosen_key = key
  383 + break
  384 + if not ranked_items:
  385 + if saw_value:
  386 + malformed_sources += 1
  387 + missing_keys.append(specification['aliases'][0])
  388 + continue
  389 +
  390 + hit_sources += 1
  391 + algorithm = specification['algorithm']
  392 + seed = specification['seed']
  393 + source_weight = ALGORITHMS[algorithm]['weight'] * seed['weight']
  394 + for rank, (item_id, raw_score) in enumerate(
  395 + ranked_items[:per_seed_k], start=1):
  396 + if item_id in excluded:
  397 + excluded_count += 1
  398 + continue
  399 + contribution = source_weight / float(self.rrf_k + rank)
  400 + evidence = {
  401 + 'channel': 'collaborative',
  402 + 'source': algorithm,
  403 + 'key': chosen_key,
  404 + 'seed_item_id': seed['item_id'],
  405 + 'seed_reason': seed.get('reason'),
  406 + 'rank': rank,
  407 + 'raw_score': raw_score,
  408 + 'contribution': round(contribution, 8),
  409 + }
  410 + self._add_candidate(candidates, item_id, contribution, evidence)
  411 +
  412 + items = self._render_candidates(candidates, top_k)
  413 + return {
  414 + 'ok': True,
  415 + 'items': items,
  416 + 'diagnostics': {
  417 + 'strategy': 'weighted_reciprocal_rank_fusion',
  418 + 'rrf_k': self.rrf_k,
  419 + 'algorithms': selected_algorithms,
  420 + 'seed_count': len(seeds),
  421 + 'planned_source_count': len(specifications),
  422 + 'queried_key_count': len(query_keys),
  423 + 'hit_source_count': hit_sources,
  424 + 'missing_source_count': len(missing_keys),
  425 + 'malformed_source_count': malformed_sources,
  426 + 'missing_keys_sample': missing_keys[:20],
  427 + 'excluded_occurrence_count': excluded_count,
  428 + 'candidate_count_before_limit': len(candidates),
  429 + },
  430 + }
  431 +
  432 + def recall_products_by_dimensions(self, context=None, interests=None,
  433 + list_types=None, top_k=50,
  434 + per_source_k=100,
  435 + exclude_item_ids=None):
  436 + top_k = _bounded_integer(top_k, 'top_k', 50, 1, 100)
  437 + per_source_k = _bounded_integer(
  438 + per_source_k, 'per_source_k', 100, 1, 500
  439 + )
  440 + selected_list_types = self._normalize_list_types(list_types)
  441 + plans = self._plan_dimensions(context, interests)
  442 + excluded = set(_unique_strings(exclude_item_ids, 'exclude_item_ids'))
  443 +
  444 + source_plans = []
  445 + for plan in plans:
  446 + for list_type in selected_list_types:
  447 + source_plans.append({
  448 + 'key': 'interest:%s:%s' % (list_type, plan['dimension_key']),
  449 + 'list_type': list_type,
  450 + 'weight': plan['weight'] * LIST_TYPE_WEIGHTS[list_type],
  451 + 'dimension_key': plan['dimension_key'],
  452 + 'matched': plan['matched'],
  453 + 'specificity': plan['specificity'],
  454 + })
  455 + source_plans = source_plans[:500]
  456 + query_keys = [plan['key'] for plan in source_plans]
  457 + values = self.index_store.get_many(query_keys)
  458 +
  459 + candidates = {}
  460 + hit_keys = []
  461 + missing_keys = []
  462 + malformed_keys = []
  463 + excluded_count = 0
  464 + for source in source_plans:
  465 + value = values.get(source['key'])
  466 + if value is None:
  467 + missing_keys.append(source['key'])
  468 + continue
  469 + ranked_items = parse_ranked_items(value)
  470 + if not ranked_items:
  471 + malformed_keys.append(source['key'])
  472 + continue
  473 + hit_keys.append(source['key'])
  474 + for rank, (item_id, raw_score) in enumerate(
  475 + ranked_items[:per_source_k], start=1):
  476 + if item_id in excluded:
  477 + excluded_count += 1
  478 + continue
  479 + contribution = source['weight'] / float(self.rrf_k + rank)
  480 + evidence = {
  481 + 'channel': 'dimension',
  482 + 'source': source['list_type'],
  483 + 'key': source['key'],
  484 + 'dimension_key': source['dimension_key'],
  485 + 'matched': source['matched'],
  486 + 'specificity': source['specificity'],
  487 + 'rank': rank,
  488 + 'raw_score': raw_score,
  489 + 'contribution': round(contribution, 8),
  490 + }
  491 + self._add_candidate(candidates, item_id, contribution, evidence)
  492 +
  493 + items = self._render_candidates(candidates, top_k)
  494 + return {
  495 + 'ok': True,
  496 + 'items': items,
  497 + 'diagnostics': {
  498 + 'strategy': 'specificity_weighted_reciprocal_rank_fusion',
  499 + 'rrf_k': self.rrf_k,
  500 + 'list_types': selected_list_types,
  501 + 'dimension_plan_count': len(plans),
  502 + 'planned_source_count': len(source_plans),
  503 + 'queried_key_count': len(query_keys),
  504 + 'hit_source_count': len(hit_keys),
  505 + 'missing_source_count': len(missing_keys),
  506 + 'malformed_source_count': len(malformed_keys),
  507 + 'hit_keys_sample': hit_keys[:20],
  508 + 'missing_keys_sample': missing_keys[:20],
  509 + 'excluded_occurrence_count': excluded_count,
  510 + 'candidate_count_before_limit': len(candidates),
  511 + },
  512 + }
  513 +
  514 + def build_recommendation_candidates(
  515 + self, seed_items=None, context=None, interests=None,
  516 + algorithms=None, list_types=None, top_k=50, per_seed_k=50,
  517 + per_source_k=100, exclude_item_ids=None,
  518 + collaborative_weight=0.65, dimension_weight=0.35):
  519 + top_k = _bounded_integer(top_k, 'top_k', 50, 1, 100)
  520 + if not seed_items and not context and not interests:
  521 + raise ToolInputError(
  522 + 'At least one seed item, context field, or dimension interest is required'
  523 + )
  524 + collaborative_weight = _bounded_weight(
  525 + collaborative_weight, 'collaborative_weight', 0.65,
  526 + allow_zero=True, maximum=1.0,
  527 + )
  528 + dimension_weight = _bounded_weight(
  529 + dimension_weight, 'dimension_weight', 0.35,
  530 + allow_zero=True, maximum=1.0,
  531 + )
  532 + if collaborative_weight + dimension_weight <= 0:
  533 + raise ToolInputError('At least one channel weight must be positive')
  534 +
  535 + pool_size = min(100, max(top_k * 4, 50))
  536 + channel_results = {}
  537 + if seed_items and collaborative_weight > 0:
  538 + channel_results['collaborative'] = self.recall_similar_products(
  539 + seed_items=seed_items,
  540 + algorithms=algorithms,
  541 + top_k=pool_size,
  542 + per_seed_k=per_seed_k,
  543 + exclude_item_ids=exclude_item_ids,
  544 + )
  545 + if (context or interests) and dimension_weight > 0:
  546 + channel_results['dimension'] = self.recall_products_by_dimensions(
  547 + context=context,
  548 + interests=interests,
  549 + list_types=list_types,
  550 + top_k=pool_size,
  551 + per_source_k=per_source_k,
  552 + exclude_item_ids=exclude_item_ids,
  553 + )
  554 + if not channel_results:
  555 + raise ToolInputError(
  556 + 'No enabled channel has matching seed or dimension inputs'
  557 + )
  558 +
  559 + configured_weights = {
  560 + 'collaborative': collaborative_weight,
  561 + 'dimension': dimension_weight,
  562 + }
  563 + successful_channels = [
  564 + channel for channel, result in channel_results.items()
  565 + if result.get('items')
  566 + ]
  567 + successful_weight = sum(
  568 + configured_weights[channel] for channel in successful_channels
  569 + )
  570 + effective_weights = {}
  571 + if successful_weight:
  572 + effective_weights = {
  573 + channel: configured_weights[channel] / successful_weight
  574 + for channel in successful_channels
  575 + }
  576 +
  577 + combined = {}
  578 + for channel in successful_channels:
  579 + channel_weight = effective_weights[channel]
  580 + for item in channel_results[channel]['items']:
  581 + item_id = item['item_id']
  582 + target = combined.setdefault(item_id, {
  583 + 'item_id': item_id,
  584 + 'score': 0.0,
  585 + 'channel_scores': {},
  586 + 'evidence': [],
  587 + 'reasons': [],
  588 + 'channels': set(),
  589 + 'source_count': 0,
  590 + })
  591 + target['score'] += channel_weight * item['score']
  592 + target['channel_scores'][channel] = item['score']
  593 + target['channels'].add(channel)
  594 + target['source_count'] += item['source_count']
  595 + for evidence in item['evidence']:
  596 + copied = dict(evidence)
  597 + copied['hybrid_channel_weight'] = round(channel_weight, 6)
  598 + target['evidence'].append(copied)
  599 + target['reasons'].extend(item['reasons'])
  600 +
  601 + ranked = sorted(
  602 + combined.values(), key=lambda item: (-item['score'], item['item_id'])
  603 + )
  604 + maximum = ranked[0]['score'] if ranked else 1.0
  605 + final_items = []
  606 + for item in ranked[:top_k]:
  607 + item['score'] = round(item['score'] / maximum, 6)
  608 + item['channels'] = sorted(item['channels'])
  609 + item['evidence'].sort(
  610 + key=lambda evidence: -evidence.get('contribution', 0.0)
  611 + )
  612 + item['evidence'] = item['evidence'][:MAX_EVIDENCE_PER_ITEM]
  613 + item['reasons'] = self._deduplicate_dicts(item['reasons'])[:6]
  614 + final_items.append(item)
  615 +
  616 + return {
  617 + 'ok': True,
  618 + 'items': final_items,
  619 + 'diagnostics': {
  620 + 'strategy': 'normalized_channel_blend',
  621 + 'requested_channel_weights': configured_weights,
  622 + 'effective_channel_weights': effective_weights,
  623 + 'successful_channels': successful_channels,
  624 + 'candidate_count_before_limit': len(combined),
  625 + 'channel_diagnostics': {
  626 + channel: result['diagnostics']
  627 + for channel, result in channel_results.items()
  628 + },
  629 + 'next_step': (
  630 + 'Fetch live product details and eligibility before LLM reranking.'
  631 + ),
  632 + },
  633 + }
  634 +
  635 + @staticmethod
  636 + def _normalize_algorithms(algorithms):
  637 + if algorithms is None:
  638 + return list(ALGORITHM_NAMES)
  639 + if not isinstance(algorithms, (list, tuple)) or not algorithms:
  640 + raise ToolInputError('algorithms must be a non-empty array')
  641 + result = []
  642 + for algorithm in algorithms:
  643 + if algorithm not in ALGORITHMS:
  644 + raise ToolInputError('Unsupported algorithm: %s' % algorithm)
  645 + if algorithm not in result:
  646 + result.append(algorithm)
  647 + return result
  648 +
  649 + @staticmethod
  650 + def _normalize_list_types(list_types):
  651 + if list_types is None:
  652 + return list(LIST_TYPE_NAMES)
  653 + if not isinstance(list_types, (list, tuple)) or not list_types:
  654 + raise ToolInputError('list_types must be a non-empty array')
  655 + result = []
  656 + for list_type in list_types:
  657 + if list_type not in LIST_TYPE_NAMES:
  658 + raise ToolInputError('Unsupported list type: %s' % list_type)
  659 + if list_type not in result:
  660 + result.append(list_type)
  661 + return result
  662 +
  663 + @staticmethod
  664 + def _normalize_seed_items(seed_items):
  665 + if not isinstance(seed_items, (list, tuple)) or not seed_items:
  666 + raise ToolInputError('seed_items must be a non-empty array')
  667 + if len(seed_items) > 20:
  668 + raise ToolInputError('seed_items supports at most 20 entries')
  669 + normalized = {}
  670 + for entry in seed_items:
  671 + if isinstance(entry, dict):
  672 + item_id = normalize_identifier(entry.get('item_id'))
  673 + behavior = entry.get('behavior', 'click')
  674 + if behavior not in BEHAVIOR_WEIGHTS:
  675 + raise ToolInputError('Unsupported seed behavior: %s' % behavior)
  676 + weight = _bounded_weight(
  677 + entry.get('weight'), 'seed weight', BEHAVIOR_WEIGHTS[behavior]
  678 + )
  679 + reason = entry.get('reason')
  680 + if reason is not None:
  681 + reason = _safe_text(
  682 + reason, 'seed reason', max_length=200,
  683 + allow_separators=True,
  684 + )
  685 + else:
  686 + item_id = normalize_identifier(entry)
  687 + weight = 1.0
  688 + reason = None
  689 + if item_id is None:
  690 + raise ToolInputError('Every seed item requires a valid item_id')
  691 + item_id = _safe_text(item_id, 'item_id', max_length=128)
  692 + current = normalized.get(item_id)
  693 + if current is None or weight > current['weight']:
  694 + normalized[item_id] = {
  695 + 'item_id': item_id,
  696 + 'weight': weight,
  697 + 'reason': reason,
  698 + }
  699 + return list(normalized.values())
  700 +
  701 + def _normalize_context(self, context):
  702 + if context is None:
  703 + return {}
  704 + if not isinstance(context, dict):
  705 + raise ToolInputError('context must be an object')
  706 + allowed = {'platform', 'client_platform', 'country_code', 'customer_type'}
  707 + unknown = set(context) - allowed
  708 + if unknown:
  709 + raise ToolInputError('Unsupported context fields: %s' % ', '.join(sorted(unknown)))
  710 + result = {}
  711 + if context.get('platform') is not None:
  712 + result['platform'] = _safe_text(
  713 + context['platform'], 'platform', lower=True
  714 + )
  715 + if context.get('client_platform') is not None:
  716 + result['client_platform'] = _safe_text(
  717 + context['client_platform'], 'client_platform', lower=True
  718 + )
  719 + if context.get('country_code') is not None:
  720 + result['country_code'] = _safe_text(
  721 + context['country_code'], 'country_code', upper=True
  722 + )
  723 + if context.get('customer_type') is not None:
  724 + result['customer_type'] = _safe_text(
  725 + context['customer_type'], 'customer_type'
  726 + )
  727 + return result
  728 +
  729 + def _normalize_interests(self, interests):
  730 + if interests is None:
  731 + return []
  732 + if not isinstance(interests, (list, tuple)):
  733 + raise ToolInputError('interests must be an array')
  734 + if len(interests) > 30:
  735 + raise ToolInputError('interests supports at most 30 entries')
  736 + result = []
  737 + for entry in interests:
  738 + if not isinstance(entry, dict):
  739 + raise ToolInputError('Every interest must be an object')
  740 + dimension = DIMENSION_ALIASES.get(str(entry.get('dimension', '')).strip())
  741 + if dimension not in DIMENSION_NAMES:
  742 + raise ToolInputError('Unsupported dimension: %s' % entry.get('dimension'))
  743 + value = self._normalize_dimension_value(dimension, entry.get('value'))
  744 + weight = _bounded_weight(entry.get('weight'), 'interest weight', 1.0)
  745 + reason = entry.get('reason')
  746 + if reason is not None:
  747 + reason = _safe_text(
  748 + reason, 'interest reason', max_length=200,
  749 + allow_separators=True,
  750 + )
  751 + result.append({
  752 + 'dimension': dimension,
  753 + 'value': value,
  754 + 'weight': weight,
  755 + 'origin': 'profile',
  756 + 'reason': reason,
  757 + })
  758 + return result
  759 +
  760 + @staticmethod
  761 + def _normalize_dimension_value(dimension, value):
  762 + normalized = normalize_identifier(value)
  763 + if normalized is None:
  764 + raise ToolInputError('%s requires a valid value' % dimension)
  765 + if dimension in ('platform', 'client_platform'):
  766 + return _safe_text(normalized, dimension, lower=True)
  767 + if dimension == 'country_code':
  768 + return _safe_text(normalized, dimension, upper=True)
  769 + return _safe_text(normalized, dimension)
  770 +
  771 + def _plan_dimensions(self, context, interests):
  772 + context = self._normalize_context(context)
  773 + interests = self._normalize_interests(interests)
  774 + values = {dimension: [] for dimension in DIMENSION_NAMES}
  775 + for dimension, value in context.items():
  776 + values[dimension].append({
  777 + 'dimension': dimension,
  778 + 'value': value,
  779 + 'weight': 1.0,
  780 + 'origin': 'context',
  781 + 'reason': None,
  782 + })
  783 + for interest in interests:
  784 + values[interest['dimension']].append(interest)
  785 + if not any(values.values()):
  786 + raise ToolInputError('No queryable context or dimension interest was supplied')
  787 +
  788 + plans = {}
  789 + for dimension in DIRECT_DIMENSIONS:
  790 + for entry in values[dimension]:
  791 + self._add_dimension_plan(
  792 + plans,
  793 + '%s:%s' % (dimension, entry['value']),
  794 + entry['weight'],
  795 + [self._matched_value(entry)],
  796 + 1,
  797 + )
  798 +
  799 + for platform in values['platform']:
  800 + for client in values['client_platform']:
  801 + self._add_combination_plan(
  802 + plans,
  803 + 'platform_client:%s_%s' % (
  804 + platform['value'], client['value']
  805 + ),
  806 + [platform, client],
  807 + 1.20,
  808 + 2,
  809 + )
  810 + for category in values['category_level2']:
  811 + self._add_combination_plan(
  812 + plans,
  813 + 'platform_category2:%s_%s' % (
  814 + platform['value'], category['value']
  815 + ),
  816 + [platform, category],
  817 + 1.30,
  818 + 2,
  819 + )
  820 + for category in values['category_level3']:
  821 + self._add_combination_plan(
  822 + plans,
  823 + 'platform_category3:%s_%s' % (
  824 + platform['value'], category['value']
  825 + ),
  826 + [platform, category],
  827 + 1.35,
  828 + 2,
  829 + )
  830 + if platform['value'] in ('essa', 'essaone'):
  831 + for country in values['country_code']:
  832 + country_key = 'platform:%s;country_code:%s' % (
  833 + platform['value'], country['value']
  834 + )
  835 + self._add_combination_plan(
  836 + plans, country_key, [platform, country], 1.40, 2
  837 + )
  838 + for customer_type in values['customer_type']:
  839 + self._add_combination_plan(
  840 + plans,
  841 + '%s;customer_type:%s' % (
  842 + country_key, customer_type['value']
  843 + ),
  844 + [platform, country, customer_type],
  845 + 1.60,
  846 + 3,
  847 + )
  848 +
  849 + for client in values['client_platform']:
  850 + for category in values['category_level2']:
  851 + self._add_combination_plan(
  852 + plans,
  853 + 'client_category2:%s_%s' % (
  854 + client['value'], category['value']
  855 + ),
  856 + [client, category],
  857 + 1.20,
  858 + 2,
  859 + )
  860 +
  861 + ranked_plans = sorted(
  862 + plans.values(),
  863 + key=lambda plan: (
  864 + -plan['specificity'], -plan['weight'], plan['dimension_key']
  865 + ),
  866 + )
  867 + if not ranked_plans:
  868 + raise ToolInputError(
  869 + 'The supplied dimensions require platform or another queryable dimension'
  870 + )
  871 + return ranked_plans[:MAX_DIMENSION_PLANS]
  872 +
  873 + def _add_combination_plan(self, plans, key, entries, multiplier, specificity):
  874 + average_weight = sum(entry['weight'] for entry in entries) / len(entries)
  875 + self._add_dimension_plan(
  876 + plans,
  877 + key,
  878 + average_weight * multiplier,
  879 + [self._matched_value(entry) for entry in entries],
  880 + specificity,
  881 + )
  882 +
  883 + @staticmethod
  884 + def _add_dimension_plan(plans, key, weight, matched, specificity):
  885 + current = plans.get(key)
  886 + if current is None:
  887 + plans[key] = {
  888 + 'dimension_key': key,
  889 + 'weight': weight,
  890 + 'matched': matched,
  891 + 'specificity': specificity,
  892 + }
  893 + return
  894 + current['weight'] = max(current['weight'], weight)
  895 + current['specificity'] = max(current['specificity'], specificity)
  896 + current['matched'] = RecommendationAgentTools._deduplicate_dicts(
  897 + current['matched'] + matched
  898 + )
  899 +
  900 + @staticmethod
  901 + def _matched_value(entry):
  902 + result = {
  903 + 'dimension': entry['dimension'],
  904 + 'value': entry['value'],
  905 + 'origin': entry['origin'],
  906 + }
  907 + if entry.get('reason'):
  908 + result['reason'] = entry['reason']
  909 + return result
  910 +
  911 + @staticmethod
  912 + def _add_candidate(candidates, item_id, contribution, evidence):
  913 + candidate = candidates.setdefault(item_id, {
  914 + 'score': 0.0,
  915 + 'evidence': [],
  916 + 'channels': set(),
  917 + })
  918 + candidate['score'] += contribution
  919 + candidate['evidence'].append(evidence)
  920 + candidate['channels'].add(evidence['channel'])
  921 +
  922 + def _render_candidates(self, candidates, top_k):
  923 + ranked = sorted(
  924 + candidates.items(), key=lambda entry: (-entry[1]['score'], entry[0])
  925 + )
  926 + maximum = ranked[0][1]['score'] if ranked else 1.0
  927 + items = []
  928 + for item_id, candidate in ranked[:top_k]:
  929 + all_evidence = sorted(
  930 + candidate['evidence'],
  931 + key=lambda entry: -entry.get('contribution', 0.0),
  932 + )
  933 + evidence = all_evidence[:MAX_EVIDENCE_PER_ITEM]
  934 + items.append({
  935 + 'item_id': item_id,
  936 + 'score': round(candidate['score'] / maximum, 6),
  937 + 'channels': sorted(candidate['channels']),
  938 + 'source_count': len({entry['key'] for entry in all_evidence}),
  939 + 'reasons': self._build_reasons(evidence),
  940 + 'evidence': evidence,
  941 + })
  942 + return items
  943 +
  944 + @staticmethod
  945 + def _build_reasons(evidence):
  946 + collaborative = {}
  947 + dimensions = {}
  948 + for entry in evidence:
  949 + if entry['channel'] == 'collaborative':
  950 + seed = entry['seed_item_id']
  951 + reason = collaborative.setdefault(seed, {
  952 + 'type': 'similar_to_seed',
  953 + 'seed_item_id': seed,
  954 + 'algorithms': [],
  955 + })
  956 + if entry['source'] not in reason['algorithms']:
  957 + reason['algorithms'].append(entry['source'])
  958 + if entry.get('seed_reason'):
  959 + reason['profile_reason'] = entry['seed_reason']
  960 + else:
  961 + dimension_key = entry['dimension_key']
  962 + reason = dimensions.setdefault(dimension_key, {
  963 + 'type': 'matched_dimension',
  964 + 'dimension_key': dimension_key,
  965 + 'list_types': [],
  966 + 'matched': entry.get('matched', []),
  967 + })
  968 + if entry['source'] not in reason['list_types']:
  969 + reason['list_types'].append(entry['source'])
  970 + return list(collaborative.values()) + list(dimensions.values())
  971 +
  972 + @staticmethod
  973 + def _deduplicate_dicts(values):
  974 + result = []
  975 + seen = set()
  976 + for value in values:
  977 + marker = repr(sorted(value.items()))
  978 + if marker not in seen:
  979 + result.append(value)
  980 + seen.add(marker)
  981 + return result
... ...
offline_tasks/agent_tools/store.py 0 → 100644
... ... @@ -0,0 +1,40 @@
  1 +"""Storage adapters used by the recommendation tools."""
  2 +
  3 +
  4 +class IndexStore(object):
  5 + """Minimal interface required by the recommendation service."""
  6 +
  7 + def get_many(self, keys):
  8 + raise NotImplementedError
  9 +
  10 +
  11 +class MemoryIndexStore(IndexStore):
  12 + """Small deterministic store for tests and local examples."""
  13 +
  14 + def __init__(self, values=None):
  15 + self.values = dict(values or {})
  16 + self.requested_keys = []
  17 +
  18 + def get_many(self, keys):
  19 + keys = list(keys)
  20 + self.requested_keys.extend(keys)
  21 + return {key: self.values.get(key) for key in keys}
  22 +
  23 + def set(self, key, value):
  24 + self.values[key] = value
  25 +
  26 +
  27 +class RedisIndexStore(IndexStore):
  28 + """Adapter around a redis-py compatible client."""
  29 +
  30 + def __init__(self, redis_client):
  31 + if redis_client is None:
  32 + raise ValueError('redis_client is required')
  33 + self.redis_client = redis_client
  34 +
  35 + def get_many(self, keys):
  36 + keys = list(keys)
  37 + if not keys:
  38 + return {}
  39 + values = self.redis_client.mget(keys)
  40 + return dict(zip(keys, values))
... ...
offline_tasks/doc/README.md
... ... @@ -6,6 +6,20 @@
6 6  
7 7 ## 📚 核心文档
8 8  
  9 +### 0. 智能导购 Agent 工具集
  10 +
  11 +**文件**: [智能导购Agent工具集.md](./智能导购Agent工具集.md)
  12 +
  13 +**内容**:
  14 +- Agent 推荐架构与能力边界
  15 +- 5 个工具的输入输出和编排方式
  16 +- 多算法 RRF、画像融合与可解释证据
  17 +- CLI、stdio、Python 接入和上线评估
  18 +
  19 +**适用对象**: Agent 开发、推荐工程、在线服务开发
  20 +
  21 +---
  22 +
9 23 ### 1. 详细设计文档
10 24  
11 25 **文件**: [详细设计文档.md](./详细设计文档.md)
... ... @@ -89,7 +103,8 @@
89 103  
90 104 ## 🔄 文档更新记录
91 105  
92   -- **2024-10-17**: 整合文档,简化为3个核心文档
  106 +- **2026-08-23**: 新增 Agent 工具方案,统一 Redis key/value 当前契约
  107 +- **2024-10-17**: 整合核心文档
93 108 - **2024-10-16**: 初始版本,包含完整功能文档
94 109  
95 110 ---
... ... @@ -100,4 +115,4 @@
100 115  
101 116 如有疑问、发现错误或建议改进,请联系团队。
102 117  
103   -**最后更新**: 2024-10-17
  118 +**最后更新**: 2026-08-23
... ...
offline_tasks/doc/Redis_Key格式问题修复方案.md
1   -# Redis Key格式问题修复方案
  1 +# Redis key 前缀迁移记录
2 2  
3   -## 🔍 问题诊断
  3 +本文是历史事故记录。当前在线契约请以 [Redis数据规范.md](./Redis数据规范.md) 为准。
4 4  
5   -### 发现的问题
  5 +## 历史问题
6 6  
7   -经过排查,发现了以下三个关键问题:
8   -
9   -1. **Redis Key 格式错误** ❌
10   - - **实际存储**: `i2i:content_name:*`, `i2i:deepwalk:*`, `i2i:session_w2v:*`
11   - - **文档定义**: `item:similar:content_name:*`, `item:similar:deepwalk:*`, `item:similar:session_w2v:*`
12   - - **影响**: 查询 `KEYS item:similar:*` 返回空,因为key前缀不匹配
13   -
14   -2. **C++ Swing 未被加载** ❌
15   - - `collaboration/output/swing_similar.txt` 存在(15,177条记录,6.9MB)
16   - - 但加载脚本没有处理这个文件
17   - - 应该存储为: `item:similar:swing_cpp:*`
18   -
19   -3. **Python Swing 文件缺失** ⚠️
20   - - `i2i_swing_20251022.txt` 不存在
21   - - Python Swing算法可能执行失败
22   -
23   -### 数据统计
  7 +旧版加载器曾把 Python I2I 输出写成:
24 8  
  9 +```text
  10 +i2i:{algorithm}:{item_id}
25 11 ```
26   -Redis总Key数: 229,710
27   - ├─ i2i:* (错误格式): 176,150
28   - ├─ item:similar:* (正确格式): 0
29   - └─ interest:* (正确格式): 53,560 ✓
30   -
31   -C++ Swing输出: 15,177条记录 (未加载)
32   -Interest数据: 53,560条 (已正确加载) ✓
33   -```
34   -
35   -**结论**: `interest:*` 有数据是因为它使用了正确的key格式,但 `item:similar:*` 为空是因为数据被错误地存储到了 `i2i:*` 格式。
36   -
37   ----
38   -
39   -## 🔧 根本原因
40 12  
41   -### 代码问题定位
  13 +在线服务使用的是:
42 14  
43   -**文件**: `scripts/load_index_to_redis.py`
44   -
45   -**错误代码** (第100行):
46   -```python
47   -count = load_index_file(
48   - file_path,
49   - redis_client,
50   - f"i2i:{i2i_type}", # ❌ 错误!
51   - expire_seconds
52   -)
53   -```
54   -
55   -**应该是**:
56   -```python
57   -count = load_index_file(
58   - file_path,
59   - redis_client,
60   - f"item:similar:{i2i_type}", # ✓ 正确!
61   - expire_seconds
62   -)
  15 +```text
  16 +item:similar:{algorithm}:{item_id}
63 17 ```
64 18  
65   -**缺失功能**: 没有加载 C++ Swing 的函数
66   -
67   ----
68   -
69   -## ✅ 修复方案
70   -
71   -### 已完成的修复
72   -
73   -✅ **1. 修复了 `load_index_to_redis.py`**
74   - - 修正了key前缀: `i2i:` → `item:similar:`
75   - - 添加了 `load_cpp_swing_index()` 函数
76   - - 添加了 `i2i_item_behavior` 到加载列表
77   -
78   -✅ **2. 创建了清理脚本 `fix_redis_keys.py`**
79   - - 清理错误格式的 `i2i:*` key
80   - - 提供统计信息和确认提示
81   -
82   -### 执行步骤
  19 +前缀不一致导致离线文件存在、Redis 也有数据,但在线标准 key 全部未命中。同期 C++ Swing 文件也没有进入加载流程。
83 20  
84   -#### 步骤1: 清理错误的Redis Key
  21 +## 已落实的代码修复
85 22  
86   -```bash
87   -cd /home/tw/recommendation/offline_tasks
  23 +当前 `scripts/load_index_to_redis.py`:
88 24  
89   -# 运行清理脚本
90   -python3 scripts/fix_redis_keys.py
91   -# 输入 'yes' 确认删除错误格式的key
92   -```
  25 +- 使用 `item:similar:{algorithm}:{item_id}`;
  26 +- 单独加载 `item:similar:swing_cpp:{item_id}`;
  27 +- 加载 `swing`、`session_w2v`、`deepwalk`、`content_name`、`content_pic`、`item_behavior`;
  28 +- 将 TSV 最后一列的 `item_id:score,...` 原样写入 Redis;
  29 +- 默认设置 60 天 TTL,并执行商品新鲜度过滤。
93 30  
94   -#### 步骤2: 重新加载数据(使用output_1022的数据)
  31 +Session W2V 当前标准 key 是 `item:similar:session_w2v:{item_id}`,不是早期部分文档中的 `item:similar:w2v:{item_id}`。
95 32  
96   -```bash
97   -# 方式1: 从output_1022目录加载指定日期的数据
98   -python3 scripts/load_index_to_redis.py \
99   - --date 20251022 \
100   - --redis-host localhost \
101   - --redis-port 6379 \
102   - --expire-days 7
  33 +## 安全迁移步骤
103 34  
104   -# 注意:确保output目录指向output_1022,或者临时修改OUTPUT_DIR
105   -```
  35 +1. 在目标 Redis 使用 `SCAN` 分别统计旧、新前缀,不使用生产 `KEYS`。
  36 +2. 抽样解析旧 value,确认它与当前 `item_id:score,...` 或兼容格式一致。
  37 +3. 先运行当前加载器写入新 key,并验证覆盖率、TTL 和在线 hit rate。
  38 +4. 在一个完整 TTL 周期内保留读取兼容;Agent 工具会把旧 `w2v` 作为 `session_w2v` 的后备。
  39 +5. 只有在确认所有消费者已切换、回滚窗口结束后,才另行审批旧 key 清理。
106 40  
107   -**或者,更简单的方式**:
  41 +不要通过替换整个 `output` 目录、刷新 Redis 数据库或全量删除旧前缀来完成普通重载。这些操作影响面超出 key 迁移,需要独立确认和回滚方案。
108 42  
109   -```bash
110   -# 创建软链接指向output_1022
111   -cd /home/tw/recommendation/offline_tasks
112   -rm -rf output # 如果当前output是目录
113   -ln -s output_1022/output output
114   -
115   -# 然后正常加载
116   -python3 scripts/load_index_to_redis.py \
117   - --redis-host localhost \
118   - --redis-port 6379 \
119   - --date 20251022
120   -```
121   -
122   -#### 步骤3: 验证修复结果
  43 +## 验证清单
123 44  
124 45 ```bash
125   -redis-cli
126   -
127   -# 检查key数量
128   -DBSIZE
129   -
130   -# 查看正确格式的key
131   -KEYS item:similar:*
132   -
133   -# 查看C++ Swing的key(应该有15177个)
134   -KEYS item:similar:swing_cpp:*
135   -
136   -# 查看其他i2i算法的key
137   -KEYS item:similar:deepwalk:*
138   -KEYS item:similar:content_name:*
139   -KEYS item:similar:session_w2v:*
140   -KEYS item:similar:item_behavior:*
141   -
142   -# 验证interest数据仍然存在
143   -KEYS interest:*
144   -
145   -# 测试查询具体的key
146   -GET item:similar:swing_cpp:3600052
147   -GET interest:hot:platform:essabuy
  46 +redis-cli --scan --pattern 'item:similar:swing_cpp:*' | head
  47 +redis-cli --scan --pattern 'item:similar:swing:*' | head
  48 +redis-cli --scan --pattern 'item:similar:session_w2v:*' | head
  49 +redis-cli --scan --pattern 'item:similar:item_behavior:*' | head
  50 +redis-cli GET 'item:similar:swing:{sample_item_id}'
  51 +redis-cli TTL 'item:similar:swing:{sample_item_id}'
148 52 ```
149 53  
150   -**预期结果**:
151   -```
152   -KEYS item:similar:* 返回数量: ~176,000+ (包括C++ Swing的15,177条)
153   -KEYS item:similar:swing_cpp:* 返回数量: 15,177
154   -KEYS item:similar:deepwalk:* 返回数量: ~48,376
155   -KEYS item:similar:content_name:* 返回数量: ~127,720
156   -KEYS interest:* 返回数量: 53,560 (保持不变)
157   -```
158   -
159   ----
160   -
161   -## 📊 修复后的数据结构
162   -
163   -### 正确的Redis Key格式
164   -
165   -```
166   -# i2i相似度索引
167   -item:similar:swing_cpp:{item_id} → C++ Swing结果
168   -item:similar:swing:{item_id} → Python Swing结果
169   -item:similar:session_w2v:{item_id} → Session W2V结果
170   -item:similar:deepwalk:{item_id} → DeepWalk结果
171   -item:similar:content_name:{item_id} → 内容相似度(名称)
172   -item:similar:content_pic:{item_id} → 内容相似度(图片)
173   -item:similar:item_behavior:{item_id} → Item行为相似度
174   -
175   -# 兴趣点聚合索引
176   -interest:hot:{dimension_key} → 热门商品
177   -interest:cart:{dimension_key} → 加购商品
178   -interest:new:{dimension_key} → 新品
179   -interest:global:{dimension_key} → 全局热门
180   -```
181   -
182   -### 查询示例
183   -
184   -```python
185   -import redis
186   -import json
187   -
188   -r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
189   -
190   -# 查询C++ Swing相似商品
191   -similar_items = json.loads(r.get('item:similar:swing_cpp:3600052'))
192   -# 返回: [[2704531, 0.00431593], [2503886, 0.00431593], ...]
193   -
194   -# 查询平台热门商品
195   -hot_items = r.get('interest:hot:platform:essabuy')
196   -# 返回: "3090653:70.0000,3509349:70.0000,..."
197   -```
198   -
199   ----
200   -
201   -## 🚨 Python Swing 问题
202   -
203   -### 问题描述
204   -`i2i_swing_20251022.txt` 文件不存在,说明Python Swing算法没有成功执行。
205   -
206   -### 可能原因
207   -1. 算法执行失败(内存不足、超时等)
208   -2. Session数据问题
209   -3. 参数配置问题
210   -
211   -### 排查步骤
212   -
213   -```bash
214   -# 查看Python Swing的日志
215   -cat /home/tw/recommendation/offline_tasks/output_1022/logs/debug/i2i_swing*.log
216   -
217   -# 检查session文件
218   -ls -lh /home/tw/recommendation/offline_tasks/output_1022/output/session.txt.*
219   -
220   -# 手动运行Python Swing测试
221   -cd /home/tw/recommendation/offline_tasks
222   -python3 scripts/i2i_swing.py --lookback_days 30 --top_n 10 --debug
223   -```
224   -
225   -### 临时解决方案
226   -由于C++ Swing已经生成且性能更好,可以暂时只使用C++ Swing的结果:
227   -- C++ Swing: `item:similar:swing_cpp:*` (15,177条记录)
228   -- 文档推荐在生产环境使用C++ Swing
229   -
230   ----
231   -
232   -## 📝 后续改进建议
233   -
234   -### 1. 代码改进
235   -- ✅ 已修复key格式问题
236   -- ✅ 已添加C++ Swing加载功能
237   -- 建议: 添加单元测试验证key格式
238   -
239   -### 2. 文档更新
240   -- 更新 `Redis数据规范.md` 中的加载示例代码
241   -- 添加故障排查指南
242   -- 标注C++ Swing为生产推荐
243   -
244   -### 3. 监控告警
245   -- 添加Redis key格式验证
246   -- 监控各类索引的数量
247   -- Python Swing执行失败时告警
248   -
249   -### 4. 自动化测试
250   -```python
251   -# 建议添加测试用例
252   -def test_redis_key_format():
253   - """测试Redis key格式是否正确"""
254   - keys = redis_client.keys('item:similar:*')
255   - assert len(keys) > 0, "item:similar:* should not be empty"
256   -
257   - # 确保没有错误格式的key
258   - wrong_keys = redis_client.keys('i2i:*')
259   - assert len(wrong_keys) == 0, f"Found wrong format keys: {wrong_keys[:5]}"
260   -```
261   -
262   ----
263   -
264   -## 🎯 总结
265   -
266   -### 问题根源
267   -加载脚本使用了错误的Redis key前缀 `i2i:*` 而不是文档定义的 `item:similar:*`
268   -
269   -### 解决方案
270   -1. ✅ 修复了 `load_index_to_redis.py` 的key前缀
271   -2. ✅ 添加了C++ Swing加载功能
272   -3. ✅ 创建了清理脚本清理错误的key
273   -4. ⏳ 需要重新加载数据
274   -
275   -### 后续行动
276   -1. 执行 `fix_redis_keys.py` 清理错误的key
277   -2. 重新运行 `load_index_to_redis.py` 加载数据
278   -3. 验证所有 `item:similar:*` key都能正常查询
279   -4. 排查Python Swing执行失败的原因
280   -
281   ----
  54 +验证不能只看 key 存在,还应检查 value 可解析、候选有序、种子商品未自召回、候选实时可售,以及在线请求确实连接到同一 Redis 实例和 DB。
282 55  
283   -**创建时间**: 2025-10-22
284   -**版本**: v1.0
285   -**状态**: ✅ 修复方案已就绪,等待执行
  56 +更新日期:2026-08-23。
286 57  
... ...
offline_tasks/doc/Redis数据规范.md
1   -# Redis数据灌入规范
  1 +# Redis 在线索引契约
2 2  
3   -## 📋 数据灌入概述
  3 +本文描述 `scripts/load_index_to_redis.py` 当前实际写入的 Redis 契约。在线服务、诊断脚本和 Agent 工具均应以本文及加载器代码为准。
4 4  
5   -将离线生成的推荐索引加载到Redis,供在线系统实时查询使用。
  5 +## 1. 权威约定
6 6  
7   -## 🔑 Redis Key规范
  7 +- 加载器取离线 TSV 的第一列作为 key 后缀,最后一列作为 value。
  8 +- value 原样写入 Redis,不会转换成 JSON。
  9 +- 当前标准 value 是按排名降序的文本:`item_id:score,item_id:score,...`。
  10 +- 所有索引的默认 TTL 都由 `--expire-days` 控制,当前默认值为 60 天。
  11 +- Redis 地址、端口、数据库和认证信息由部署配置决定,文档不固定数据库编号,也不保存凭据。
  12 +- 商品 ID 在接口中建议使用字符串,避免跨语言传递时的数值精度问题。
8 13  
9   -### 通用规则
10   -```
11   -{namespace}:{function}:{algorithm}:{identifier}
12   -```
13   -
14   -- `namespace`: 业务命名空间(item, user, interest等)
15   -- `function`: 功能类型(similar, feature, hot等)
16   -- `algorithm`: 算法名称(swing, w2v, deepwalk等)
17   -- `identifier`: 具体标识(item_id, dimension_key等)
18   -
19   -## 📊 数据灌入规范表
20   -
21   -| 模块名称 | 源数据地址 | 格式描述 | RedisKey模板 | RedisValue格式 | TTL |
22   -|---------|-----------|---------|-------------|---------------|-----|
23   -| **i2i_swing_cpp** | `offline_tasks/collaboration/output/swing_similar.txt` | `item_id\tsimilar_id1:score1,...` | `item:similar:swing_cpp:{item_id}` | `[[similar_id1,score1],[similar_id2,score2],...]` | 60天 |
24   -| **i2i_swing** | `output/i2i_swing_YYYYMMDD.txt` | `item_id\titem_name\tsimilar_id1:score1,...` | `item:similar:swing:{item_id}` | `[[similar_id1,score1],[similar_id2,score2],...]` | 60天 |
25   -| **i2i_session_w2v** | `output/i2i_session_w2v_YYYYMMDD.txt` | `item_id\titem_name\tsimilar_id1:score1,...` | `item:similar:w2v:{item_id}` | `[[similar_id1,score1],[similar_id2,score2],...]` | 60天 |
26   -| **i2i_deepwalk** | `output/i2i_deepwalk_YYYYMMDD.txt` | `item_id\titem_name\tsimilar_id1:score1,...` | `item:similar:deepwalk:{item_id}` | `[[similar_id1,score1],[similar_id2,score2],...]` | 60天 |
27   -| **i2i_content_name** | `output/i2i_content_name_YYYYMMDD.txt` | `item_id\titem_name\tsimilar_id1:score1,...` | `item:similar:content_name:{item_id}` | `[[similar_id1,score1],[similar_id2,score2],...]` | 800天 |
28   -| **i2i_content_pic** | `output/i2i_content_pic_YYYYMMDD.txt` | `item_id\titem_name\tsimilar_id1:score1,...` | `item:similar:content_pic:{item_id}` | `[[similar_id1,score1],[similar_id2,score2],...]` | 800天 |
29   -| **interest_hot** | `output/interest_aggregation_hot_YYYYMMDD.txt` | `dimension_key\titem_id1,item_id2,...` | `interest:hot:{dimension_key}` | `[item_id1,item_id2,item_id3,...]` | 60天 |
30   -| **interest_cart** | `output/interest_aggregation_cart_YYYYMMDD.txt` | `dimension_key\titem_id1,item_id2,...` | `interest:cart:{dimension_key}` | `[item_id1,item_id2,item_id3,...]` | 60天 |
31   -| **interest_new** | `output/interest_aggregation_new_YYYYMMDD.txt` | `dimension_key\titem_id1,item_id2,...` | `interest:new:{dimension_key}` | `[item_id1,item_id2,item_id3,...]` | 60天 |
32   -| **interest_global** | `output/interest_aggregation_global_YYYYMMDD.txt` | `dimension_key\titem_id1,item_id2,...` | `interest:global:{dimension_key}` | `[item_id1,item_id2,item_id3,...]` | 60天 |
33   -
34   -## 📝 详细说明
35   -
36   -### 1. i2i相似度索引
  14 +示例:
37 15  
38   -#### 1.1 C++ Swing算法(高性能版本)
39   -
40   -**源数据格式**
41   -```
42   -3600052 2704531:0.00431593,2503886:0.00431593,3371410:0.00431593,3186572:0.00431593
  16 +```text
  17 +Key: item:similar:swing:3141390
  18 +Value: 3264320:1.2656,3264284:1.2656,3562128:0.4000
43 19 ```
44 20  
45   -**Redis存储**
  21 +value 不是下面这种 JSON:
46 22  
47   -**Key**: `item:similar:swing_cpp:3600052`
48   -
49   -**Value** (JSON格式):
50 23 ```json
51   -[[2704531, 0.00431593], [2503886, 0.00431593], [3371410, 0.00431593], [3186572, 0.00431593]]
  24 +[[3264320, 1.2656], [3264284, 1.2656]]
52 25 ```
53 26  
54   -**Value** (序列化后):
55   -```python
56   -import json
57   -value = json.dumps([[2704531, 0.00431593], [2503886, 0.00431593], [3371410, 0.00431593], [3186572, 0.00431593]])
58   -# 存储: "[[2704531,0.00431593],[2503886,0.00431593],[3371410,0.00431593],[3186572,0.00431593]]"
59   -```
  27 +历史环境可能仍保留 JSON pair 数组、JSON ID 数组或旧的 `item:similar:w2v:*` key。新代码不应继续写这些格式;`agent_tools` 的读取器仅为平滑迁移而兼容它们。
60 28  
61   -**特点**:
62   -- 原始Swing分数(未归一化)
63   -- 高性能C++计算
64   -- 适合大规模数据
  29 +## 2. I2I 索引
65 30  
66   -#### 1.2 Python Swing算法(标准版本)
  31 +| 离线模块 | 输入文件 | Redis key | value |
  32 +| --- | --- | --- | --- |
  33 +| C++ Swing | `collaboration/output/swing_similar.txt` | `item:similar:swing_cpp:{item_id}` | `item_id:score,...` |
  34 +| Python Swing | `output/i2i_swing_YYYYMMDD.txt` | `item:similar:swing:{item_id}` | `item_id:score,...` |
  35 +| Session W2V | `output/i2i_session_w2v_YYYYMMDD.txt` | `item:similar:session_w2v:{item_id}` | `item_id:score,...` |
  36 +| DeepWalk | `output/i2i_deepwalk_YYYYMMDD.txt` | `item:similar:deepwalk:{item_id}` | `item_id:score,...` |
  37 +| 名称内容相似 | `output/i2i_content_name_YYYYMMDD.txt` | `item:similar:content_name:{item_id}` | `item_id:score,...` |
  38 +| 图片内容相似 | `output/i2i_content_pic_YYYYMMDD.txt` | `item:similar:content_pic:{item_id}` | `item_id:score,...` |
  39 +| 行为相似 | `output/i2i_item_behavior_YYYYMMDD.txt` | `item:similar:item_behavior:{item_id}` | `item_id:score,...` |
67 40  
68   -**源数据格式**
69   -```
70   -12345 香蕉干 67890:0.8567,11223:0.7234,44556:0.6891
71   -```
  41 +`item:similar:w2v:{item_id}` 是历史别名,不是当前加载器的写入目标。迁移期间可以读它作为 `session_w2v` 的后备 key,但新生产者和新调用方必须使用 `item:similar:session_w2v:{item_id}`。
72 42  
73   -**Redis存储**
  43 +各算法原始 score 的量纲不同,例如 Swing 原始分数、向量分数和行为聚合分数不能直接相加。跨算法融合应使用排名融合或先逐路校准;Agent 工具默认使用加权 RRF。
74 44  
75   -**Key**: `item:similar:swing:12345`
  45 +## 3. 兴趣聚合索引
76 46  
77   -**Value** (JSON格式):
78   -```json
79   -[[67890, 0.8567], [11223, 0.7234], [44556, 0.6891]]
80   -```
  47 +完整 key 格式为:
81 48  
82   -**Value** (序列化后):
83   -```python
84   -import json
85   -value = json.dumps([[67890, 0.8567], [11223, 0.7234], [44556, 0.6891]])
86   -# 存储: "[[67890,0.8567],[11223,0.7234],[44556,0.6891]]"
  49 +```text
  50 +interest:{list_type}:{dimension_key}
87 51 ```
88 52  
89   -**特点**:
90   -- 归一化分数(0-1区间)
91   -- 支持时间衰减和日期维度
92   -- 便于调试
93   -
94   -#### 1.3 查询示例
95   -
96   -```python
97   -import redis
98   -import json
99   -
100   -r = redis.Redis(host='localhost', port=6379, db=0)
  53 +`list_type` 有四种:
101 54  
102   -# 方式1: 获取C++ Swing结果(生产推荐)
103   -similar_items_cpp = json.loads(r.get('item:similar:swing_cpp:3600052'))
104   -# 返回: [[2704531, 0.00431593], [2503886, 0.00431593], ...]
  55 +| 类型 | 数据范围 |
  56 +| --- | --- |
  57 +| `hot` | 最近窗口内的多行为加权结果 |
  58 +| `cart` | 加购、入池行为结果 |
  59 +| `new` | 最近上架商品结果 |
  60 +| `global` | 完整回看窗口内的多行为加权结果 |
105 61  
106   -# 方式2: 获取Python Swing结果(开发测试)
107   -similar_items = json.loads(r.get('item:similar:swing:12345'))
108   -# 返回: [[67890, 0.8567], [11223, 0.7234], [44556, 0.6891]]
  62 +`global` 是列表类型,不是自动生成的 dimension。因此现有生产器会生成 `interest:global:platform:essaone` 等 key,不会生成 `interest:global:global`。若业务需要真正的无条件全局兜底,必须在离线侧新增 `global` dimension 后再建立该契约。
109 63  
110   -# 获取Top5相似商品
111   -top_5 = similar_items[:5]
  64 +单维度:
112 65  
113   -# 多算法融合(可选)
114   -swing_cpp = json.loads(r.get('item:similar:swing_cpp:3600052') or '[]')
115   -swing_py = json.loads(r.get('item:similar:swing:3600052') or '[]')
116   -w2v = json.loads(r.get('item:similar:w2v:3600052') or '[]')
117   -# 融合多个算法结果...
  66 +```text
  67 +platform:{platform}
  68 +client_platform:{client_platform}
  69 +supplier:{supplier_id}
  70 +category_level1:{category_id}
  71 +category_level2:{category_id}
  72 +category_level3:{category_id}
  73 +category_level4:{category_id}
118 74 ```
119 75  
120   -### 2. 兴趣点聚合索引
  76 +组合维度:
121 77  
122   -#### 源数据格式
  78 +```text
  79 +platform_client:{platform}_{client_platform}
  80 +platform_category2:{platform}_{category_level2_id}
  81 +platform_category3:{platform}_{category_level3_id}
  82 +client_category2:{client_platform}_{category_level2_id}
  83 +platform:{platform};country_code:{country_code}
  84 +platform:{platform};country_code:{country_code};customer_type:{customer_type}
123 85 ```
124   -platform:pc 12345,67890,11223,44556,22334
125   -category_level2:200 67890,12345,22334,55667,11223
126   -```
127   -
128   -#### Redis存储
129 86  
130   -**Key**: `interest:hot:platform:pc`
  87 +国家及客户类型组合当前只为 `essa`、`essaone` 生成。具体数据来源和语义限制见 [新维度说明.md](./新维度说明.md)。
131 88  
132   -**Value** (JSON格式):
133   -```json
134   -[12345, 67890, 11223, 44556, 22334]
135   -```
  89 +兴趣索引同样保留 score:
136 90  
137   -**Value** (序列化后):
138   -```python
139   -import json
140   -value = json.dumps([12345, 67890, 11223, 44556, 22334])
141   -# 存储: "[12345,67890,11223,44556,22334]"
  91 +```text
  92 +Key: interest:hot:platform_category2:essaone_29
  93 +Value: 3482467:156.2000,2708138:143.0000,1008982:132.5000
142 94 ```
143 95  
144   -#### 查询示例
145   -```python
146   -import redis
147   -import json
  96 +## 4. 标准解析
148 97  
149   -r = redis.Redis(host='localhost', port=6379, db=0)
150   -
151   -# 获取PC平台的热门商品
152   -hot_items = json.loads(r.get('interest:hot:platform:pc'))
153   -# 返回: [12345, 67890, 11223, 44556, 22334]
154   -
155   -# 获取Top10热门商品
156   -top_10 = hot_items[:10]
157   -```
158   -
159   -## 🔄 数据加载流程
160   -
161   -### 1. 加载i2i索引
162   -
163   -#### 1.1 加载C++ Swing索引(无商品名)
  98 +仅消费当前契约时可使用:
164 99  
165 100 ```python
166   -def load_cpp_swing_index(file_path, redis_client, expire_seconds=5184000):
167   - """
168   - 加载C++ Swing索引到Redis
169   -
170   - Args:
171   - file_path: 索引文件路径(collaboration/output/swing_similar.txt)
172   - redis_client: Redis客户端
173   - expire_seconds: 过期时间(秒),默认60天
174   - """
175   - import json
176   -
177   - count = 0
178   - with open(file_path, 'r', encoding='utf-8') as f:
179   - for line in f:
180   - parts = line.strip().split('\t')
181   - if len(parts) < 2:
182   - continue
183   -
184   - item_id = parts[0]
185   - similar_str = parts[1] # similar_id1:score1,similar_id2:score2,...
186   -
187   - # 解析相似商品
188   - similar_items = []
189   - for pair in similar_str.split(','):
190   - if ':' in pair:
191   - sim_id, score = pair.split(':')
192   - similar_items.append([int(sim_id), float(score)])
193   -
194   - # 存储到Redis
195   - redis_key = f"item:similar:swing_cpp:{item_id}"
196   - redis_value = json.dumps(similar_items)
197   -
198   - redis_client.set(redis_key, redis_value)
199   - redis_client.expire(redis_key, expire_seconds)
200   -
201   - count += 1
202   -
203   - return count
204   -```
205   -
206   -#### 1.2 加载Python i2i索引(含商品名)
  101 +def parse_ranked_value(value):
  102 + if not value:
  103 + return []
  104 + if isinstance(value, bytes):
  105 + value = value.decode('utf-8')
  106 +
  107 + result = []
  108 + for token in value.split(','):
  109 + token = token.strip()
  110 + if not token or ':' not in token:
  111 + continue
  112 + item_id, score = token.rsplit(':', 1)
  113 + try:
  114 + result.append((item_id, float(score)))
  115 + except ValueError:
  116 + continue
  117 + return result
  118 +```
  119 +
  120 +需要兼容历史 JSON 格式时,统一调用:
207 121  
208 122 ```python
209   -def load_i2i_index(file_path, algorithm_name, redis_client, expire_seconds=5184000):
210   - """
211   - 加载Python i2i相似度索引到Redis
212   -
213   - Args:
214   - file_path: 索引文件路径
215   - algorithm_name: 算法名称(swing, w2v, deepwalk, content)
216   - redis_client: Redis客户端
217   - expire_seconds: 过期时间(秒),默认60天
218   - """
219   - import json
220   -
221   - count = 0
222   - with open(file_path, 'r', encoding='utf-8') as f:
223   - for line in f:
224   - parts = line.strip().split('\t')
225   - if len(parts) < 3:
226   - continue
227   -
228   - item_id = parts[0]
229   - # item_name = parts[1] # 可选:如果需要缓存商品名
230   - similar_str = parts[2] # similar_id1:score1,similar_id2:score2,...
231   -
232   - # 解析相似商品
233   - similar_items = []
234   - for pair in similar_str.split(','):
235   - if ':' in pair:
236   - sim_id, score = pair.split(':')
237   - similar_items.append([int(sim_id), float(score)])
238   -
239   - # 存储到Redis
240   - redis_key = f"item:similar:{algorithm_name}:{item_id}"
241   - redis_value = json.dumps(similar_items)
242   -
243   - redis_client.set(redis_key, redis_value)
244   - redis_client.expire(redis_key, expire_seconds)
245   -
246   - count += 1
247   -
248   - return count
249   -```
250   -
251   -### 2. 加载兴趣聚合索引
  123 +from agent_tools.parsing import parse_ranked_items
252 124  
253   -```python
254   -def load_interest_index(file_path, list_type, redis_client, expire_seconds=5184000):
255   - """
256   - 加载兴趣点聚合索引到Redis
257   -
258   - Args:
259   - file_path: 索引文件路径
260   - list_type: 列表类型(hot, cart, new, global)
261   - redis_client: Redis客户端
262   - expire_seconds: 过期时间(秒),默认60天
263   - """
264   - import json
265   -
266   - count = 0
267   - with open(file_path, 'r', encoding='utf-8') as f:
268   - for line in f:
269   - parts = line.strip().split('\t')
270   - if len(parts) != 2:
271   - continue
272   -
273   - dimension_key = parts[0] # platform:pc
274   - item_ids_str = parts[1] # 12345,67890,11223,...
275   -
276   - # 解析商品ID列表
277   - item_ids = [int(item_id) for item_id in item_ids_str.split(',')]
278   -
279   - # 存储到Redis
280   - redis_key = f"interest:{list_type}:{dimension_key}"
281   - redis_value = json.dumps(item_ids)
282   -
283   - redis_client.set(redis_key, redis_value)
284   - redis_client.expire(redis_key, expire_seconds)
285   -
286   - count += 1
287   -
288   - return count
  125 +items = parse_ranked_items(redis_client.get(key))
289 126 ```
290 127  
291   -## 🚀 快速加载命令
292   -
293   -### 加载所有索引
294   -```bash
295   -cd /home/tw/recommendation/offline_tasks
296   -
297   -# 加载所有索引(使用今天的数据,包括C++ Swing)
298   -python3 scripts/load_index_to_redis.py --redis-host localhost --redis-port 6379
299   -
300   -# 加载指定日期的索引
301   -python3 scripts/load_index_to_redis.py --date 20251016 --redis-host localhost
  128 +不要在每个在线召回分支各写一套解析逻辑。
302 129  
303   -# 只加载i2i索引(包括C++ Swing)
304   -python3 scripts/load_index_to_redis.py --load-i2i --redis-host localhost
  130 +## 5. 加载与验证
305 131  
306   -# 只加载C++ Swing索引
307   -python3 scripts/load_index_to_redis.py \
308   - --file collaboration/output/swing_similar.txt \
309   - --algorithm swing_cpp \
310   - --redis-host localhost
311   -
312   -# 只加载兴趣聚合索引
313   -python3 scripts/load_index_to_redis.py --load-interest --redis-host localhost
314   -```
  132 +加载指定日期的全部索引:
315 133  
316   -### 验证数据
317 134 ```bash
318   -# 连接Redis
319   -redis-cli
320   -
321   -# 检查key数量
322   -DBSIZE
323   -
324   -# 查看某个商品的相似推荐(C++ Swing)
325   -GET item:similar:swing_cpp:3600052
326   -
327   -# 查看某个商品的相似推荐(Python Swing)
328   -GET item:similar:swing:12345
  135 +cd offline_tasks
  136 +python3 scripts/load_index_to_redis.py --date YYYYMMDD
  137 +```
329 138  
330   -# 查看平台热门商品
331   -GET interest:hot:platform:pc
  139 +该命令会连接外部服务并写 Redis。执行前必须确认 `config/offline_config.py` 或显式参数中的目标地址、数据库、TTL 和日期。不要为了加载新数据执行 `--flush-db`,除非已确认整个目标数据库都可删除。
332 140  
333   -# 查看所有i2i相关的key
334   -KEYS item:similar:*
  141 +在线抽样:
335 142  
336   -# 查看C++ Swing的key
337   -KEYS item:similar:swing_cpp:*
  143 +```bash
  144 +redis-cli --scan --pattern 'item:similar:swing:*' | head
  145 +redis-cli --scan --pattern 'interest:hot:platform:*' | head
  146 +redis-cli GET 'item:similar:swing:3141390'
  147 +redis-cli TTL 'item:similar:swing:3141390'
  148 +```
338 149  
339   -# 查看Python Swing的key
340   -KEYS item:similar:swing:*
  150 +认证信息通过 `REDISCLI_AUTH` 或安全的凭据注入方式传递,不要写入命令历史、脚本或文档。
341 151  
342   -# 查看所有interest相关的key
343   -KEYS interest:*
  152 +建议按索引族记录以下指标,而不是依赖文档中的静态数量:
344 153  
345   -# 检查key的过期时间
346   -TTL item:similar:swing_cpp:3600052
347   -TTL item:similar:swing:12345
348   -```
  154 +- 生成文件行数、合法行比例和空 value 比例;
  155 +- Redis 写入成功数、跳过数和 TTL;
  156 +- key 覆盖商品数、每个 key 的候选数量分布;
  157 +- 抽样解析成功率和候选商品实时可售率;
  158 +- 在线每路 hit rate、召回候选数和延迟。
349 159  
350   -## 📊 数据统计
351   -
352   -### Redis内存占用估算
353   -
354   -| 索引类型 | Key数量 | 单条Value大小 | 总内存 |
355   -|---------|--------|-------------|--------|
356   -| i2i_swing_cpp | 50,000 | ~400B | ~20MB |
357   -| i2i_swing | 50,000 | ~500B | ~25MB |
358   -| i2i_w2v | 50,000 | ~500B | ~25MB |
359   -| i2i_deepwalk | 50,000 | ~500B | ~25MB |
360   -| i2i_content_name | 50,000 | ~500B | ~25MB |
361   -| i2i_content_pic | 50,000 | ~500B | ~25MB |
362   -| interest_hot | 10,000 | ~1KB | ~10MB |
363   -| interest_cart | 10,000 | ~1KB | ~10MB |
364   -| interest_new | 5,000 | ~1KB | ~5MB |
365   -| interest_global | 10,000 | ~1KB | ~10MB |
366   -| **总计** | **320,000** | - | **~180MB** |
367   -
368   -**说明**:
369   -- C++ Swing数据更紧凑(无商品名),单条大小约400B
370   -- 建议生产环境使用C++ Swing (`swing_cpp`),性能更优
371   -- Python Swing可作为对照组或特殊场景使用
372   -
373   -### 过期策略
374   -
375   -| 索引类型 | TTL | 原因 |
376   -|---------|-----|------|
377   -| i2i行为相似 | 60天 | 用户行为模式相对稳定,延长缓存时间 |
378   -| i2i内容相似 | 800天 | 商品属性变化极慢,可以长期保留 |
379   -| 热门/加购 | 60天 | 热度变化相对稳定,延长缓存时间 |
380   -| 新品 | 60天 | 新品推荐周期延长 |
381   -| 全局热门 | 60天 | 相对稳定,延长缓存时间 |
382   -
383   -## ⚠️ 注意事项
384   -
385   -1. **原子性**: 使用Pipeline批量写入,提高性能
386   -2. **过期时间**: 合理设置TTL,避免过期数据
387   -3. **内存管理**: 定期清理过期key,监控内存使用
388   -4. **数据版本**: 使用日期标记,支持数据回滚
389   -5. **容错处理**: 加载失败时不影响线上服务
390   -6. **监控告警**: 监控加载成功率、Redis内存、查询延迟
391   -
392   -## 🔍 监控指标
393   -
394   -### 数据质量指标
395   -```python
396   -# 检查加载成功率
397   -total_keys = redis_client.dbsize()
398   -expected_keys = 320000 # 更新:包含C++ Swing
399   -success_rate = total_keys / expected_keys * 100
400   -
401   -# 检查数据完整性
402   -sample_keys = [
403   - 'item:similar:swing_cpp:3600052', # C++ Swing
404   - 'item:similar:swing:12345', # Python Swing
405   - 'item:similar:w2v:12345',
406   - 'interest:hot:platform:pc'
407   -]
408   -for key in sample_keys:
409   - if not redis_client.exists(key):
410   - print(f"Missing key: {key}")
411   -
412   -# 检查C++ Swing vs Python Swing覆盖率
413   -cpp_swing_count = len(redis_client.keys('item:similar:swing_cpp:*'))
414   -py_swing_count = len(redis_client.keys('item:similar:swing:*'))
415   -print(f"C++ Swing keys: {cpp_swing_count}")
416   -print(f"Python Swing keys: {py_swing_count}")
417   -```
  160 +## 6. 变更规则
418 161  
419   -### 性能指标
420   -- 加载耗时: < 5分钟
421   -- 内存占用: < 200MB
422   -- 查询延迟: < 1ms
423   -- 成功率: > 99%
  162 +以下任一变化都属于在线契约变更,必须同步修改加载器、读取器、测试和本文:
424 163  
425   -## 🔗 相关文档
  164 +- key 前缀或算法名;
  165 +- value 序列化格式;
  166 +- dimension key 的拼接方式;
  167 +- score 含义或排序方向;
  168 +- TTL、数据库或双写/迁移策略。
426 169  
427   -- **离线索引规范**: `OFFLINE_INDEX_SPEC.md`
428   -- **API接口文档**: `RECOMMENDATION_API.md`
429   -- **运维手册**: `OPERATIONS.md`
  170 +更新日期:2026-08-23。
... ...
offline_tasks/doc/在线召回Redis Key清单.md
1   -# 在线召回Redis Key完整清单
  1 +# 在线召回 Redis Key 清单
2 2  
3   -## 📊 Redis数据统计
  3 +本文给在线推荐服务和智能导购 Agent 提供可查询的 key 清单。序列化、TTL 和迁移规则以 [Redis数据规范.md](./Redis数据规范.md) 为准。
4 4  
5   -- **总Key数量**: 211,232 个
6   -- **数据库**: Redis DB 3 (port: 6479)
  5 +## I2I 召回
7 6  
8   ----
  7 +| key 模式 | 信号 | 典型用途 |
  8 +| --- | --- | --- |
  9 +| `item:similar:swing_cpp:{sku}` | 大规模共现 | 详情页、强行为种子 |
  10 +| `item:similar:swing:{sku}` | 时间感知共现 | 与 C++ Swing 互补 |
  11 +| `item:similar:session_w2v:{sku}` | 会话顺序 | 浏览路径相似 |
  12 +| `item:similar:deepwalk:{sku}` | 行为图邻近 | 跨路径扩展 |
  13 +| `item:similar:content_name:{sku}` | 名称向量 | 新品和行为冷启动 |
  14 +| `item:similar:content_pic:{sku}` | 图片向量 | 视觉相似 |
  15 +| `item:similar:item_behavior:{sku}` | 商品行为模式 | 行为侧补充 |
9 16  
10   -## 🔑 一、商品相似度索引(I2I Recall)
  17 +当前标准 Session W2V key 是 `session_w2v`。`item:similar:w2v:{sku}` 只作为历史存量的读取后备,不再写入。
11 18  
12   -用于"相似推荐"场景,根据用户点击的商品召回相似商品。
  19 +不要按“第一个非空算法即返回”的方式使用多路索引。各路覆盖范围不同,而且原始 score 不同量纲;应并行查询、按排名融合、去重,并保留来源供后续解释。
13 20  
14   -### 1. C++ Swing算法(高性能版本)
15   -**Key模式**: `item:similar:swing_cpp:{item_id}`
  21 +## 兴趣与画像维度召回
16 22  
17   -**数量**: 15,310 个
  23 +把下面的 `dimension_key` 拼到 `interest:{hot|cart|new|global}:` 后:
18 24  
19   -**示例**:
20   -```redis
21   -Key: item:similar:swing_cpp:3562865
22   -Value: "3605981:0.0209644,2526246:0.0209644,2348869:0.0209644"
23   -```
24   -
25   -**格式**: JSON字符串,`similar_id:score` 格式
26   -
27   -**用途**:
28   -- 详情页"相似推荐"
29   -- 基于用户点击历史的个性化推荐
30   -- 高性能生产环境推荐
31   -
32   ----
33   -
34   -### 2. Python Swing算法(标准版本)
35   -**Key模式**: `item:similar:swing:{item_id}`
36   -
37   -**数量**: 169,409 个
38   -
39   -**示例**:
40   -```redis
41   -Key: item:similar:swing:3141390
42   -Value: "3264320:1.2656,3264284:1.2656,3562128:0.4000,..."
43   -```
44   -
45   -**格式**: JSON字符串,`similar_id:score` 格式
46   -
47   -**用途**:
48   -- 详情页"看了又看"
49   -- 购物车"相关推荐"
50   -- 需要归一化分数的场景
51   -
52   ----
53   -
54   -### 3. Session W2V算法
55   -**Key模式**: `item:similar:session_w2v:{item_id}`
56   -
57   -**数量**: 26,503 个
58   -
59   -**示例**:
60   -```redis
61   -Key: item:similar:session_w2v:3402580
62   -Value: "商品序列相似度数据"
63   -```
64   -
65   -**用途**:
66   -- 基于用户会话序列的推荐
67   -- 捕捉用户的浏览路径
68   -- 补充Swing算法的不足
69   -
70   ----
71   -
72   -## 🎯 二、兴趣聚合索引(Interest Recall)
73   -
74   -用于"热门推荐"场景,根据用户兴趣维度召回相关商品。
75   -
76   -### 当前存在的兴趣聚合Key:
77   -
78   -#### 1. 平台维度
79   -```redis
80   -Key: interest:hot:platform:essaone
81   -Value: [3582462, 3582428, 3582384, ...] # 1000个商品
82   -```
83   -
84   -#### 2. 客户端平台维度
85   -```redis
86   -Key: interest:hot:client_platform:pc
87   -Value: [3582462, 3582428, 3582384, ...] # 1000个商品
88   -```
89   -
90   -#### 3. 平台+客户端组合维度
91   -```redis
92   -Key: interest:hot:platform_client:essaone_pc
93   -Value: [平台+客户端的组合热门商品]
94   -```
95   -
96   -#### 4. 一级分类维度
97   -```redis
98   -Key: interest:hot:category_level1:1
99   -Value: [一级分类的热门商品]
100   -```
101   -
102   -#### 5. 二级分类维度
103   -```redis
104   -Key: interest:hot:category_level2:29
105   -Value: [3482467, 2708138, 1008982, ...] # 1000个商品
106   -```
107   -
108   -#### 6. 三级分类维度
109   -```redis
110   -Key: interest:hot:category_level3:2040
111   -Value: [三级分类的热门商品]
112   -```
113   -
114   -#### 7. 四级分类维度
115   -```redis
116   -Key: interest:hot:category_level4:2040
117   -Value: [四级分类的热门商品]
118   -```
119   -
120   -#### 8. 平台+二级分类组合维度
121   -```redis
122   -Key: interest:hot:platform_category2:essaone_29
123   -Value: [260个商品]
124   -```
125   -
126   -#### 9. 平台+三级分类组合维度
127   -```redis
128   -Key: interest:hot:platform_category3:essaone_2040
129   -Value: [231个商品]
130   -```
131   -
132   -#### 10. 供应商维度
133   -```redis
134   -Key: interest:hot:supplier:24947
135   -Value: [1566197] # 1个商品
136   -```
137   -
138   ----
139   -
140   -## 📋 在线召回使用策略
141   -
142   -### 场景1: 详情页相似推荐
  25 +| dimension key | 前置输入 |
  26 +| --- | --- |
  27 +| `platform:{platform}` | 业务平台 |
  28 +| `client_platform:{client}` | 客户端 |
  29 +| `supplier:{supplier_id}` | 供应商偏好 |
  30 +| `category_level1:{id}` | 一级分类偏好 |
  31 +| `category_level2:{id}` | 二级分类偏好 |
  32 +| `category_level3:{id}` | 三级分类偏好 |
  33 +| `category_level4:{id}` | 四级分类偏好 |
  34 +| `platform_client:{platform}_{client}` | 平台和客户端 |
  35 +| `platform_category2:{platform}_{id}` | 平台和二级分类 |
  36 +| `platform_category3:{platform}_{id}` | 平台和三级分类 |
  37 +| `client_category2:{client}_{id}` | 客户端和二级分类 |
  38 +| `platform:{platform};country_code:{country}` | `essa`/`essaone` 的平台和国家 |
  39 +| `platform:{platform};country_code:{country};customer_type:{type}` | `essa`/`essaone` 的平台、国家和客户类型 |
143 40  
144   -**召回Key**:
145   -```python
146   -# 根据当前浏览的商品ID
147   -item_id = request.sku_id
  41 +召回时优先查询信息更完整的组合维度,同时保留单维度作为回退。例如:
148 42  
149   -recall_keys = [
150   - f"item:similar:swing_cpp:{item_id}", # 优先使用高性能版本
151   - f"item:similar:swing:{item_id}", # 降级使用
152   - f"item:similar:session_w2v:{item_id}", # 补充推荐
153   -]
  43 +```text
  44 +interest:hot:platform_category2:essaone_29
  45 +interest:hot:category_level2:29
  46 +interest:hot:platform:essaone
154 47 ```
155 48  
156   -**召回流程**:
157   -1. 优先查询 `swing_cpp`(C++高性能版本)
158   -2. 如果没有结果,查询 `swing`(Python标准版本)
159   -3. 如果还没结果,查询 `session_w2v`(会话序列版本)
160   -4. 最终结果融合多个算法的相似商品
  49 +“回退”是查询更宽泛且真实存在的 key,不能用字符串替换猜测父分类 ID。二级分类 ID 与一级分类 ID 通常不同,必须从商品目录或分类树取得正确父级 ID。
161 50  
162   ----
  51 +## 当前没有的索引契约
163 52  
164   -### 场景2: 首页热门推荐
  53 +- 没有品牌维度生产逻辑,因此 `interest:hot:{brand_id}` 不是有效的品牌 key。
  54 +- 没有无条件 `global` dimension,因此 `interest:global:global` 当前不会产出。
  55 +- `tag_category_similar_*.txt` 目前是离线文件,没有由 `load_index_to_redis.py` 加载成在线 key。
165 56  
166   -**召回Key**:
167   -```python
168   -# 根据用户特征和上下文
169   -user_profile = get_user_profile(user_id)
170   -context = request.context # {platform, client, category, ...}
  57 +在线服务如果依赖上述能力,必须先补离线生产与加载契约,不能仅在调用侧拼 key。
171 58  
172   -recall_keys = []
  59 +## Agent 推荐调用
173 60  
174   -# 1. 组合维度推荐(最精准)
175   -if context.get('platform') and context.get('category_level2'):
176   - recall_keys.append(
177   - f"interest:hot:platform_category2:{context['platform']}_{context['category_level2']}"
178   - )
  61 +新工具层位于 `offline_tasks/agent_tools/`,提供:
179 62  
180   -# 2. 单一分类维度
181   -if context.get('category_level2'):
182   - recall_keys.append(f"interest:hot:category_level2:{context['category_level2']}")
  63 +1. `recommendation_capabilities`:发现算法、维度和 key 语义;
  64 +2. `resolve_recommendation_dimension`:把分类或供应商名称映射为内部 ID;
  65 +3. `recall_similar_products`:多种 I2I 索引融合;
  66 +4. `recall_products_by_dimensions`:组合维度优先、单维度回退;
  67 +5. `build_recommendation_candidates`:融合协同与画像候选。
183 68  
184   -# 3. 平台维度
185   -if context.get('platform'):
186   - recall_keys.append(f"interest:hot:platform:{context['platform']}")
  69 +工具输出中的 `score` 是当前调用内归一化后的融合分,不等于任一离线算法原始 score。`evidence` 会保留实际命中的 key、排名、原始 score、种子或画像维度。
187 70  
188   -# 4. 客户端平台维度
189   -if context.get('client'):
190   - recall_keys.append(f"interest:hot:client_platform:{context['client']}")
  71 +推荐链路应为:
191 72  
192   -# 5. 全局热门(兜底)
193   -recall_keys.append("interest:hot:platform:essaone") # 全局热门
  73 +```text
  74 +公共知识 + 用户画像
  75 + -> 推导少量高置信种子和维度
  76 + -> 协同/维度工具生成高召回候选
  77 + -> 商品目录工具检查名称、类目、价格、库存、可售与合规
  78 + -> LLM 比较并输出最终推荐及理由
194 79 ```
195 80  
196   -**召回优先级**:
197   -1. 组合维度(如 platform_category2) - 最精准
198   -2. 分类维度(category_level2/3/4)
199   -3. 平台维度(platform)
200   -4. 全局热门 - 兜底策略
  81 +协同索引不能替代实时商品校验。已购买、已曝光或业务禁止的商品应通过 `exclude_item_ids` 尽早排除,最终候选仍需经过实时目录过滤。
201 82  
202   ----
  83 +## 在线核验
203 84  
204   -### 场景3: 用户点击历史推荐
  85 +不要在生产 Redis 使用 `KEYS` 做全量统计。使用增量 `SCAN`:
205 86  
206   -**召回Key**:
207   -```python
208   -# 根据用户点击的商品列表
209   -clicked_items = [3141390, 3141390, 3606104, 3606102, ...]
210   -
211   -all_recalled_items = []
212   -
213   -for item_id in clicked_items:
214   - # 查询相似商品
215   - similar_items = redis.get(f"item:similar:swing_cpp:{item_id}")
216   - if not similar_items:
217   - similar_items = redis.get(f"item:similar:swing:{item_id}")
218   -
219   - all_recalled_items.extend(similar_items)
220   -
221   -# 去重并排序
222   -final_items = deduplicate_and_rank(all_recalled_items)
223   -```
224   -
225   ----
226   -
227   -### 场景4: 类别偏好推荐
228   -
229   -**召回Key**:
230   -```python
231   -# 根据用户收藏的类别
232   -collected_categories = [1541, 137, 153, 1561, 1689, 1691]
233   -
234   -recall_keys = []
235   -
236   -for cat_id in collected_categories:
237   - # 查询该类别的热门商品
238   - category_key = f"interest:hot:category_level2:{cat_id}"
239   - recall_keys.append(category_key)
240   -
241   -# 批量查询
242   -hot_items = redis.mget(recall_keys)
243   -```
244   -
245   ----
246   -
247   -## ⚠️ 注意事项
248   -
249   -### 1. Key存在性检查
250   -```python
251   -def safe_get_recall(key):
252   - """安全获取召回数据,带降级策略"""
253   - result = redis.get(key)
254   - if not result:
255   - # 降级策略:使用更通用的key
256   - if ":category_level2:" in key:
257   - # 尝试用更高级别的分类
258   - fallback_key = key.replace("category_level2", "category_level1")
259   - result = redis.get(fallback_key)
260   - elif "platform_category" in key:
261   - # 尝试单独的平台或分类
262   - result = redis.get(key.replace("platform_category2:", "category_level2:"))
263   -
264   - return result or []
265   -```
266   -
267   -### 2. 数据格式
268   -- **I2I数据**: JSON字符串,格式为 `"item_id1:score1,item_id2:score2"`
269   -- **Interest数据**: JSON数组,格式为 `[item_id1, item_id2, ...]`
270   -
271   -### 3. 解析方法
272   -```python
273   -import json
274   -
275   -# I2I数据解析
276   -def parse_i2i_data(value):
277   - items = []
278   - for pair in value.split(','):
279   - if ':' in pair:
280   - item_id, score = pair.split(':')
281   - items.append([int(item_id), float(score)])
282   - return items
283   -
284   -# Interest数据解析
285   -def parse_interest_data(value):
286   - return json.loads(value)
287   -```
288   -
289   -### 4. 推荐数量
290   -- 每个相似推荐key通常包含10-50个商品
291   -- 每个兴趣聚合key通常包含100-1000个商品
292   -- 最终推荐数量建议:取Top 20-50个商品
293   -
294   ----
295   -
296   -## 📊 Key覆盖率统计
297   -
298   -| Key类型 | 数量 | 覆盖率 | 使用优先级 |
299   -|---------|------|--------|-----------|
300   -| item:similar:swing | 170,116 | ~80% | ⭐⭐⭐⭐⭐ |
301   -| item:similar:content_name | 129,103 | ~70% | ⭐⭐⭐⭐ |
302   -| item:similar:session_w2v | 52,339 | ~30% | ⭐⭐⭐ |
303   -| item:similar:deepwalk | 49,052 | ~30% | ⭐⭐⭐ |
304   -| item:similar:swing_cpp | 15,310 | ~10% | ⭐⭐⭐⭐⭐ |
305   -| item:similar:content_pic | 12,118 | ~7% | ⭐⭐ |
306   -| interest:hot:* | 10 | ~5% | ⭐⭐ |
307   -
308   -**说明**:
309   -- Swing覆盖商品约10万+,应优先使用
310   -- 兴趣聚合数据较少,建议作为补充召回策略
311   -
312   ----
313   -
314   -## 🔧 修复建议
315   -
316   -### 缺失的关键数据:
317   -1. **DeepWalk索引**: `item:similar:deepwalk:{item_id}` - 缺失
318   -2. **内容相似度**: `item:similar:content_name:{item_id}` - 缺失
319   -3. **图片相似度**: `item:similar:content_pic:{item_id}` - 缺失
320   -4. **更多兴趣聚合维度**:
321   - - `interest:hot:category_level2:{id}` - 缺失(1541, 137, 153等)
322   - - `interest:cart:*` - 缺失
323   - - `interest:new:*` - 缺失
324   - - `interest:global:*` - 缺失
325   -
326   -### 建议操作:
327 87 ```bash
328   -# 1. 运行兴趣聚合任务生成更多维度数据
329   -cd /home/tw/recommendation/offline_tasks
330   -python3 scripts/interest_aggregation.py
331   -
332   -# 2. 加载更多兴趣聚合数据到Redis
333   -python3 scripts/load_index_to_redis.py --load-interest
334   -
335   -# 3. 定期更新数据(每天)
336   -crontab -e
337   -# 添加: 0 3 * * * /home/tw/recommendation/offline_tasks/update_indices.sh
  88 +redis-cli --scan --pattern 'item:similar:swing_cpp:*' | head
  89 +redis-cli --scan --pattern 'item:similar:session_w2v:*' | head
  90 +redis-cli --scan --pattern 'interest:hot:platform:*' | head
338 91 ```
339 92  
340   ----
341   -
342   -## 📞 使用示例
343   -
344   -### Python召回示例
345   -
346   -```python
347   -import redis
348   -import json
349   -
350   -redis_client = redis.Redis(
351   - host='localhost',
352   - port=6479,
353   - db=3,
354   - password='BMfv5aI31kgHWtlx',
355   - decode_responses=True
356   -)
357   -
358   -def recall_similar_items(item_id):
359   - """召回相似商品"""
360   - # 按优先级查询
361   - keys = [
362   - f"item:similar:swing_cpp:{item_id}",
363   - f"item:similar:swing:{item_id}",
364   - f"item:similar:session_w2v:{item_id}"
365   - ]
366   -
367   - for key in keys:
368   - value = redis_client.get(key)
369   - if value:
370   - # 解析数据
371   - items = []
372   - for pair in value.split(','):
373   - if ':' in pair:
374   - similar_id, score = pair.split(':')
375   - items.append([int(similar_id), float(score)])
376   - return items
377   -
378   - return []
379   -
380   -def recall_hot_items(platform, category_level2):
381   - """召回热门商品"""
382   - key = f"interest:hot:platform_category2:{platform}_{category_level2}"
383   - value = redis_client.get(key)
384   -
385   - if value:
386   - return json.loads(value)
387   -
388   - # 降级策略
389   - category_key = f"interest:hot:category_level2:{category_level2}"
390   - value = redis_client.get(category_key)
391   - if value:
392   - return json.loads(value)
393   -
394   - # 最终降级:全局热门
395   - global_key = f"interest:hot:platform:{platform}"
396   - value = redis_client.get(global_key)
397   - if value:
398   - return json.loads(value)
399   -
400   - return []
401   -```
402   -
403   ----
404   -
405   -## 🎯 总结
406   -
407   -**当前Redis中有数据的Key类型**:
408   -1. ✅ `item:similar:swing:{item_id}` - 170,116个
409   -2. ✅ `item:similar:content_name:{item_id}` - 129,103个
410   -3. ✅ `item:similar:session_w2v:{item_id}` - 52,339个
411   -4. ✅ `item:similar:deepwalk:{item_id}` - 49,052个
412   -5. ✅ `item:similar:swing_cpp:{item_id}` - 15,310个
413   -6. ✅ `item:similar:content_pic:{item_id}` - 12,118个
414   -7. ✅ `interest:hot:platform:{platform}` - 1个
415   -8. ✅ `interest:hot:client_platform:{client}` - 1个
416   -9. ✅ `interest:hot:platform_client:{platform}_{client}` - 1个
417   -10. ✅ `interest:hot:category_level1:{id}` - 1个
418   -11. ✅ `interest:hot:category_level2:{id}` - 1个
419   -12. ✅ `interest:hot:category_level3:{id}` - 1个
420   -13. ✅ `interest:hot:category_level4:{id}` - 1个
421   -14. ✅ `interest:hot:platform_category2:{platform}_{id}` - 1个
422   -15. ✅ `interest:hot:platform_category3:{platform}_{id}` - 1个
423   -16. ✅ `interest:hot:supplier:{id}` - 1个
424   -
425   -**缺失但应该有的Key**:
426   -- ❌ 更多类别的 `interest:hot:category_level2:{id}`
427   -- ❌ `interest:cart:*` (加购热门)
428   -- ❌ `interest:new:*` (新品)
429   -- ❌ `interest:global:*` (全局热门)
  93 +逐路至少监控:key 数、请求 hit rate、空结果率、解析失败率、平均候选数、P95 延迟、实时可售率。具体数量属于运行时状态,不写死在本清单中。
430 94  
431   -**建议**: 优先使用现有的高质量数据,同时尽快补充缺失的兴趣聚合数据。
  95 +更新日期:2026-08-23。
432 96  
... ...
offline_tasks/doc/新维度说明.md
1   -# 兴趣聚合新维度说明
  1 +# 国家与客户类型组合维度
2 2  
3   -## 📋 新增维度
  3 +`interest_aggregation.py` 为 `essa`、`essaone` 生成两类地域画像索引:
4 4  
5   -从2026年1月12日起,兴趣聚合索引新增以下维度:
6   -
7   -### 1. 平台 + 国家代码
8   -**格式**:`interest:{类型}:platform:{平台};country_code:{国家代码}`
9   -
10   -**示例**:
11   -- `interest:hot:platform:essa;country_code:US`
12   -- `interest:hot:platform:essaone;country_code:CN`
13   -- `interest:cart:platform:essa;country_code:GB`
14   -- `interest:new:platform:essaone;country_code:US`
15   -
16   -**适用平台**:仅 `essa` 和 `essaone`
17   -- ✅ essa:有国家维度
18   -- ✅ essaone:有国家维度
19   -- ❌ essabuy:无国家维度
20   -
21   -### 2. 平台 + 国家代码 + 客户类型
22   -**格式**:`interest:{类型}:platform:{平台};country_code:{国家代码};customer_type:{客户类型}`
23   -
24   -**示例**:
25   -- `interest:hot:platform:essa;country_code:US;customer_type:目标客户`
26   -- `interest:hot:platform:essaone;country_code:CN;customer_type:普通客户`
27   -- `interest:cart:platform:essa;country_code:GB;customer_type:VIP客户`
28   -
29   -**适用平台**:仅 `essa` 和 `essaone`
30   -- ✅ essa:有国家和客户类型维度
31   -- ✅ essaone:有国家和客户类型维度
32   -- ❌ essabuy:无这些维度
33   -
34   -## 🔍 数据来源
35   -
36   -新维度的数据通过以下方式获取:
37   -
38   -```sql
39   --- 通过sensors_events的login_id关联
40   -sensors_events.login_id -> buy_account.id
41   -buy_account.buyer_id -> buy_buyer.id
42   -buy_buyer.id -> buy_buyer_extend.buyer_id
43   -
44   --- 获取国家代码
45   -buy_buyer_extend_option.code = 'country_code'
46   --> pub_dict_item.name (例如: US, CN, GB)
47   -
48   --- 获取客户类型
49   -buy_buyer_extend_option.code = 'customer_type'
50   --> pub_dict_item.name (例如: 目标客户, 普通客户, VIP客户)
  5 +```text
  6 +interest:{list_type}:platform:{platform};country_code:{country_code}
  7 +interest:{list_type}:platform:{platform};country_code:{country_code};customer_type:{customer_type}
51 8 ```
52 9  
53   -## 📊 索引类型(list_type)
54   -
55   -新维度适用于所有现有索引类型:
56   -
57   -1. **hot(热门)**:最近N天的热门商品
58   -2. **cart(加购)**:加购行为商品
59   -3. **new(新品)**:新上架商品
60   -4. **global(全局)**:所有历史数据聚合
61   -
62   -## 💡 使用示例
63   -
64   -### Redis查询
  10 +`list_type` 可以是 `hot`、`cart`、`new`、`global`。`essabuy` 当前不会生成这两类组合维度。
65 11  
66   -```bash
67   -# 查询essa平台美国的热门商品
68   -redis-cli -h localhost -p 6479 -a "BMfv5aI31kgHWtlx" GET "interest:hot:platform:essa;country_code:US"
69   -
70   -# 查询essaone平台中国目标客户的热门商品
71   -redis-cli -h localhost -p 6479 -a "BMfv5aI31kgHWtlx" GET "interest:hot:platform:essaone;country_code:CN;customer_type:目标客户"
  12 +## 当前数据来源
72 13  
73   -# 查询所有包含国家代码的hot索引
74   -redis-cli -h localhost -p 6479 -a "BMfv5aI31kgHWtlx" KEYS "interest:hot:platform:*;country_code:*"
  14 +权威来源是 `scripts/interest_aggregation.py` 中的 SQL 和聚合逻辑:
75 15  
76   -# 查询所有包含国家和客户类型的hot索引
77   -redis-cli -h localhost -p 6479 -a "BMfv5aI31kgHWtlx" KEYS "interest:hot:platform:*;country_code:*;customer_type:*"
  16 +```text
  17 +sensors_events.login_id
  18 + -> buy_account.id
  19 + -> buy_buyer.id
  20 + -> buy_buyer_extend.buyer_id
  21 + -> buy_buyer_extend_option.buyer_extend_id
78 22 ```
79 23  
80   -### 输出文件查询
  24 +字段映射:
81 25  
82   -```bash
83   -# 查看生成的索引文件
84   -grep "platform:essa;country_code:" /data/tw/recommendation/offline_tasks/output/interest_aggregation_hot_20260112.txt
  26 +| 维度 | 当前字段 | 适用平台 |
  27 +| --- | --- | --- |
  28 +| `country_code` | `buy_buyer.countries` | `essa`、`essaone` |
  29 +| `customer_type` | `buy_buyer.sell_channel` | `essa` |
  30 +| `customer_type` | `buy_buyer_extend_option.code` | `essaone` |
85 31  
86   -# 查看特定平台和国家的索引
87   -grep "platform:essaone;country_code:CN" /data/tw/recommendation/offline_tasks/output/interest_aggregation_hot_20260112.txt
  32 +旧文档曾描述为通过 `pub_dict_item` 取得国家和客户类型名称,但当前 SQL 没有这些字典关联。调用方必须传索引中真实存在的内部值,不能根据展示名称自行猜测。
88 33  
89   -# 统计新维度数量
90   -grep -c "platform:essa;country_code:" /data/tw/recommendation/offline_tasks/output/interest_aggregation_hot_20260112.txt
91   -grep -c "platform:essaone;country_code:.*;customer_type:" /data/tw/recommendation/offline_tasks/output/interest_aggregation_hot_20260112.txt
92   -```
  34 +尤其要注意:`essaone` 的 `customer_type` 当前是扩展字段的 `code`,它描述的可能是画像属性名,不一定是“普通客户/VIP 客户”这样的业务枚举值。上线使用三维组合前应抽样检查 key 分布和业务含义;如果需要属性值维度,应先明确 `buy_buyer_extend_option` 的值字段并修改离线 SQL,不能只改在线 key。
93 35  
94   -## 🎯 完整的索引列表
  36 +## 产出示例
95 37  
96   -### essa平台
97   -```
98   -interest:hot:platform:essa
99   -interest:hot:platform:essa;country_code:{国家代码}
100   -interest:hot:platform:essa;country_code:{国家代码};customer_type:{客户类型}
  38 +```text
  39 +platform:essa;country_code:US 1001:150.5000,1002:145.2000
  40 +platform:essa;country_code:US;customer_type:retail 1001:85.3000,1006:72.1000
  41 +platform:essaone;country_code:344;customer_type:is_ka_buyer 2001:123.4000,2002:118.7000
101 42 ```
102 43  
103   -### essaone平台
104   -```
105   -interest:hot:platform:essaone
106   -interest:hot:platform:essaone;country_code:{国家代码}
107   -interest:hot:platform:essaone;country_code:{国家代码};customer_type:{客户类型}
108   -```
  44 +加载后:
109 45  
110   -### essabuy平台
  46 +```text
  47 +interest:hot:platform:essa;country_code:US
  48 +interest:hot:platform:essa;country_code:US;customer_type:retail
  49 +interest:hot:platform:essaone;country_code:344;customer_type:is_ka_buyer
111 50 ```
112   -interest:hot:platform:essabuy
113   -(无国家和客户类型维度)
114   -```
115   -
116   -## ⚙️ 代码修改
117 51  
118   -### 修改的文件
119   -- `/data/tw/recommendation/offline_tasks/scripts/interest_aggregation.py`
  52 +value 仍是 `item_id:score,...` 文本,不是 JSON。
120 53  
121   -### 备份文件
122   -- `/data/tw/recommendation/offline_tasks/scripts/interest_aggregation.py.backup`
  54 +## 查询与回退
123 55  
124   -### 主要修改内容
  56 +三维 key 未命中时依次回退到平台加国家、平台单维度;这些 key 可以独立查询和融合:
125 57  
126   -1. **SQL查询**(第268-312行)
127   - - 增加 `login_id` 字段
128   - - 增加 `country_code_pd.name AS country_code`
129   - - 增加 `customer_type_pd.name AS customer_type`
130   - - 新增6个LEFT JOIN关联表获取用户信息
131   -
132   -2. **聚合函数**(第142-156行)
133   - - 新增 `platform:{平台};country_code:{国家代码}` 维度
134   - - 新增 `platform:{平台};country_code:{国家代码};customer_type:{客户类型}` 维度
135   - - 限制只为essa和essaone平台生成这些维度
136   -
137   -## 📝 注意事项
138   -
139   -1. **数据完整性**
140   - - 如果用户没有login_id,country_code和customer_type将为NULL
141   - - 这些用户不会出现在新维度索引中
142   - - 但仍会出现在基础platform索引中
143   -
144   -2. **性能影响**
145   - - 新增了多个表关联,SQL查询时间可能增加
146   - - 建议监控查询性能,必要时添加索引
  58 +```text
  59 +interest:hot:platform:essaone;country_code:344;customer_type:is_ka_buyer
  60 +interest:hot:platform:essaone;country_code:344
  61 +interest:hot:platform:essaone
  62 +```
147 63  
148   -3. **索引数量**
149   - - 新维度会显著增加索引数量
150   - - 每个平台×每个国家×每个客户类型 = 一个索引
151   - - 请确保Redis有足够的存储空间
  64 +不要把 `essabuy` 拼入国家组合,也不要构造单独的 `country_code:{value}` 或 `customer_type:{value}`,当前生产器不生成这些 key。
152 65  
153   -4. **数据准确性**
154   - - country_code和customer_type依赖于buy_buyer_extend_option表的数据质量
155   - - 如果code字段不是'country_code'或'customer_type',将无法获取数据
  66 +## 数据质量检查
156 67  
157   -## 🚀 运行方式
  68 +运行离线任务后,至少检查:
158 69  
159 70 ```bash
160   -cd /data/tw/recommendation/offline_tasks
161   -
162   -# 标准运行(使用默认参数)
163   -python3 scripts/interest_aggregation.py
164   -
165   -# 调试模式(查看详细信息)
166   -python3 scripts/interest_aggregation.py --debug
167   -
168   -# 自定义参数
169   -python3 scripts/interest_aggregation.py \
170   - --lookback_days 730 \
171   - --top_n 1000 \
172   - --recent_days 180 \
173   - --debug
  71 +cut -f1 output/interest_aggregation_hot_YYYYMMDD.txt \
  72 + | rg '^platform:(essa|essaone);country_code:' \
  73 + | head
  74 +
  75 +cut -f1 output/interest_aggregation_hot_YYYYMMDD.txt \
  76 + | rg ';customer_type:' \
  77 + | sed 's/.*;customer_type://' \
  78 + | sort | uniq -c | sort -nr | head
174 79 ```
175 80  
176   -## 📈 预期结果
177   -
178   -运行后将在输出文件中看到类似内容:
  81 +需要查询线上 Redis 时使用 `SCAN`,认证信息通过安全环境变量注入:
179 82  
180   -```
181   -platform:essa;country_code:US 1001:150.5,1002:145.2,1003:138.9,...
182   -platform:essa;country_code:CN 1004:142.1,1005:139.8,...
183   -platform:essa;country_code:US;customer_type:目标客户 1001:85.3,1006:72.1,...
184   -platform:essaone;country_code:CN;customer_type:普通客户 2001:123.4,2002:118.7,...
185   -```
186   -
187   -在Redis中:
188 83 ```bash
189   -redis-cli -h localhost -p 6479 -a "BMfv5aI31kgHWtlx" KEYS "interest:*" | grep "country_code"
  84 +redis-cli --scan \
  85 + --pattern 'interest:hot:platform:*;country_code:*' \
  86 + | head
190 87 ```
191 88  
192   ----
193   -**更新日期**:2026-01-12
194   -**版本**:v2.0
  89 +监控项包括:有 login ID 的行为占比、国家非空率、平台对应客户字段非空率、每个组合 key 的商品数、异常 customer type 数量、候选实时可售率。
  90 +
  91 +更新日期:2026-08-23。
... ...
offline_tasks/doc/智能导购Agent工具集.md 0 → 100644
... ... @@ -0,0 +1,310 @@
  1 +# 智能导购 Agent 推荐工具集
  2 +
  3 +## 1. 目标与边界
  4 +
  5 +传统推荐索引擅长从真实行为中发现“用户共同选择了什么”,LLM 擅长理解自然语言需求、公共知识和画像语义。两者结合时,LLM 不应直接猜商品,也不应理解每一种 Redis key;它只负责提炼意图、选择工具、比较已补全的商品。
  6 +
  7 +本工具集把离线协同索引封装成稳定的候选生成层:
  8 +
  9 +```text
  10 +对话 + 公共知识 + 用户画像
  11 + -> LLM 提炼种子商品、分类、供应商、平台和地域偏好
  12 + -> Agent 推荐工具并行召回、融合、去重和解释
  13 + -> 商品目录/搜索工具补全名称、属性、价格、库存、可售和合规
  14 + -> LLM 重排并生成最终推荐理由
  15 +```
  16 +
  17 +工具层负责高召回候选,不负责以下实时事实:
  18 +
  19 +- 库存、价格、MOQ、配送范围和促销;
  20 +- 商品是否下架、屏蔽或对当前客户可见;
  21 +- 用户当前对话中的硬约束是否满足;
  22 +- 最终展示位的商业规则和合规判断。
  23 +
  24 +这些条件必须在 LLM 最终挑选前由权威商品工具校验。
  25 +
  26 +## 2. 已实现能力
  27 +
  28 +代码位于 `offline_tasks/agent_tools/`,提供框架无关的 JSON Schema 和 Python 调用接口。
  29 +
  30 +| Tool | 何时调用 | 主要输出 |
  31 +| --- | --- | --- |
  32 +| `recommendation_capabilities` | 首次接入或不确定支持哪些信号 | 算法、维度、key 语义、推荐流程 |
  33 +| `resolve_recommendation_dimension` | LLM 只知道分类或供应商名称 | 内部维度值候选和匹配类型 |
  34 +| `recall_similar_products` | 已有用户明确偏好的 SKU | 多种 I2I 算法融合候选 |
  35 +| `recall_products_by_dimensions` | 已有平台、分类、供应商、国家等画像 | 组合维度优先、单维度回退的候选 |
  36 +| `build_recommendation_candidates` | 常规智能导购候选生成 | 协同与画像两通道融合候选 |
  37 +
  38 +### 2.1 种子商品
  39 +
  40 +`seed_items` 最多 20 个。每个种子包含:
  41 +
  42 +```json
  43 +{
  44 + "item_id": "3385246",
  45 + "behavior": "purchase",
  46 + "reason": "用户过去采购过同类商品"
  47 +}
  48 +```
  49 +
  50 +支持 `click`、`view`、`addToPool`、`addToCart`、`contactFactory`、`purchase`。省略显式 `weight` 时分别使用与离线任务一致的行为强度;应用也可以传 `0 < weight <= 10` 覆盖。种子 SKU 会自动从结果中排除。
  51 +
  52 +### 2.2 维度兴趣
  53 +
  54 +`interests` 最多 30 个:
  55 +
  56 +```json
  57 +{
  58 + "dimension": "category_level2",
  59 + "value": "29",
  60 + "weight": 2.0,
  61 + "reason": "画像显示用户持续采购玩具车辆"
  62 +}
  63 +```
  64 +
  65 +`value` 必须是离线索引使用的内部值。只有自然语言名称时,先调用 `resolve_recommendation_dimension`;若字典没有命中,应从商品搜索或分类树工具取得内部 ID,不能让 LLM 猜 ID。
  66 +
  67 +`context` 用于当前请求环境:
  68 +
  69 +```json
  70 +{
  71 + "platform": "essaone",
  72 + "client_platform": "pc",
  73 + "country_code": "344",
  74 + "customer_type": "is_ka_buyer"
  75 +}
  76 +```
  77 +
  78 +工具会自动规划 `platform_category2`、`client_category2`、平台国家客户类型等组合 key,同时查询更宽泛的单维度。具体可用 key 见 [在线召回Redis Key清单.md](./在线召回Redis%20Key清单.md)。
  79 +
  80 +## 3. 排名与解释
  81 +
  82 +### 3.1 路内融合
  83 +
  84 +Swing、W2V、DeepWalk、向量相似和兴趣聚合的原始 score 量纲不同。直接相加会让数值范围大的算法支配结果,因此工具使用加权 Reciprocal Rank Fusion:
  85 +
  86 +```text
  87 +contribution = source_weight / (rrf_k + rank)
  88 +candidate_score = sum(contribution)
  89 +```
  90 +
  91 +默认 `rrf_k=60`。算法权重、种子行为权重、画像兴趣权重、组合维度特异性和列表类型共同决定 `source_weight`。同一商品被多个独立信号命中时会自然获得共识增益。
  92 +
  93 +每一路融合后把本次调用的最高分归一化为 1。这个 `score` 只能在同一次工具调用内比较,不是点击率或购买概率。
  94 +
  95 +### 3.2 两通道融合
  96 +
  97 +`build_recommendation_candidates` 默认使用:
  98 +
  99 +```text
  100 +0.65 * collaborative_score + 0.35 * dimension_score
  101 +```
  102 +
  103 +如果某一路没有候选,权重会在成功通道之间重新归一化,避免可用结果被无效通道无故压低。调用方可按实验配置调整两个权重,但不应根据单次对话随意改变离线算法内部权重。
  104 +
  105 +### 3.3 证据
  106 +
  107 +候选示例:
  108 +
  109 +```json
  110 +{
  111 + "item_id": "300",
  112 + "score": 1.0,
  113 + "channels": ["collaborative", "dimension"],
  114 + "source_count": 3,
  115 + "reasons": [
  116 + {
  117 + "type": "similar_to_seed",
  118 + "seed_item_id": "100",
  119 + "algorithms": ["swing", "session_w2v"]
  120 + },
  121 + {
  122 + "type": "matched_dimension",
  123 + "dimension_key": "platform_category2:essaone_29",
  124 + "list_types": ["hot"]
  125 + }
  126 + ],
  127 + "evidence": [
  128 + {
  129 + "channel": "collaborative",
  130 + "source": "swing",
  131 + "key": "item:similar:swing:100",
  132 + "rank": 1,
  133 + "raw_score": 0.91,
  134 + "contribution": 0.01557377
  135 + }
  136 + ]
  137 +}
  138 +```
  139 +
  140 +LLM 可以把 `reasons` 转成用户可理解的推荐依据,但不能把“相似/热门”虚构成商品属性。属性描述必须来自后续商品详情工具。
  141 +
  142 +## 4. 运行方式
  143 +
  144 +### 4.1 生成维度字典
  145 +
  146 +正常运行 `fetch_item_attributes.py` 时会额外生成:
  147 +
  148 +```text
  149 +output/agent_dimension_catalog.json
  150 +```
  151 +
  152 +它只包含分类、供应商、平台和客户端映射,不包含约 300 万商品名称,适合在线进程加载。该文件是生成数据,保持在 `.gitignore` 中并随离线任务更新。
  153 +
  154 +### 4.2 列出工具 schema
  155 +
  156 +```bash
  157 +cd offline_tasks
  158 +python3 scripts/agent_recommendation_tools.py list-tools
  159 +```
  160 +
  161 +输出可直接注册到支持 JSON Schema function tools 的 Agent 框架。
  162 +
  163 +### 4.3 配置 Redis
  164 +
  165 +工具不读取仓库中的明文连接配置。使用以下环境变量之一:
  166 +
  167 +```text
  168 +RECOMMENDATION_REDIS_URL
  169 +```
  170 +
  171 +或:
  172 +
  173 +```text
  174 +RECOMMENDATION_REDIS_HOST
  175 +RECOMMENDATION_REDIS_PORT
  176 +RECOMMENDATION_REDIS_DB
  177 +RECOMMENDATION_REDIS_PASSWORD
  178 +RECOMMENDATION_DIMENSION_CATALOG
  179 +```
  180 +
  181 +不要把密码写进 tool arguments、日志、文档或模型上下文。
  182 +
  183 +### 4.4 单次调用
  184 +
  185 +```bash
  186 +python3 scripts/agent_recommendation_tools.py call \
  187 + build_recommendation_candidates \
  188 + --arguments '{
  189 + "seed_items":[{"item_id":"3385246","behavior":"click"}],
  190 + "context":{"platform":"essaone","client_platform":"pc"},
  191 + "interests":[{"dimension":"category_level2","value":"29","weight":2}],
  192 + "exclude_item_ids":["3385246"],
  193 + "top_k":30
  194 + }'
  195 +```
  196 +
  197 +### 4.5 长驻 stdio
  198 +
  199 +```bash
  200 +python3 scripts/agent_recommendation_tools.py serve-stdio
  201 +```
  202 +
  203 +每行一个请求:
  204 +
  205 +```json
  206 +{"id":"req-1","tool":"recall_similar_products","arguments":{"seed_items":[{"item_id":"3385246"}]}}
  207 +```
  208 +
  209 +每行一个响应:
  210 +
  211 +```json
  212 +{"id":"req-1","result":{"ok":true,"items":[],"diagnostics":{}}}
  213 +```
  214 +
  215 +这不是特定厂商协议;可由现有 Agent 网关包装成 MCP、HTTP 或框架原生 Tool。
  216 +
  217 +### 4.6 Python 集成
  218 +
  219 +```python
  220 +import redis
  221 +
  222 +from offline_tasks.agent_tools import (
  223 + DimensionCatalog, RecommendationAgentTools, RedisIndexStore,
  224 +)
  225 +
  226 +redis_client = redis.Redis(
  227 + host=redis_host,
  228 + port=redis_port,
  229 + db=redis_db,
  230 + password=redis_password,
  231 + decode_responses=True,
  232 +)
  233 +catalog = DimensionCatalog.from_file('output/agent_dimension_catalog.json')
  234 +tools = RecommendationAgentTools(RedisIndexStore(redis_client), catalog)
  235 +
  236 +tool_definitions = tools.tool_definitions()
  237 +result = tools.call_tool(tool_name, tool_arguments)
  238 +```
  239 +
  240 +上述导入方式从仓库根目录运行;若在线项目只把 `offline_tasks/` 加入 `PYTHONPATH`,则改为从 `agent_tools` 导入。正式跨仓库复用时建议将该目录构建成内部 Python 包并锁定版本。
  241 +
  242 +## 5. 错误与诊断
  243 +
  244 +Tool 调用永远返回顶层 `ok`。错误结构:
  245 +
  246 +```json
  247 +{
  248 + "ok": false,
  249 + "error": {
  250 + "code": "invalid_arguments",
  251 + "message": "seed_items must be a non-empty array",
  252 + "retryable": false
  253 + }
  254 +}
  255 +```
  256 +
  257 +`index_unavailable` 表示 Redis 查询异常,通常可重试;`invalid_arguments` 和 `unknown_tool` 应由 Agent 修正调用,不应盲目重试。
  258 +
  259 +成功响应的 `diagnostics` 包含:
  260 +
  261 +- 计划的 source 和查询 key 数;
  262 +- 命中、缺失、格式错误的 source 数;
  263 +- 少量命中或缺失 key 样本;
  264 +- 排除的候选出现次数;
  265 +- 截断前候选数和实际融合策略。
  266 +
  267 +这些字段用于日志和指标,不建议原样展示给最终用户。
  268 +
  269 +## 6. Agent 编排建议
  270 +
  271 +1. 从画像中选择最近、高强度且能代表当前意图的 3 到 10 个种子,不要把全部历史灌给工具。
  272 +2. 对 LLM 推断出的兴趣保留置信度;低置信推断应降低 `weight`,硬约束不能只靠 weight 表达。
  273 +3. 分类名称先解析,歧义结果由分类树或商品搜索确认。
  274 +4. 一般直接调用混合工具;只有调试或需要控制通道时才分别调用两种召回工具。
  275 +5. 取 30 到 100 个候选后批量获取商品详情,先执行硬过滤,再让 LLM 在较小集合中比较。
  276 +6. 最终理由区分“画像依据”“协同证据”和“商品事实”,避免把统计相关性写成因果关系。
  277 +7. 无候选时读取 diagnostics,区分无种子、维度 ID 错、key 缺失、格式异常和实时过滤清空。
  278 +
  279 +## 7. 评估与上线
  280 +
  281 +离线回放至少比较:
  282 +
  283 +- Recall@K、NDCG@K、种子覆盖率和维度 key 命中率;
  284 +- 多路候选重合率、目录过滤后保留率和类目/供应商多样性;
  285 +- 强行为样本与冷启动样本的分段效果;
  286 +- 错误维度、过期画像和热门偏置的敏感性。
  287 +
  288 +线上实验至少记录:
  289 +
  290 +- 工具 P50/P95/P99 延迟和 Redis mget 大小;
  291 +- 每通道 hit rate、候选数、LLM 最终采用率;
  292 +- 点击、询盘、加购、购买和负反馈;
  293 +- 空结果率、重复曝光率以及不同平台/国家/客户群体的偏差。
  294 +
  295 +发布时把算法权重、通道权重和候选池大小纳入实验配置;工具 schema 与 Redis 契约版本应进入日志,便于归因和回滚。
  296 +
  297 +## 8. 后续扩展
  298 +
  299 +按收益和依赖关系建议继续建设:
  300 +
  301 +1. **真实全局兜底**:离线生成无条件热销、新品和探索池,解决完全冷启动。
  302 +2. **类目语义桥接**:建立名称、别名、多语言到分类 ID 的检索服务,不只做字面包含匹配。
  303 +3. **搭配与替代关系**:从订单构建有方向的“常一起采购”和“可替代”索引,避免所有关系都被压成相似。
  304 +4. **用户/群组索引**:对稳定画像预计算 U2I 或 cohort-to-item,减少每次对话临时展开大量种子。
  305 +5. **约束感知重排**:在目录补全后加入价格带、MOQ、交期、地域和供应商配额的确定性重排。
  306 +6. **多样性与探索**:基于类目、供应商和新颖度做受控去同质化,并保留少量探索位。
  307 +7. **反馈闭环**:记录工具候选、LLM 采用项、展示和行为结果,训练融合权重或轻量 reranker。
  308 +8. **索引版本化**:采用版本指针或双 buffer 原子切换,避免加载期间读到新旧混合数据。
  309 +
  310 +其中 1、2、3 会直接扩大 Agent 能找到的商品范围;5、6、7 决定候选能否转化成稳定的业务收益。
... ...
offline_tasks/doc/离线索引数据规范.md
... ... @@ -8,11 +8,12 @@
8 8 | **i2i_swing** | `python3 scripts/i2i_swing.py` | 每天 | `output/i2i_swing_YYYYMMDD.txt` | `item_id \t item_name \t similar_id1:score1,similar_id2:score2,...` |
9 9 | **i2i_session_w2v** | `python3 scripts/i2i_session_w2v.py` | 每天 | `output/i2i_session_w2v_YYYYMMDD.txt` | `item_id \t item_name \t similar_id1:score1,similar_id2:score2,...` |
10 10 | **i2i_deepwalk** | `python3 scripts/i2i_deepwalk.py` | 每天 | `output/i2i_deepwalk_YYYYMMDD.txt` | `item_id \t item_name \t similar_id1:score1,similar_id2:score2,...` |
11   -| **i2i_content** | `python3 scripts/i2i_content_similar.py` | 每周 | `output/i2i_content_hybrid_YYYYMMDD.txt` | `item_id \t item_name \t similar_id1:score1,similar_id2:score2,...` |
12   -| **interest_hot** | `python3 scripts/interest_aggregation.py` | 每天 | `output/interest_aggregation_hot_YYYYMMDD.txt` | `dimension_key \t item_id1,item_id2,item_id3,...` |
13   -| **interest_cart** | `python3 scripts/interest_aggregation.py` | 每天 | `output/interest_aggregation_cart_YYYYMMDD.txt` | `dimension_key \t item_id1,item_id2,item_id3,...` |
14   -| **interest_new** | `python3 scripts/interest_aggregation.py` | 每天 | `output/interest_aggregation_new_YYYYMMDD.txt` | `dimension_key \t item_id1,item_id2,item_id3,...` |
15   -| **interest_global** | `python3 scripts/interest_aggregation.py` | 每天 | `output/interest_aggregation_global_YYYYMMDD.txt` | `dimension_key \t item_id1,item_id2,item_id3,...` |
  11 +| **i2i_content_name/pic** | `python3 scripts/i2i_content_similar.py` | 每周 | `output/i2i_content_name_YYYYMMDD.txt`、`output/i2i_content_pic_YYYYMMDD.txt` | `item_id \t item_name \t similar_id1:score1,...` |
  12 +| **i2i_item_behavior** | `python3 scripts/i2i_item_behavior.py` | 每天 | `output/i2i_item_behavior_YYYYMMDD.txt` | `item_id \t item_name \t similar_id1:score1,...` |
  13 +| **interest_hot** | `python3 scripts/interest_aggregation.py` | 每天 | `output/interest_aggregation_hot_YYYYMMDD.txt` | `dimension_key \t item_id1:score1,item_id2:score2,...` |
  14 +| **interest_cart** | `python3 scripts/interest_aggregation.py` | 每天 | `output/interest_aggregation_cart_YYYYMMDD.txt` | `dimension_key \t item_id1:score1,item_id2:score2,...` |
  15 +| **interest_new** | `python3 scripts/interest_aggregation.py` | 每天 | `output/interest_aggregation_new_YYYYMMDD.txt` | `dimension_key \t item_id1:score1,item_id2:score2,...` |
  16 +| **interest_global** | `python3 scripts/interest_aggregation.py` | 每天 | `output/interest_aggregation_global_YYYYMMDD.txt` | `dimension_key \t item_id1:score1,item_id2:score2,...` |
16 17  
17 18 ## 📊 详细格式说明
18 19  
... ... @@ -60,12 +61,12 @@ item_id \t item_name \t similar_id1:score1,similar_id2:score2,...
60 61 - `item_id`: 商品SKU ID
61 62 - `item_name`: 商品名称
62 63 - `similar_id`: 相似商品ID
63   -- `score`: 相似度分数(0-1之间,越大越相似)
  64 +- `score`: 算法内部相似度分数,越大越相似;不同算法量纲不可直接比较
64 65  
65 66 **特点**
66 67 - 🐍 **易调试**: Python实现,便于开发和调试
67 68 - 🎯 **功能丰富**: 支持时间衰减、日期维度等高级特性
68   -- 📊 **归一化**: 相似度分数已归一化到0-1区间
  69 +- 📊 **有序输出**: 每路按自身 score 降序;跨算法应使用排名融合或校准
69 70 - 📁 **文件位置**: `offline_tasks/output/i2i_*_YYYYMMDD.txt`
70 71  
71 72 #### 1.3 算法对比
... ... @@ -96,22 +97,22 @@ item_id \t item_name \t similar_id1:score1,similar_id2:score2,...
96 97  
97 98 #### 输出格式
98 99 ```
99   -dimension_key \t item_id1,item_id2,item_id3,...
  100 +dimension_key \t item_id1:score1,item_id2:score2,...
100 101 ```
101 102  
102 103 #### 示例
103 104 ```
104   -platform:pc 12345,67890,11223,44556,22334
105   -category_level2:200 67890,12345,22334,55667,11223
106   -platform_category2:pc_200 12345,67890,22334,11223,55667
107   -supplier:10001 12345,44556,22334,67890,11223
  105 +platform:essaone 12345:80.0000,67890:65.0000,11223:42.0000
  106 +category_level2:200 67890:55.0000,12345:40.0000,22334:32.0000
  107 +platform_category2:essaone_200 12345:38.0000,67890:31.0000
  108 +supplier:10001 12345:30.0000,44556:24.0000
108 109 ```
109 110  
110 111 #### 维度说明
111 112  
112 113 **单维度(7个)**
113   -- `platform:{platform_id}` - 业务平台(pc, h5, app等)
114   -- `client_platform:{client}` - 客户端平台(iOS, Android, Web等)
  114 +- `platform:{platform_id}` - 业务平台(当前常见值:essa、essaone、essabuy)
  115 +- `client_platform:{client}` - 客户端平台(当前产出中常见值:pc)
115 116 - `supplier:{supplier_id}` - 供应商
116 117 - `category_level1:{cat_id}` - 一级分类
117 118 - `category_level2:{cat_id}` - 二级分类
... ... @@ -124,6 +125,12 @@ supplier:10001 12345,44556,22334,67890,11223
124 125 - `platform_category3:{platform}_{cat_id}` - 平台+三级分类
125 126 - `client_category2:{client}_{cat_id}` - 客户端+二级分类
126 127  
  128 +**地域画像组合维度(仅 essa、essaone)**
  129 +- `platform:{platform};country_code:{country}` - 平台+国家
  130 +- `platform:{platform};country_code:{country};customer_type:{type}` - 平台+国家+客户类型
  131 +
  132 +`global` 是列表类型,不是 dimension;当前不会自动生成 `interest:global:global`。
  133 +
127 134 #### 列表类型说明
128 135  
129 136 | 类型 | 文件名 | 计算逻辑 | 适用场景 |
... ... @@ -205,7 +212,7 @@ head -5 output/i2i_swing_$(date +%Y%m%d).txt
205 212 **i2i索引质量**
206 213 - 覆盖率:有推荐的商品数 / 总商品数 > 80%
207 214 - 推荐数量:每个商品推荐10-50个相似商品
208   -- 分数范围:相似度分数在0.01-1.0之间
  215 +- 分数有效:score 可解析为有限浮点数,同一路内按降序排列;不要求统一为 0-1
209 216  
210 217 **兴趣聚合质量**
211 218 - 覆盖率:有数据的维度数 / 总维度数 > 60%
... ... @@ -223,7 +230,7 @@ grep &quot;^12345\t&quot; output/i2i_swing_20251016.txt
223 230 ### 查看特定维度的热门商品
224 231 ```bash
225 232 # 查看PC平台的热门商品
226   -grep "^platform:pc\t" output/interest_aggregation_hot_20251016.txt
  233 +grep "^platform:essaone\t" output/interest_aggregation_hot_YYYYMMDD.txt
227 234 ```
228 235  
229 236 ### 统计索引数量
... ... @@ -239,14 +246,13 @@ done
239 246 1. **文件编码**: 所有文件使用UTF-8编码
240 247 2. **分隔符**: 使用Tab(\t)分隔字段
241 248 3. **商品ID**: 使用数字类型,不带引号
242   -4. **分数精度**: 相似度分数保留4位小数
  249 +4. **分数精度**: Python 索引通常保留4位小数,C++ 等产出可保留更高精度
243 250 5. **排序规则**: 相似商品按分数降序排列
244 251 6. **去重**: 确保推荐列表中没有重复商品
245 252 7. **有效性**: 推荐的商品必须是在售状态
246 253  
247 254 ## 🔗 相关文档
248 255  
249   -- **Redis数据规范**: `REDIS_DATA_SPEC.md`
250   -- **API接口文档**: `RECOMMENDATION_API.md`
251   -- **Debug指南**: `DEBUG_GUIDE.md`
252   -- **配置说明**: `UPDATE_CONFIG_GUIDE.md`
  256 +- **Redis数据规范**: `Redis数据规范.md`
  257 +- **在线 key 清单**: `在线召回Redis Key清单.md`
  258 +- **Agent 工具方案**: `智能导购Agent工具集.md`
... ...
offline_tasks/doc/详细设计文档.md
... ... @@ -4,7 +4,7 @@
4 4  
5 5 本文档是推荐系统离线任务的详细设计文档,包含系统架构、功能模块、实现细节和使用指南。
6 6  
7   -**最后更新**: 2024-10-17
  7 +**最后更新**: 2026-08-23
8 8 **版本**: v1.1
9 9 **状态**: ✅ 已完成并可用
10 10  
... ... @@ -119,7 +119,7 @@ offline_tasks/
119 119 - 性能: 适中,易于调试
120 120 - 适用场景: 开发测试,需要高级特性(时间衰减、日期维度)
121 121 - 输出格式: `item_id \t item_name \t similar_id1:score1,...`
122   -- 分数特点: 归一化到0-1区间
  122 +- 分数特点: 算法内按降序排列,量纲不保证为0-1
123 123  
124 124 **参数配置:**
125 125 ```bash
... ... @@ -175,7 +175,7 @@ python3 scripts/i2i_deepwalk.py --lookback_days 730 --top_n 50 --save_model --sa
175 175  
176 176 **参数:**
177 177 ```bash
178   -python3 scripts/i2i_content_similar.py --top_n 50 --method hybrid
  178 +python3 scripts/i2i_content_similar.py --top_n 50
179 179 ```
180 180  
181 181 ### 2. 兴趣点聚合索引
... ... @@ -334,7 +334,7 @@ DB_CONFIG = {
334 334 # Redis配置
335 335 REDIS_CONFIG = {
336 336 'host': 'your_redis_host',
337   - 'port': 6379,
  337 + 'port': 6479,
338 338 'db': 0,
339 339 'password': None
340 340 }
... ... @@ -409,9 +409,9 @@ ls debug/
409 409  
410 410 ```
411 411 # 文件: output/interest_aggregation_hot_20251016.txt
412   -platform:pc 12345,23456,34567,45678,56789
413   -category_level2:200 45678,56789,67890,78901,89012
414   -platform_category2:pc_200 12345,23456,34567,45678
  412 +platform:essaone 12345:50.0000,23456:42.0000,34567:31.0000
  413 +category_level2:200 45678:45.0000,56789:38.0000,67890:30.0000
  414 +platform_category2:essaone_200 12345:36.0000,23456:28.0000
415 415 ```
416 416  
417 417 ---
... ... @@ -423,13 +423,13 @@ platform_category2:pc_200 12345,23456,34567,45678
423 423 **使用索引:**
424 424 ```python
425 425 # 基于平台
426   -interest:hot:platform:pc
  426 +interest:hot:platform:essaone
427 427  
428 428 # 基于分类偏好
429 429 interest:hot:category_level2:200
430 430  
431 431 # 基于平台+分类
432   -interest:hot:platform_category2:pc_200
  432 +interest:hot:platform_category2:essaone_200
433 433 ```
434 434  
435 435 ### 场景2: 详情页相关推荐
... ... @@ -442,13 +442,15 @@ item:similar:swing_cpp:12345
442 442 # 行为相似(Python Swing)
443 443 item:similar:swing:12345
444 444  
445   -# 内容相似
446   -item:similar:content_hybrid:12345
  445 +# 内容相似(名称和图片是两路独立索引)
  446 +item:similar:content_name:12345
  447 +item:similar:content_pic:12345
447 448  
448 449 # 融合推荐(多算法)
449 450 swing_items = redis.get('item:similar:swing_cpp:12345')
450   -w2v_items = redis.get('item:similar:w2v:12345')
451   -content_items = redis.get('item:similar:content_hybrid:12345')
  451 +w2v_items = redis.get('item:similar:session_w2v:12345')
  452 +content_name_items = redis.get('item:similar:content_name:12345')
  453 +content_pic_items = redis.get('item:similar:content_pic:12345')
452 454 # 融合多个算法结果...
453 455 ```
454 456  
... ... @@ -457,7 +459,7 @@ content_items = redis.get(&#39;item:similar:content_hybrid:12345&#39;)
457 459 **使用索引:**
458 460 ```python
459 461 # 全局热门
460   -interest:global:platform:pc
  462 +interest:global:platform:essaone
461 463  
462 464 # 分类相关
463 465 interest:global:category_level2:200
... ... @@ -709,4 +711,4 @@ crontab -e
709 711 ---
710 712  
711 713 **文档版本**: v1.1
712   -**最后更新**: 2024-10-17
  714 +**最后更新**: 2026-08-23
... ...
offline_tasks/example_query_redis.py
1   -"""
2   -示例:从Redis查询推荐结果
3   -演示如何使用生成的索引进行在线推荐
4   -"""
5   -import redis
  1 +"""Query examples for the current Redis recommendation index contract."""
  2 +
6 3 import argparse
7   -from offline_tasks.config.offline_config import REDIS_CONFIG
  4 +import json
  5 +import os
  6 +
  7 +import redis
  8 +
  9 +try:
  10 + from agent_tools.parsing import parse_ranked_items
  11 +except ImportError:
  12 + from offline_tasks.agent_tools.parsing import parse_ranked_items
  13 +
  14 +
  15 +I2I_PREFIXES = {
  16 + 'swing_cpp': ['item:similar:swing_cpp'],
  17 + 'swing': ['item:similar:swing'],
  18 + 'session_w2v': ['item:similar:session_w2v', 'item:similar:w2v'],
  19 + 'deepwalk': ['item:similar:deepwalk'],
  20 + 'content_name': ['item:similar:content_name'],
  21 + 'content_pic': ['item:similar:content_pic'],
  22 + 'item_behavior': ['item:similar:item_behavior'],
  23 +}
8 24  
9 25  
10 26 def query_i2i_similar_items(redis_client, item_id, algorithm='swing', top_n=10):
11   - """
12   - 查询物品的相似物品
13   -
14   - Args:
15   - redis_client: Redis客户端
16   - item_id: 物品ID
17   - algorithm: 算法类型 (swing/session_w2v/deepwalk)
18   - top_n: 返回前N个结果
19   -
20   - Returns:
21   - List of (item_id, score)
22   - """
23   - key = f"i2i:{algorithm}:{item_id}"
24   - value = redis_client.get(key)
25   -
26   - if not value:
27   - return []
28   -
29   - # 解析结果
30   - results = []
31   - items = value.split(',')
32   - for item in items[:top_n]:
33   - parts = item.split(':')
34   - if len(parts) == 2:
35   - results.append((parts[0], float(parts[1])))
36   -
37   - return results
  27 + """Return ranked ``(item_id, score)`` pairs for one seed item."""
  28 + if algorithm not in I2I_PREFIXES:
  29 + raise ValueError('unsupported algorithm: %s' % algorithm)
  30 + for prefix in I2I_PREFIXES[algorithm]:
  31 + value = redis_client.get('%s:%s' % (prefix, item_id))
  32 + items = parse_ranked_items(value)
  33 + if items:
  34 + return items[:top_n]
  35 + return []
38 36  
39 37  
40 38 def query_interest_items(redis_client, dimension_key, list_type='hot', top_n=20):
41   - """
42   - 查询兴趣点聚合的推荐物品
43   -
44   - Args:
45   - redis_client: Redis客户端
46   - dimension_key: 维度key (如 platform:PC, country:US)
47   - list_type: 列表类型 (hot/cart/new/global)
48   - top_n: 返回前N个结果
49   -
50   - Returns:
51   - List of (item_id, score)
52   - """
53   - key = f"interest:{list_type}:{dimension_key}"
54   - value = redis_client.get(key)
55   -
56   - if not value:
57   - return []
58   -
59   - # 解析结果
60   - results = []
61   - items = value.split(',')
62   - for item in items[:top_n]:
63   - parts = item.split(':')
64   - if len(parts) == 2:
65   - results.append((parts[0], float(parts[1])))
66   -
67   - return results
68   -
69   -
70   -def main():
71   - parser = argparse.ArgumentParser(description='Query recommendation results from Redis')
72   - parser.add_argument('--redis-host', type=str, default=REDIS_CONFIG['host'],
73   - help='Redis host')
74   - parser.add_argument('--redis-port', type=int, default=REDIS_CONFIG['port'],
75   - help='Redis port')
76   - parser.add_argument('--redis-db', type=int, default=REDIS_CONFIG['db'],
77   - help='Redis database')
78   -
79   - args = parser.parse_args()
80   -
81   - # 创建Redis连接
82   - print("Connecting to Redis...")
  39 + """Return ranked pairs for an exact offline dimension key."""
  40 + if list_type not in ('hot', 'cart', 'new', 'global'):
  41 + raise ValueError('unsupported list type: %s' % list_type)
  42 + key = 'interest:%s:%s' % (list_type, dimension_key)
  43 + return parse_ranked_items(redis_client.get(key))[:top_n]
  44 +
  45 +
  46 +def build_parser():
  47 + parser = argparse.ArgumentParser(
  48 + description='Query the current Redis recommendation index contract'
  49 + )
  50 + parser.add_argument('--redis-host', default=os.environ.get(
  51 + 'RECOMMENDATION_REDIS_HOST', 'localhost'
  52 + ))
  53 + parser.add_argument('--redis-port', type=int, default=int(os.environ.get(
  54 + 'RECOMMENDATION_REDIS_PORT', '6479'
  55 + )))
  56 + parser.add_argument('--redis-db', type=int, default=int(os.environ.get(
  57 + 'RECOMMENDATION_REDIS_DB', '0'
  58 + )))
  59 + parser.add_argument('--item-id')
  60 + parser.add_argument('--algorithm', choices=sorted(I2I_PREFIXES), default='swing')
  61 + parser.add_argument(
  62 + '--dimension-key',
  63 + help='For example: platform:essaone or category_level2:29',
  64 + )
  65 + parser.add_argument(
  66 + '--list-type', choices=('hot', 'cart', 'new', 'global'), default='hot'
  67 + )
  68 + parser.add_argument('--top-n', type=int, default=10)
  69 + return parser
  70 +
  71 +
  72 +def main(argv=None):
  73 + args = build_parser().parse_args(argv)
  74 + if not args.item_id and not args.dimension_key:
  75 + raise SystemExit('provide --item-id or --dimension-key')
  76 + if args.top_n < 1 or args.top_n > 500:
  77 + raise SystemExit('--top-n must be between 1 and 500')
  78 +
83 79 redis_client = redis.Redis(
84 80 host=args.redis_host,
85 81 port=args.redis_port,
86 82 db=args.redis_db,
87   - decode_responses=True
  83 + password=os.environ.get('RECOMMENDATION_REDIS_PASSWORD'),
  84 + decode_responses=True,
  85 + socket_connect_timeout=2,
  86 + socket_timeout=2,
88 87 )
89   -
90   - try:
91   - redis_client.ping()
92   - print("✓ Redis connected\n")
93   - except Exception as e:
94   - print(f"✗ Failed to connect to Redis: {e}")
95   - return 1
96   -
97   - # 示例1: 查询i2i相似物品
98   - print("="*80)
99   - print("示例1: 查询物品的相似物品(i2i)")
100   - print("="*80)
101   -
102   - test_item_id = "123456" # 替换为实际的物品ID
103   -
104   - for algorithm in ['swing', 'session_w2v', 'deepwalk']:
105   - print(f"\n算法: {algorithm}")
106   - results = query_i2i_similar_items(redis_client, test_item_id, algorithm, top_n=5)
107   -
108   - if results:
109   - print(f"物品 {test_item_id} 的相似物品:")
110   - for idx, (item_id, score) in enumerate(results, 1):
111   - print(f" {idx}. 物品ID: {item_id}, 相似度: {score:.4f}")
112   - else:
113   - print(f" 未找到物品 {test_item_id} 的相似物品")
114   -
115   - # 示例2: 查询兴趣点推荐
116   - print("\n" + "="*80)
117   - print("示例2: 查询兴趣点聚合推荐")
118   - print("="*80)
119   -
120   - # 测试不同维度
121   - test_cases = [
122   - ('platform', 'PC', 'hot'),
123   - ('country', 'US', 'hot'),
124   - ('customer_type', 'retailer', 'cart'),
125   - ('category_level2', '100', 'new'),
126   - ]
127   -
128   - for dimension, value, list_type in test_cases:
129   - dimension_key = f"{dimension}:{value}"
130   - print(f"\n维度: {dimension_key}, 类型: {list_type}")
131   - results = query_interest_items(redis_client, dimension_key, list_type, top_n=5)
132   -
133   - if results:
134   - print(f"推荐物品:")
135   - for idx, (item_id, score) in enumerate(results, 1):
136   - print(f" {idx}. 物品ID: {item_id}, 分数: {score:.4f}")
137   - else:
138   - print(f" 未找到推荐结果")
139   -
140   - # 示例3: 组合查询(实际推荐场景)
141   - print("\n" + "="*80)
142   - print("示例3: 组合推荐场景")
143   - print("="*80)
144   -
145   - print("\n场景: 用户在PC端,来自美国,是零售商,浏览了物品123456")
146   - print("\n1. 基于物品的相似推荐(i2i):")
147   - results = query_i2i_similar_items(redis_client, test_item_id, 'swing', top_n=3)
148   - for idx, (item_id, score) in enumerate(results, 1):
149   - print(f" {idx}. 物品ID: {item_id}, 相似度: {score:.4f}")
150   -
151   - print("\n2. 基于平台+国家的热门推荐:")
152   - results = query_interest_items(redis_client, 'platform_country:PC_US', 'hot', top_n=3)
153   - for idx, (item_id, score) in enumerate(results, 1):
154   - print(f" {idx}. 物品ID: {item_id}, 分数: {score:.4f}")
155   -
156   - print("\n3. 基于客户类型的加购推荐:")
157   - results = query_interest_items(redis_client, 'customer_type:retailer', 'cart', top_n=3)
158   - for idx, (item_id, score) in enumerate(results, 1):
159   - print(f" {idx}. 物品ID: {item_id}, 分数: {score:.4f}")
160   -
161   - print("\n" + "="*80)
162   - print("✓ 查询示例完成")
163   - print("="*80)
164   -
  88 + result = {}
  89 + if args.item_id:
  90 + result['similar_items'] = query_i2i_similar_items(
  91 + redis_client, args.item_id, args.algorithm, args.top_n
  92 + )
  93 + if args.dimension_key:
  94 + result['interest_items'] = query_interest_items(
  95 + redis_client, args.dimension_key, args.list_type, args.top_n
  96 + )
  97 + print(json.dumps(result, ensure_ascii=False, indent=2))
165 98 return 0
166 99  
167 100  
168 101 if __name__ == '__main__':
169 102 main()
170   -
... ...
offline_tasks/scripts/ES_VECTOR_SIMILARITY.md
... ... @@ -16,19 +16,19 @@ cd /home/tw/recommendation/offline_tasks
16 16 python scripts/i2i_content_similar.py
17 17 ```
18 18  
19   -脚本无需任何参数,所有配置都在代码中设置好。
  19 +脚本无需算法参数。执行前必须核对脚本头部的连接目标;本文不记录真实凭据,生产部署应通过安全配置注入。
20 20  
21 21 ### 配置说明
22 22  
23 23 脚本内置配置(位于 `i2i_content_similar.py` 头部):
24 24  
25 25 ```python
26   -# ES配置
  26 +# ES_CONFIG 字段示意(真实值以部署配置为准)
27 27 ES_CONFIG = {
28   - 'host': 'http://localhost:9200',
29   - 'index_name': 'spu',
30   - 'username': 'essa',
31   - 'password': '4hOaLaf41y2VuI8y'
  28 + 'host': '<configured_host>',
  29 + 'index_name': '<configured_index>',
  30 + 'username': '<configured_username>',
  31 + 'password': '<from_secret_store>',
32 32 }
33 33  
34 34 # 算法参数
... ... @@ -150,29 +150,29 @@ item_id\titem_name\tsimilar_id1:score1,similar_id2:score2,...
150 150  
151 151 #### 名称向量相似
152 152 - **Key**: `item:similar:content_name:{item_id}`
153   -- **Value**: `[[similar_id1,score1],[similar_id2,score2],...]`
154   -- **TTL**: 800天
  153 +- **Value**: `similar_id1:score1,similar_id2:score2,...`
  154 +- **TTL**: 由加载器 `--expire-days` 控制,默认60天
155 155  
156 156 #### 图片向量相似
157 157 - **Key**: `item:similar:content_pic:{item_id}`
158   -- **Value**: `[[similar_id1,score1],[similar_id2,score2],...]`
159   -- **TTL**: 800天
  158 +- **Value**: `similar_id1:score1,similar_id2:score2,...`
  159 +- **TTL**: 由加载器 `--expire-days` 控制,默认60天
160 160  
161 161 ### 使用示例
162 162  
163 163 ```python
164 164 import redis
165   -import json
  165 +from agent_tools.parsing import parse_ranked_items
166 166  
167   -r = redis.Redis(host='localhost', port=6379, db=0)
  167 +r = redis.Redis(host='localhost', port=6479, db=0, decode_responses=True)
168 168  
169 169 # 获取基于名称向量的相似商品
170   -similar_items = json.loads(r.get('item:similar:content_name:123456'))
171   -# 返回: [[234567, 0.9234], [345678, 0.8756], ...]
  170 +similar_items = parse_ranked_items(r.get('item:similar:content_name:123456'))
  171 +# 返回: [('234567', 0.9234), ('345678', 0.8756), ...]
172 172  
173 173 # 获取基于图片向量的相似商品
174   -similar_items = json.loads(r.get('item:similar:content_pic:123456'))
175   -# 返回: [[567890, 0.8123], [678901, 0.7856], ...]
  174 +similar_items = parse_ranked_items(r.get('item:similar:content_pic:123456'))
  175 +# 返回: [('567890', 0.8123), ('678901', 0.7856), ...]
176 176 ```
177 177  
178 178 ## 性能说明
... ... @@ -241,8 +241,9 @@ similar_items = json.loads(r.get(&#39;item:similar:content_pic:123456&#39;))
241 241 ### 连接ES失败
242 242  
243 243 ```python
244   -# 检查ES配置
245   -curl -u essa:4hOaLaf41y2VuI8y http://localhost:9200/_cat/indices
  244 +# 检查ES配置;用户名和密码由环境安全注入
  245 +curl -u "$RECOMMENDATION_ES_USERNAME:$RECOMMENDATION_ES_PASSWORD" \
  246 + "$RECOMMENDATION_ES_HOST/_cat/indices"
246 247 ```
247 248  
248 249 ### 查询超时
... ... @@ -260,7 +261,8 @@ es = Elasticsearch(
260 261  
261 262 检查ES mapping:
262 263 ```bash
263   -curl -u essa:4hOaLaf41y2VuI8y http://localhost:9200/spu/_mapping
  264 +curl -u "$RECOMMENDATION_ES_USERNAME:$RECOMMENDATION_ES_PASSWORD" \
  265 + "$RECOMMENDATION_ES_HOST/spu/_mapping"
264 266 ```
265 267  
266 268 ## 与其他相似度算法的对比
... ... @@ -277,5 +279,4 @@ curl -u essa:4hOaLaf41y2VuI8y http://localhost:9200/spu/_mapping
277 279  
278 280 - **名称向量相似**: 每周更新(商品名称变化少)
279 281 - **图片向量相似**: 每周更新(商品图片变化少)
280   -- **Redis TTL**: 800天(内容相似度变化极慢,可以长期保留)
281   -
  282 +- **Redis TTL**: 由统一加载参数控制,当前默认60天;调整前需同时评估更新频率与过期风险
... ...
offline_tasks/scripts/agent_recommendation_tools.py 0 → 100644
... ... @@ -0,0 +1,15 @@
  1 +"""Executable wrapper for :mod:`agent_tools.cli`."""
  2 +
  3 +import os
  4 +import sys
  5 +
  6 +
  7 +OFFLINE_TASKS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  8 +if OFFLINE_TASKS_DIR not in sys.path:
  9 + sys.path.insert(0, OFFLINE_TASKS_DIR)
  10 +
  11 +from agent_tools.cli import main # noqa: E402
  12 +
  13 +
  14 +if __name__ == '__main__':
  15 + sys.exit(main())
... ...
offline_tasks/scripts/fetch_item_attributes.py
... ... @@ -10,6 +10,7 @@ import argparse
10 10 from datetime import datetime
11 11 from db_service import create_db_connection
12 12 from config.offline_config import DB_CONFIG, OUTPUT_DIR
  13 +from agent_tools.catalog import save_agent_dimension_catalog
13 14 from scripts.debug_utils import setup_debug_logger, sanitize_index_field
14 15 from scripts.item_freshness import save_item_create_times
15 16  
... ... @@ -129,6 +130,10 @@ def fetch_and_save_mappings(engine, output_dir, logger=None, debug=False):
129 130 with open(output_file, 'w', encoding='utf-8') as f:
130 131 json.dump(mappings, f, ensure_ascii=False, indent=2)
131 132  
  133 + agent_catalog_file = save_agent_dimension_catalog(mappings, output_dir)
  134 + if logger:
  135 + logger.info(f"Agent维度字典已保存到: {agent_catalog_file}")
  136 +
132 137 create_times_file = save_item_create_times(item_create_times, output_dir, logger=logger)
133 138  
134 139 # 保存统计信息
... ... @@ -192,4 +197,3 @@ def main():
192 197  
193 198 if __name__ == '__main__':
194 199 main()
195   -
... ...
offline_tasks/test_agent_recommendation_tools.py 0 → 100644
... ... @@ -0,0 +1,329 @@
  1 +"""In-memory checks for the agent-facing recommendation toolset."""
  2 +
  3 +import json
  4 +import os
  5 +import tempfile
  6 +import unittest
  7 +
  8 +from agent_tools import (
  9 + DimensionCatalog, MemoryIndexStore, RecommendationAgentTools,
  10 + save_agent_dimension_catalog,
  11 +)
  12 +from agent_tools.parsing import normalize_identifier, parse_ranked_items
  13 +
  14 +
  15 +class IndexParsingTest(unittest.TestCase):
  16 +
  17 + def test_parses_current_delimited_format(self):
  18 + self.assertEqual(
  19 + parse_ranked_items(b'101:0.9,102:0.5,103:0.1'),
  20 + [('101', 0.9), ('102', 0.5), ('103', 0.1)],
  21 + )
  22 +
  23 + def test_parses_json_and_legacy_json_string_formats(self):
  24 + self.assertEqual(
  25 + parse_ranked_items('[[101,0.9],[102,0.5]]'),
  26 + [('101', 0.9), ('102', 0.5)],
  27 + )
  28 + self.assertEqual(
  29 + parse_ranked_items(json.dumps('101:0.9,102:0.5')),
  30 + [('101', 0.9), ('102', 0.5)],
  31 + )
  32 + self.assertEqual(
  33 + parse_ranked_items('[101,102]'),
  34 + [('101', None), ('102', None)],
  35 + )
  36 +
  37 + def test_skips_malformed_and_duplicate_entries(self):
  38 + self.assertEqual(
  39 + parse_ranked_items('101:bad,102:0.5,102:0.2,,103'),
  40 + [('102', 0.5), ('103', None)],
  41 + )
  42 + self.assertEqual(normalize_identifier('123.0'), '123')
  43 + self.assertIsNone(normalize_identifier(float('nan')))
  44 +
  45 +
  46 +class DimensionCatalogTest(unittest.TestCase):
  47 +
  48 + def setUp(self):
  49 + self.catalog = DimensionCatalog({
  50 + 'category': {
  51 + '29': '玩具车辆',
  52 + '31': '益智拼装玩具',
  53 + },
  54 + 'supplier': {'24947': '示例玩具供应商'},
  55 + })
  56 +
  57 + def test_resolves_exact_value_and_name_substring(self):
  58 + exact = self.catalog.resolve('category_level2', '29')
  59 + self.assertEqual(exact[0]['value'], '29')
  60 + self.assertEqual(exact[0]['match_type'], 'exact_value')
  61 +
  62 + matches = self.catalog.resolve('category_level2', '拼装')
  63 + self.assertEqual(matches[0]['value'], '31')
  64 + self.assertEqual(matches[0]['match_type'], 'label_contains')
  65 +
  66 + def test_loads_generated_catalog_file(self):
  67 + payload = {
  68 + 'schema_version': 1,
  69 + 'dimensions': {'category': {'5': '文具'}},
  70 + }
  71 + with tempfile.TemporaryDirectory() as temp_dir:
  72 + path = os.path.join(temp_dir, 'catalog.json')
  73 + with open(path, 'w', encoding='utf-8') as catalog_file:
  74 + json.dump(payload, catalog_file, ensure_ascii=False)
  75 + catalog = DimensionCatalog.from_file(path)
  76 + self.assertEqual(catalog.resolve('category_level1', '文具')[0]['value'], '5')
  77 +
  78 + def test_dimension_catalog_output_excludes_large_item_mapping(self):
  79 + mappings = {
  80 + 'item': {'100': '不应写入 Agent 字典'},
  81 + 'category': {'5': '文具'},
  82 + 'supplier': {'9': '示例供应商'},
  83 + }
  84 + with tempfile.TemporaryDirectory() as temp_dir:
  85 + path = save_agent_dimension_catalog(mappings, temp_dir)
  86 + with open(path, 'r', encoding='utf-8') as catalog_file:
  87 + payload = json.load(catalog_file)
  88 + self.assertFalse(os.path.exists(path + '.tmp'))
  89 + self.assertNotIn('item', payload['dimensions'])
  90 + self.assertEqual(payload['dimensions']['category']['5'], '文具')
  91 +
  92 +
  93 +class RecommendationAgentToolsTest(unittest.TestCase):
  94 +
  95 + def setUp(self):
  96 + self.values = {
  97 + 'item:similar:swing:100': '200:0.9,201:0.8,202:0.7,100:1.0',
  98 + 'item:similar:session_w2v:100': json.dumps([
  99 + ['201', 0.95], ['203', 0.8], ['200', 0.7],
  100 + ]),
  101 + 'item:similar:w2v:101': '204:0.8,205:0.7',
  102 + 'interest:hot:platform:essaone;country_code:344;customer_type:target': (
  103 + '300:90,301:80'
  104 + ),
  105 + 'interest:hot:platform:essaone;country_code:344': '301:70,304:60',
  106 + 'interest:hot:platform_category2:essaone_29': '300:50,302:40',
  107 + 'interest:hot:category_level2:29': '303:30,300:20',
  108 + 'interest:hot:platform:essaone': '304:20,305:10',
  109 + 'interest:hot:client_platform:pc': '305:30,306:20',
  110 + 'interest:hot:platform_client:essaone_pc': '300:20,306:10',
  111 + 'interest:hot:client_category2:pc_29': '302:20,307:10',
  112 + }
  113 + self.store = MemoryIndexStore(self.values)
  114 + self.catalog = DimensionCatalog({
  115 + 'category': {'29': '玩具车辆'},
  116 + 'supplier': {'24947': '示例供应商'},
  117 + })
  118 + self.tools = RecommendationAgentTools(self.store, self.catalog)
  119 +
  120 + def test_similar_recall_fuses_algorithm_consensus(self):
  121 + result = self.tools.recall_similar_products(
  122 + seed_items=[{
  123 + 'item_id': '100',
  124 + 'behavior': 'click',
  125 + 'reason': '用户刚刚查看',
  126 + }],
  127 + algorithms=['swing', 'session_w2v'],
  128 + top_k=4,
  129 + )
  130 + self.assertTrue(result['ok'])
  131 + self.assertEqual(result['items'][0]['item_id'], '201')
  132 + self.assertNotIn('100', [item['item_id'] for item in result['items']])
  133 + self.assertEqual(result['items'][0]['source_count'], 2)
  134 + self.assertEqual(result['diagnostics']['hit_source_count'], 2)
  135 +
  136 + def test_similar_recall_uses_legacy_w2v_alias(self):
  137 + result = self.tools.recall_similar_products(
  138 + seed_items=[{'item_id': '101'}],
  139 + algorithms=['session_w2v'],
  140 + top_k=2,
  141 + )
  142 + self.assertEqual([item['item_id'] for item in result['items']], ['204', '205'])
  143 + self.assertEqual(
  144 + result['items'][0]['evidence'][0]['key'],
  145 + 'item:similar:w2v:101',
  146 + )
  147 +
  148 + def test_similar_recall_honors_exclusions(self):
  149 + result = self.tools.recall_similar_products(
  150 + seed_items=[{'item_id': '100'}],
  151 + algorithms=['swing'],
  152 + exclude_item_ids=['200', 201],
  153 + )
  154 + self.assertEqual([item['item_id'] for item in result['items']], ['202'])
  155 +
  156 + def test_dimension_recall_plans_specific_and_fallback_keys(self):
  157 + result = self.tools.recall_products_by_dimensions(
  158 + context={
  159 + 'platform': 'ESSAONE',
  160 + 'client_platform': 'PC',
  161 + 'country_code': '344',
  162 + 'customer_type': 'target',
  163 + },
  164 + interests=[{
  165 + 'dimension': 'category_level2',
  166 + 'value': 29,
  167 + 'weight': 2,
  168 + 'reason': '画像偏好玩具车辆',
  169 + }],
  170 + list_types=['hot'],
  171 + top_k=10,
  172 + )
  173 + self.assertTrue(result['ok'])
  174 + self.assertEqual(result['items'][0]['item_id'], '300')
  175 + self.assertIn(
  176 + 'interest:hot:platform_category2:essaone_29',
  177 + self.store.requested_keys,
  178 + )
  179 + self.assertIn(
  180 + 'interest:hot:category_level2:29',
  181 + self.store.requested_keys,
  182 + )
  183 + self.assertIn(
  184 + 'interest:hot:platform:essaone;country_code:344;customer_type:target',
  185 + self.store.requested_keys,
  186 + )
  187 + self.assertGreaterEqual(result['items'][0]['source_count'], 3)
  188 +
  189 + def test_dimension_recall_still_works_when_only_fallback_exists(self):
  190 + store = MemoryIndexStore({
  191 + 'interest:hot:category_level2:29': '401:10,402:9',
  192 + })
  193 + tools = RecommendationAgentTools(store)
  194 + result = tools.recall_products_by_dimensions(
  195 + context={'platform': 'essaone'},
  196 + interests=[{'dimension': 'category_level2', 'value': '29'}],
  197 + list_types=['hot'],
  198 + )
  199 + self.assertEqual([item['item_id'] for item in result['items']], ['401', '402'])
  200 + self.assertGreater(result['diagnostics']['missing_source_count'], 0)
  201 +
  202 + def test_hybrid_recall_rewards_cross_channel_consensus(self):
  203 + self.store.set('item:similar:swing:100', '300:0.9,200:0.8')
  204 + result = self.tools.build_recommendation_candidates(
  205 + seed_items=[{'item_id': '100'}],
  206 + context={'platform': 'essaone'},
  207 + interests=[{'dimension': 'category_level2', 'value': '29'}],
  208 + algorithms=['swing'],
  209 + list_types=['hot'],
  210 + top_k=5,
  211 + )
  212 + self.assertEqual(result['items'][0]['item_id'], '300')
  213 + self.assertEqual(
  214 + result['items'][0]['channels'], ['collaborative', 'dimension']
  215 + )
  216 + self.assertEqual(
  217 + set(result['diagnostics']['successful_channels']),
  218 + {'collaborative', 'dimension'},
  219 + )
  220 +
  221 + def test_catalog_resolution_and_tool_dispatch(self):
  222 + resolved = self.tools.call_tool(
  223 + 'resolve_recommendation_dimension',
  224 + {'dimension': 'category_level2', 'query': '车辆'},
  225 + )
  226 + self.assertTrue(resolved['ok'])
  227 + self.assertEqual(resolved['matches'][0]['value'], '29')
  228 +
  229 + invalid = self.tools.call_tool(
  230 + 'recall_similar_products',
  231 + {'seed_items': []},
  232 + )
  233 + self.assertFalse(invalid['ok'])
  234 + self.assertEqual(invalid['error']['code'], 'invalid_arguments')
  235 +
  236 + unknown = self.tools.call_tool('not_a_tool')
  237 + self.assertEqual(unknown['error']['code'], 'unknown_tool')
  238 +
  239 + missing_query = self.tools.call_tool(
  240 + 'resolve_recommendation_dimension',
  241 + {'dimension': 'category_level2', 'query': None},
  242 + )
  243 + self.assertEqual(missing_query['error']['code'], 'invalid_arguments')
  244 +
  245 + def test_natural_language_reasons_allow_punctuation(self):
  246 + result = self.tools.recall_similar_products(
  247 + seed_items=[{'item_id': '100', 'reason': '当前意图: 拼装; 玩具'}],
  248 + algorithms=['swing'],
  249 + )
  250 + self.assertTrue(result['ok'])
  251 + self.assertEqual(
  252 + result['items'][0]['reasons'][0]['profile_reason'],
  253 + '当前意图: 拼装; 玩具',
  254 + )
  255 +
  256 + def test_source_count_is_not_limited_by_evidence_payload(self):
  257 + prefixes = [
  258 + 'item:similar:swing_cpp',
  259 + 'item:similar:swing',
  260 + 'item:similar:session_w2v',
  261 + 'item:similar:deepwalk',
  262 + 'item:similar:content_name',
  263 + ]
  264 + values = {}
  265 + for seed in ('100', '101'):
  266 + for prefix in prefixes:
  267 + values['%s:%s' % (prefix, seed)] = '999:1.0'
  268 + tools = RecommendationAgentTools(MemoryIndexStore(values))
  269 + result = tools.recall_similar_products(
  270 + seed_items=[{'item_id': '100'}, {'item_id': '101'}],
  271 + algorithms=[
  272 + 'swing_cpp', 'swing', 'session_w2v', 'deepwalk', 'content_name',
  273 + ],
  274 + )
  275 + self.assertEqual(result['items'][0]['source_count'], 10)
  276 + self.assertEqual(len(result['items'][0]['evidence']), 8)
  277 +
  278 + def test_hybrid_channel_weight_matches_schema_range(self):
  279 + result = self.tools.call_tool(
  280 + 'build_recommendation_candidates',
  281 + {
  282 + 'seed_items': [{'item_id': '100'}],
  283 + 'collaborative_weight': 1.1,
  284 + },
  285 + )
  286 + self.assertFalse(result['ok'])
  287 + self.assertEqual(result['error']['code'], 'invalid_arguments')
  288 +
  289 + disabled = self.tools.call_tool(
  290 + 'build_recommendation_candidates',
  291 + {
  292 + 'seed_items': [{'item_id': '100'}],
  293 + 'collaborative_weight': 0,
  294 + 'dimension_weight': 1,
  295 + },
  296 + )
  297 + self.assertFalse(disabled['ok'])
  298 + self.assertEqual(disabled['error']['code'], 'invalid_arguments')
  299 +
  300 + def test_tool_definitions_are_complete_and_json_serializable(self):
  301 + definitions = self.tools.tool_definitions()
  302 + names = [definition['function']['name'] for definition in definitions]
  303 + self.assertEqual(names, [
  304 + 'recommendation_capabilities',
  305 + 'resolve_recommendation_dimension',
  306 + 'recall_similar_products',
  307 + 'recall_products_by_dimensions',
  308 + 'build_recommendation_candidates',
  309 + ])
  310 + json.dumps(definitions, ensure_ascii=False)
  311 +
  312 + def test_capabilities_report_current_loader_keys(self):
  313 + capabilities = self.tools.recommendation_capabilities()
  314 + patterns = {
  315 + item['name']: item['primary_key_pattern']
  316 + for item in capabilities['algorithms']
  317 + }
  318 + self.assertEqual(
  319 + patterns['session_w2v'],
  320 + 'item:similar:session_w2v:{item_id}',
  321 + )
  322 + self.assertEqual(
  323 + patterns['item_behavior'],
  324 + 'item:similar:item_behavior:{item_id}',
  325 + )
  326 +
  327 +
  328 +if __name__ == '__main__':
  329 + unittest.main(verbosity=2)
... ...
索引缺失问题排查.md
1   -请你重点关注有哪些维度的索引,各自数据的来龙去脉。
2   -现在在线推荐服务推荐结果都为空,经过检查时离线索引数据为空,请你检查这些索引清单(含用户特征相关和兜底维度),方便你逐项去离线侧核对/补齐。Redis DB 默认:推荐用 db3,用户画像用 snapshot_db(app_config 中 Redis snapshot_db,默认0)。
3   -一、首页猜你喜欢 /recommendation/home
4   -1) 用户行为 I2I(需要用户画像行为;无画像则这些路空)
5   -item:similar:swing_cpp:{sku} (key_name=user_behavior_click/purchase)
6   -item:similar:swing:{sku} (同上)
7   -item:similar:session_w2v:{sku}(同上)
8   -item:similar:deepwalk:{sku} (同上)
9   -item:similar:content_name:{sku}(同上)
10   -item:similar:content_pic:{sku} (同上)
11   -2) 用户品牌偏好(需要画像品牌;无画像则空)
12   -interest:hot:{brand_id} (key_name=user_brand_preference,模板 interest:hot:{key},key 为品牌ID字符串)
13   -3) 用户类目偏好 ES 召回(需要画像类目;无画像则空)
14   -直接查 ES sale_category_all,不依赖 Redis 索引。
15   -4) 用户行为类目 ES 召回(需要画像行为类目;无画像则空)
16   -同上,查 ES,不依赖 Redis 索引。
17   -5) 兜底兴趣聚合(无画像也应有结果,取决于这些 key 是否存在)
18   -平台热门:interest:hot:platform:{platform} 示例 interest:hot:platform:essaone
19   -全局热门:interest:global:global(模板 interest:global:{key},这里 key=global)
20   -若有客户端维度(目前配置中未直接用 client_key,但可检查是否有 interest:hot:client_platform:{client}、interest:hot:platform_client:{platform}_{client} 供扩展)
21   -二、详情页大家都在看 /recommendation/detail
22   -1) 当前商品 I2I(无画像也可用,只要有这些 key)
23   -item:similar:swing_cpp:{sku_id}
24   -item:similar:swing:{sku_id}
25   -item:similar:session_w2v:{sku_id}
26   -item:similar:deepwalk:{sku_id}
27   -item:similar:content_name:{sku_id}
28   -item:similar:content_pic:{sku_id}
29   -2) 用户行为 I2I(需要用户画像行为;无画像则空)
30   -同首页的行为 I2I 路径,依赖 item:similar:swing_cpp|swing|session_w2v|deepwalk|content_name|content_pic:{sku}
31   -三、Redis Key 模板(统一定义)
32   -I2I:item:similar:swing_cpp:{key} / swing / w2v / session_w2v / deepwalk / content_name / content_pic
33   -兴趣聚合:interest:hot:{key}、interest:cart:{key}、interest:new:{key}、interest:global:{key}
34   -四、需要检查/补齐的关键索引清单
35   -必须有(兜底与主干):
36   -interest:hot:platform:essaone(或对应平台)——首页兜底
37   -interest:global:global —— 首页兜底
38   -item:similar:swing_cpp:{sku} —— 详情页主路、首页行为召回
  1 +# 在线召回索引缺失排查
  2 +
  3 +本文用于定位“离线文件有数据但在线推荐为空”。当前 key 和 value 契约见 `offline_tasks/doc/Redis数据规范.md`。
  4 +
  5 +## 先确认请求真正需要的索引
  6 +
  7 +详情页当前商品召回:
  8 +
  9 +```text
  10 +item:similar:swing_cpp:{sku}
39 11 item:similar:swing:{sku}
40   -建议有(覆盖率/多样性):
41 12 item:similar:session_w2v:{sku}
42 13 item:similar:deepwalk:{sku}
43 14 item:similar:content_name:{sku}
44 15 item:similar:content_pic:{sku}
45   -可选/扩展兜底(若有产出):
  16 +item:similar:item_behavior:{sku}
  17 +```
  18 +
  19 +首页用户行为召回使用相同的 I2I key,但种子来自用户画像;无有效行为种子时这一路为空属于预期。
  20 +
  21 +画像与上下文召回:
  22 +
  23 +```text
  24 +interest:hot:platform:{platform}
  25 +interest:global:platform:{platform}
46 26 interest:hot:client_platform:{client}
47 27 interest:hot:platform_client:{platform}_{client}
48   -类目维度热门:interest:hot:category_level2:{id} 等(当前配置未直接用,但有数据可扩展)
49   -其他兴趣列表:interest:cart:*、interest:new:*
50   -五、用户画像数据
51   -Key 形如:user_profile:{user_id}(在 snapshot_db,默认 db0)。缺失画像会导致行为/偏好召回为空,但兜底热门仍可用,只要上述兴趣/全球热门 key 存在。
52   -你可以据此逐项在离线产出与 Redis db3/snapshot_db 里核对哪些 key 缺失,优先确保兜底热门与当前商品 I2I 存在
  28 +interest:hot:category_level2:{category_id}
  29 +interest:hot:platform_category2:{platform}_{category_id}
  30 +```
  31 +
  32 +当前离线任务不生产品牌维度,也不生产 `interest:global:global`。如果在线代码依赖 `interest:hot:{brand_id}` 或 `interest:global:global`,结果为空是生产/消费契约缺失,不是 Redis 故障。
  33 +
  34 +## 逐层核对
  35 +
  36 +1. 确认请求的 Redis host、port、DB 与加载任务完全一致;不要假设固定使用 DB 3。
  37 +2. 检查对应日期的离线文件存在且非空,并抽样确认第一列 key 后缀和最后一列 value。
  38 +3. 检查加载日志中的文件路径、loaded、skipped_old_keys、skipped_empty 和异常。
  39 +4. 使用 `SCAN` 确认 key 族存在,再对请求中的具体 SKU 或维度执行 `GET`。
  40 +5. 用 `item_id:score,...` 解析器验证 value;直接 `json.loads` 当前 value 会失败。
  41 +6. 检查 TTL,排除任务成功后 key 已过期、写到错误 DB 或被后续任务覆盖。
  42 +7. 检查用户画像是否确实提供种子 SKU、内部分类 ID 和平台内部值。
  43 +8. 最后检查实时商品过滤,避免召回非空但全部因下架、库存、地域、权限或重复曝光被删掉。
  44 +
  45 +示例命令:
  46 +
  47 +```bash
  48 +redis-cli --scan --pattern 'item:similar:swing:*' | head
  49 +redis-cli --scan --pattern 'interest:hot:platform:*' | head
  50 +redis-cli GET 'item:similar:swing:{sample_sku}'
  51 +redis-cli GET 'interest:hot:platform:{platform}'
  52 +redis-cli TTL 'interest:hot:platform:{platform}'
  53 +```
  54 +
  55 +认证信息使用 `REDISCLI_AUTH` 或部署平台的凭据注入,不写入文档和 shell 历史。
  56 +
  57 +## 推荐的在线降级
  58 +
  59 +```text
  60 +多算法 I2I 并行融合
  61 + -> 平台+分类等组合维度
  62 + -> 分类/平台单维度
  63 + -> 业务明确配置的兜底商品池
  64 +```
  65 +
  66 +现有 `global` 列表仍然按 platform/category/supplier 等维度聚合,并非无条件全站热门。若产品要求“任何请求必有结果”,应新增独立的全局兜底产出、加载 key、实时可售过滤和监控,而不是在调用侧猜一个不存在的 key。
  67 +
  68 +## 应补充的监控
  69 +
  70 +- 每种离线文件的行数、生成时间和解析成功率;
  71 +- 每种 Redis key 的写入数、TTL 和抽样一致性;
  72 +- 在线每路召回的请求数、hit rate、候选数和延迟;
  73 +- 用户画像覆盖率、有效种子数和内部维度 ID 命中率;
  74 +- 召回后实时过滤各原因的淘汰数;
  75 +- 最终空结果率及其分阶段归因。
  76 +
  77 +`offline_tasks/agent_tools` 的响应包含 `queried_key_count`、`hit_source_count`、`missing_keys_sample`、`malformed_source_count` 和候选数,可直接用于分路诊断。
53 78  
54   -请你分析日志,为什么没结果,并且给出完善的方案
  79 +更新日期:2026-08-23。
... ...