Blame view

app/tools/search_tools.py 17.6 KB
e7f2b240   tangwang   first commit
1
2
  """
  Search Tools for Product Discovery
66442668   tangwang   feat: 搜索结果引用与并行搜索...
3
  
5e3d6d3a   tangwang   refactor(search):...
4
  - search_products is created via make_search_products_tool(session_id, registry).
621b6925   tangwang   up
5
  - After search API, an LLM labels each result as Relevant / Partially Relevant / Irrelevant; we count and
897b5ca9   tangwang   perf: 前端性能优化 + 搜索...
6
    store the curated list in the registry, return [SEARCH_RESULTS_REF:ref_id] + quality counts + top10 titles.
e7f2b240   tangwang   first commit
7
8
9
  """
  
  import base64
66442668   tangwang   feat: 搜索结果引用与并行搜索...
10
  import json
e7f2b240   tangwang   first commit
11
  import logging
46f8dd12   tangwang   1. add prod under...
12
  import os
e7f2b240   tangwang   first commit
13
14
15
  from pathlib import Path
  from typing import Optional
  
8810a6fa   tangwang   重构
16
  import requests
e7f2b240   tangwang   first commit
17
18
19
20
  from langchain_core.tools import tool
  from openai import OpenAI
  
  from app.config import settings
66442668   tangwang   feat: 搜索结果引用与并行搜索...
21
22
23
24
25
  from app.search_registry import (
      ProductItem,
      SearchResult,
      SearchResultRegistry,
      global_registry,
66442668   tangwang   feat: 搜索结果引用与并行搜索...
26
  )
e7f2b240   tangwang   first commit
27
28
29
  
  logger = logging.getLogger(__name__)
  
e7f2b240   tangwang   first commit
30
31
32
  _openai_client: Optional[OpenAI] = None
  
  
825828c4   tangwang   fix: search image...
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  def _normalize_image_url(url: Optional[str]) -> Optional[str]:
      """Normalize image_url from API (e.g. ////cnres.appracle.com/... → https://cnres.appracle.com/...)."""
      if not url or not isinstance(url, str):
          return None
      url = url.strip()
      if not url:
          return None
      if url.startswith("https://") or url.startswith("http://"):
          return url
      # // or ////host/path → https://host/path (exactly one "//" after scheme)
      if url.startswith("/"):
          return "https://" + url.lstrip("/")
      return "https://" + url
  
  
e7f2b240   tangwang   first commit
48
49
50
  def get_openai_client() -> OpenAI:
      global _openai_client
      if _openai_client is None:
8810a6fa   tangwang   重构
51
52
53
54
          kwargs = {"api_key": settings.openai_api_key}
          if settings.openai_api_base_url:
              kwargs["base_url"] = settings.openai_api_base_url
          _openai_client = OpenAI(**kwargs)
e7f2b240   tangwang   first commit
55
56
57
      return _openai_client
  
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
58
59
  # ── LLM quality assessment ─────────────────────────────────────────────────────
  
5e3d6d3a   tangwang   refactor(search):...
60
  def _assess_search_quality(query: str, raw_products: list) -> tuple[list[str], str]:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
61
      """
5e3d6d3a   tangwang   refactor(search):...
62
63
      Use LLM to label each search result and write a short quality_summary.
      Returns (labels, quality_summary). labels: one per product; quality_summary: 12 sentences.
66442668   tangwang   feat: 搜索结果引用与并行搜索...
64
65
66
      """
      n = len(raw_products)
      if n == 0:
5e3d6d3a   tangwang   refactor(search):...
67
          return [], ""
66442668   tangwang   feat: 搜索结果引用与并行搜索...
68
  
5e3d6d3a   tangwang   refactor(search):...
69
      lines = []
66442668   tangwang   feat: 搜索结果引用与并行搜索...
70
71
      for i, p in enumerate(raw_products, 1):
          title = (p.get("title") or "")[:60]
5e3d6d3a   tangwang   refactor(search):...
72
          lines.append(f"{i}. {title}")
66442668   tangwang   feat: 搜索结果引用与并行搜索...
73
74
      product_text = "\n".join(lines)
  
5e3d6d3a   tangwang   refactor(search):...
75
      prompt = f"""评估以下搜索结果与用户查询的匹配程度,完成两件事:
621b6925   tangwang   up
76
  1. 为每条结果打一个等级:Relevant / Partially Relevant / Irrelevant
5e3d6d3a   tangwang   refactor(search):...
77
  2. 写一段 quality_summary12 句话):简要说明搜索结果主要包含哪些商品、是否基本满足搜索意图、整体匹配度如何。
66442668   tangwang   feat: 搜索结果引用与并行搜索...
78
79
80
  
  用户查询:{query}
  
5e3d6d3a   tangwang   refactor(search):...
81
  搜索结果(共 {n} 条):
66442668   tangwang   feat: 搜索结果引用与并行搜索...
82
83
  {product_text}
  
50fcfb9d   tangwang   up
84
85
86
87
88
89
90
91
92
  等级说明:
  Relevant
  The product generally satisfies the main shopping intent of the query. Minor missing, implicit, or unspecified attributes are acceptable as long as the product reasonably fits the intended use or scenario.
  
  Partially Relevant
  The product is related to the query and matches the general category or purpose, but shows weaker alignment with the specific intent or context.
  
  Irrelevant
  The product does not match the core intent or intended use implied by the query.
66442668   tangwang   feat: 搜索结果引用与并行搜索...
93
  
5e3d6d3a   tangwang   refactor(search):...
94
  请严格按以下 JSON 输出,仅输出 JSON,无其他内容:
621b6925   tangwang   up
95
  {{"labels": ["Relevant", "Partially Relevant", "Irrelevant", ...], "quality_summary": "你的1-2句总结"}}
5e3d6d3a   tangwang   refactor(search):...
96
  labels 数组长度必须等于 {n}"""
66442668   tangwang   feat: 搜索结果引用与并行搜索...
97
98
99
100
101
102
  
      try:
          client = get_openai_client()
          resp = client.chat.completions.create(
              model=settings.openai_model,
              messages=[{"role": "user", "content": prompt}],
621b6925   tangwang   up
103
              max_tokens=1200,
66442668   tangwang   feat: 搜索结果引用与并行搜索...
104
105
106
              temperature=0.1,
          )
          raw = resp.choices[0].message.content.strip()
66442668   tangwang   feat: 搜索结果引用与并行搜索...
107
108
109
110
111
          if raw.startswith("```"):
              raw = raw.split("```")[1]
              if raw.startswith("json"):
                  raw = raw[4:]
          raw = raw.strip()
66442668   tangwang   feat: 搜索结果引用与并行搜索...
112
          data = json.loads(raw)
5e3d6d3a   tangwang   refactor(search):...
113
          labels = data.get("labels", [])
621b6925   tangwang   up
114
          valid = {"Relevant", "Partially Relevant", "Irrelevant"}
5e3d6d3a   tangwang   refactor(search):...
115
          labels = [l if l in valid else "Partially Relevant" for l in labels]
66442668   tangwang   feat: 搜索结果引用与并行搜索...
116
          while len(labels) < n:
5e3d6d3a   tangwang   refactor(search):...
117
118
119
              labels.append("Partially Relevant")
          quality_summary = (data.get("quality_summary") or "").strip() or ""
          return labels[:n], quality_summary
66442668   tangwang   feat: 搜索结果引用与并行搜索...
120
      except Exception as e:
5e3d6d3a   tangwang   refactor(search):...
121
122
          logger.warning(f"Quality assessment failed: {e}; using fallback.")
          return ["Partially Relevant"] * n, ""
66442668   tangwang   feat: 搜索结果引用与并行搜索...
123
124
  
  
897b5ca9   tangwang   perf: 前端性能优化 + 搜索...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
  # ── Shared search implementation ──────────────────────────────────────────────
  
  def _call_search_api(query: str, size: int) -> Optional[tuple[list, int]]:
      """Call product search API. Returns (raw_results, total_hits) or None on failure."""
      if not query or not query.strip():
          return None
      try:
          url = f"{settings.search_api_base_url.rstrip('/')}/search/"
          headers = {
              "Content-Type": "application/json",
              "X-Tenant-ID": settings.search_api_tenant_id,
          }
          payload = {
              "query": query.strip(),
              "size": min(max(size, 1), 20),
              "from": 0,
              "language": "zh",
              "enable_rerank": True,
              "rerank_query_template": query.strip(),
              "rerank_doc_template": "{title}",
          }
          resp = requests.post(url, json=payload, headers=headers, timeout=60)
          if resp.status_code != 200:
              logger.warning(f"Search API {resp.status_code}: {resp.text[:200]}")
              return None
          data = resp.json()
          raw_results: list = data.get("results", [])
          total_hits: int = data.get("total", 0)
          return (raw_results, total_hits)
      except Exception as e:
          logger.warning(f"Search API error: {e}")
          return None
  
  
  def _raw_to_product_items(
      raw_results: list, labels: Optional[list[str]] = None
  ) -> list[ProductItem]:
      """Build ProductItem list from API raw results. If labels given, filter by Relevant/Partially Relevant."""
      if labels is not None:
          valid = {"Relevant", "Partially Relevant"}
          return [
              ProductItem(
                  spu_id=str(r.get("spu_id", "")),
                  title=r.get("title") or "",
                  price=r.get("price"),
                  category_path=r.get("category_path") or r.get("category_name"),
                  vendor=r.get("vendor"),
                  image_url=_normalize_image_url(r.get("image_url")),
                  relevance_score=r.get("relevance_score"),
                  match_label=label,
                  tags=r.get("tags") or [],
                  specifications=r.get("specifications") or [],
              )
              for r, label in zip(raw_results, labels)
              if label in valid
          ]
      return [
          ProductItem(
              spu_id=str(r.get("spu_id", "")),
              title=r.get("title") or "",
              price=r.get("price"),
              category_path=r.get("category_path") or r.get("category_name"),
              vendor=r.get("vendor"),
              image_url=_normalize_image_url(r.get("image_url")),
              relevance_score=r.get("relevance_score"),
              match_label="Partially Relevant",
              tags=r.get("tags") or [],
              specifications=r.get("specifications") or [],
          )
          for r in raw_results
      ]
  
  
  def search_products_impl(
      query: str,
      limit: int = 20,
      *,
      assess_quality: bool = True,
      session_id: Optional[str] = None,
      registry: Optional[SearchResultRegistry] = None,
  ) -> tuple[Optional[str], list[ProductItem], int]:
      """
      Single implementation: call API, optionally run LLM assessment, optionally register.
      Returns (ref_id_or_none, products, assessed_count). assessed_count = len(raw_results) when assess_quality else 0.
      """
      out = _call_search_api(query, limit)
      if not out:
          return (None, [], 0)
      raw_results, total_hits = out
      if not raw_results:
          return (None, [], 0)
  
      if assess_quality and session_id and registry:
          labels, quality_summary = _assess_search_quality(query, raw_results)
          products = _raw_to_product_items(raw_results, labels)
          perfect_count = sum(1 for l in labels if l == "Relevant")
          partial_count = sum(1 for l in labels if l == "Partially Relevant")
          ref_id = registry.next_ref_id(session_id)
          result = SearchResult(
              ref_id=ref_id,
              query=query,
              total_api_hits=total_hits,
              returned_count=len(raw_results),
              perfect_count=perfect_count,
              partial_count=partial_count,
              irrelevant_count=len(labels) - perfect_count - partial_count,
              quality_summary=quality_summary,
              products=products,
          )
          registry.register(session_id, result)
          logger.info(
              "[%s] Registered %s: query=%s perfect=%s partial=%s",
              session_id, ref_id, query, perfect_count, partial_count,
          )
          return (ref_id, products, len(raw_results))
      products = _raw_to_product_items(raw_results)
      return (None, products, 0)
  
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
244
245
246
247
248
249
250
251
  # ── Tool factory ───────────────────────────────────────────────────────────────
  
  def make_search_products_tool(
      session_id: str,
      registry: SearchResultRegistry,
  ):
      """
      Return a search_products tool bound to a specific session and registry.
897b5ca9   tangwang   perf: 前端性能优化 + 搜索...
252
      Uses LLM assessment and registers result; returns [SEARCH_RESULTS_REF:ref_id] string.
66442668   tangwang   feat: 搜索结果引用与并行搜索...
253
254
255
      """
  
      @tool
50fcfb9d   tangwang   up
256
      def search_products(query: str) -> str:
621b6925   tangwang   up
257
          """搜索商品库并做质量评估:LLM 为每条结果打等级(Relevant / Partially Relevant / Irrelevant),返回引用与 top10 标题。
66442668   tangwang   feat: 搜索结果引用与并行搜索...
258
259
  
          Args:
5e3d6d3a   tangwang   refactor(search):...
260
              query: 自然语言商品描述
66442668   tangwang   feat: 搜索结果引用与并行搜索...
261
262
  
          Returns:
897b5ca9   tangwang   perf: 前端性能优化 + 搜索...
263
              【搜索完成】+ 结果引用 [SEARCH_RESULTS_REF:ref_id] + 质量情况 + results listtop10 标题)
66442668   tangwang   feat: 搜索结果引用与并行搜索...
264
265
          """
          try:
50fcfb9d   tangwang   up
266
              limit = min(max(settings.search_products_limit, 1), 20)
66442668   tangwang   feat: 搜索结果引用与并行搜索...
267
              logger.info(f"[{session_id}] search_products: query={query!r} limit={limit}")
897b5ca9   tangwang   perf: 前端性能优化 + 搜索...
268
269
270
271
272
              ref_id, products, assessed_n = search_products_impl(
                  query, limit,
                  assess_quality=True,
                  session_id=session_id,
                  registry=registry,
66442668   tangwang   feat: 搜索结果引用与并行搜索...
273
              )
897b5ca9   tangwang   perf: 前端性能优化 + 搜索...
274
275
276
277
278
279
280
281
282
283
              if ref_id is None:
                  if not products:
                      return (
                          f"【搜索完成】query='{query}'\n"
                          "未找到匹配商品,建议换用更宽泛或不同角度的关键词重新搜索。"
                      )
                  return f"搜索失败:API 返回异常,请稍后重试。"
              perfect_count = sum(1 for p in products if p.match_label == "Relevant")
              partial_count = sum(1 for p in products if p.match_label == "Partially Relevant")
              top10_titles = [(p.title or "未知")[:80] for p in products[:10]]
5e3d6d3a   tangwang   refactor(search):...
284
              results_list = "\n".join(f"{i}. {t}" for i, t in enumerate(top10_titles, 1))
66442668   tangwang   feat: 搜索结果引用与并行搜索...
285
286
              return (
                  f"【搜索完成】query='{query}'\n"
897b5ca9   tangwang   perf: 前端性能优化 + 搜索...
287
                  f"结果引用:[SEARCH_RESULTS_REF:{ref_id}]\n"
621b6925   tangwang   up
288
                  f"搜索结果质量情况:评估总条数{assessed_n}条,Relevant {perfect_count} 条,Partially Relevant {partial_count} 条。\n"
5e3d6d3a   tangwang   refactor(search):...
289
                  f"results list:\n{results_list}"
66442668   tangwang   feat: 搜索结果引用与并行搜索...
290
              )
66442668   tangwang   feat: 搜索结果引用与并行搜索...
291
292
293
294
295
296
297
298
299
300
          except requests.exceptions.RequestException as e:
              logger.error(f"[{session_id}] Search network error: {e}", exc_info=True)
              return f"搜索失败(网络错误):{e}"
          except Exception as e:
              logger.error(f"[{session_id}] Search error: {e}", exc_info=True)
              return f"搜索失败:{e}"
  
      return search_products
  
  
897b5ca9   tangwang   perf: 前端性能优化 + 搜索...
301
302
303
304
305
306
  def search_products_api_only(query: str, limit: int = 12) -> list[ProductItem]:
      """API-only search (no LLM assessment). For 'Similar products' side panel."""
      _, products, _ = search_products_impl(query, limit, assess_quality=False)
      return products
  
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
307
308
  # ── Standalone tools (no session binding needed) ───────────────────────────────
  
e7f2b240   tangwang   first commit
309
  @tool
46f8dd12   tangwang   1. add prod under...
310
311
312
  def web_search(query: str) -> str:
      """使用 Tavily 进行通用 Web 搜索,补充外部/实时知识。
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
313
314
      触发场景:
      - 需要**外部知识**:流行趋势、品牌、搭配文化、节日习俗等
621b6925   tangwang   up
315
      - 需要**实时/及时信息**:所有与天气相关的问题、当季流行元素、某地近期或者未来的事件、所有依赖当前时间相关的信息
66442668   tangwang   feat: 搜索结果引用与并行搜索...
316
      - 需要**宏观参考**:不同场合/国家的穿着建议、选购攻略
46f8dd12   tangwang   1. add prod under...
317
318
  
      Args:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
319
          query: 要搜索的问题,自然语言描述
46f8dd12   tangwang   1. add prod under...
320
321
  
      Returns:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
322
          总结后的回答 + 若干参考来源链接
46f8dd12   tangwang   1. add prod under...
323
324
325
326
      """
      try:
          api_key = os.getenv("TAVILY_API_KEY")
          if not api_key:
46f8dd12   tangwang   1. add prod under...
327
328
329
330
331
              return (
                  "无法调用外部 Web 搜索:未检测到 TAVILY_API_KEY 环境变量。\n"
                  "请在运行环境中配置 TAVILY_API_KEY 后再重试。"
              )
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
332
          logger.info(f"web_search: {query!r}")
46f8dd12   tangwang   1. add prod under...
333
334
335
336
337
338
339
340
341
342
343
  
          url = "https://api.tavily.com/search"
          headers = {
              "Authorization": f"Bearer {api_key}",
              "Content-Type": "application/json",
          }
          payload = {
              "query": query,
              "search_depth": "advanced",
              "include_answer": True,
          }
46f8dd12   tangwang   1. add prod under...
344
345
346
          response = requests.post(url, json=payload, headers=headers, timeout=60)
  
          if response.status_code != 200:
46f8dd12   tangwang   1. add prod under...
347
348
349
350
351
352
353
354
355
356
357
358
              return f"调用外部 Web 搜索失败:Tavily 返回状态码 {response.status_code}"
  
          data = response.json()
          answer = data.get("answer") or "(Tavily 未返回直接回答,仅返回了搜索结果。)"
          results = data.get("results") or []
  
          output_lines = [
              "【外部 Web 搜索结果(Tavily)】",
              "",
              "回答摘要:",
              answer.strip(),
          ]
46f8dd12   tangwang   1. add prod under...
359
360
361
362
363
          if results:
              output_lines.append("")
              output_lines.append("参考来源(部分):")
              for idx, item in enumerate(results[:5], 1):
                  title = item.get("title") or "无标题"
66442668   tangwang   feat: 搜索结果引用与并行搜索...
364
                  link = item.get("url") or ""
46f8dd12   tangwang   1. add prod under...
365
                  output_lines.append(f"{idx}. {title}")
66442668   tangwang   feat: 搜索结果引用与并行搜索...
366
367
                  if link:
                      output_lines.append(f"   链接: {link}")
46f8dd12   tangwang   1. add prod under...
368
369
370
371
  
          return "\n".join(output_lines).strip()
  
      except requests.exceptions.RequestException as e:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
372
          logger.error("web_search network error: %s", e, exc_info=True)
46f8dd12   tangwang   1. add prod under...
373
374
          return f"调用外部 Web 搜索失败(网络错误):{e}"
      except Exception as e:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
375
          logger.error("web_search error: %s", e, exc_info=True)
46f8dd12   tangwang   1. add prod under...
376
377
378
379
          return f"调用外部 Web 搜索失败:{e}"
  
  
  @tool
e7f2b240   tangwang   first commit
380
  def analyze_image_style(image_path: str) -> str:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
381
      """分析用户上传的商品图片,提取视觉风格属性,用于后续商品搜索。
e7f2b240   tangwang   first commit
382
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
383
384
385
      适用场景:
      - 用户上传图片,想找相似商品
      - 需要理解图片中商品的风格、颜色、材质等属性
e7f2b240   tangwang   first commit
386
387
  
      Args:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
388
          image_path: 图片文件路径
e7f2b240   tangwang   first commit
389
390
  
      Returns:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
391
          商品视觉属性的详细文字描述,可直接作为 search_products  query
e7f2b240   tangwang   first commit
392
393
      """
      try:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
394
          logger.info(f"analyze_image_style: {image_path!r}")
e7f2b240   tangwang   first commit
395
396
397
  
          img_path = Path(image_path)
          if not img_path.exists():
66442668   tangwang   feat: 搜索结果引用与并行搜索...
398
              return f"错误:图片文件不存在:{image_path}"
e7f2b240   tangwang   first commit
399
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
400
401
          with open(img_path, "rb") as f:
              image_data = base64.b64encode(f.read()).decode("utf-8")
e7f2b240   tangwang   first commit
402
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
403
          prompt = """请分析这张商品图片,提供详细的视觉属性描述,用于商品搜索。
e7f2b240   tangwang   first commit
404
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
405
406
407
408
409
410
411
  请包含:
  - 商品类型(如:连衣裙、运动鞋、双肩包、西装等)
  - 主要颜色
  - 风格定位(如:休闲、正式、运动、复古、现代简约等)
  - 图案/纹理(如:纯色、条纹、格纹、碎花、几何图案等)
  - 关键设计特征(如:领型、袖长、版型、材质外观等)
  - 适用场合(如:办公、户外、度假、聚会、运动等)
e7f2b240   tangwang   first commit
412
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
413
  输出格式:3-4句自然语言描述,可直接用作搜索关键词。"""
e7f2b240   tangwang   first commit
414
415
416
  
          client = get_openai_client()
          response = client.chat.completions.create(
46f8dd12   tangwang   1. add prod under...
417
              model=settings.openai_vision_model,
e7f2b240   tangwang   first commit
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
              messages=[
                  {
                      "role": "user",
                      "content": [
                          {"type": "text", "text": prompt},
                          {
                              "type": "image_url",
                              "image_url": {
                                  "url": f"data:image/jpeg;base64,{image_data}",
                                  "detail": "high",
                              },
                          },
                      ],
                  }
              ],
621b6925   tangwang   up
433
              max_tokens=800,
e7f2b240   tangwang   first commit
434
435
436
437
              temperature=0.3,
          )
  
          analysis = response.choices[0].message.content.strip()
66442668   tangwang   feat: 搜索结果引用与并行搜索...
438
          logger.info("Image analysis completed.")
e7f2b240   tangwang   first commit
439
440
441
          return analysis
  
      except Exception as e:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
442
443
          logger.error(f"analyze_image_style error: {e}", exc_info=True)
          return f"图片分析失败:{e}"
e7f2b240   tangwang   first commit
444
445
  
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
  # ── Tool list factory ──────────────────────────────────────────────────────────
  
  def get_all_tools(
      session_id: str = "default",
      registry: Optional[SearchResultRegistry] = None,
  ) -> list:
      """
      Return all agent tools.
  
      search_products is session-bound (factory); other tools are stateless.
      """
      if registry is None:
          registry = global_registry
      return [
          make_search_products_tool(session_id, registry),
          analyze_image_style,
          web_search,
      ]