ddg_search.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """仅用 DuckDuckGo 的轻量检索,避免 HelloAgents SearchTool 初始化时打印 Tavily/SerpAPI 提示。"""
  2. from __future__ import annotations
  3. def duckduckgo_search_text(
  4. query: str,
  5. *,
  6. max_results: int = 4,
  7. max_body_chars: int = 600,
  8. ) -> str:
  9. query = (query or "").strip()
  10. if not query:
  11. return "【检索】查询为空。"
  12. try:
  13. from ddgs import DDGS
  14. except ImportError:
  15. return "【检索】未安装 duckduckgo-search,请执行:pip install duckduckgo-search"
  16. try:
  17. with DDGS(timeout=15) as client: # type: ignore[call-arg]
  18. rows = client.text(query, max_results=max_results, backend="duckduckgo")
  19. except Exception as e: # pragma: no cover
  20. return f"【检索】DuckDuckGo 请求失败:{e}"
  21. if not rows:
  22. return "【检索】无结果。"
  23. lines: list[str] = ["【DuckDuckGo 检索摘要】"]
  24. for i, entry in enumerate(rows, 1):
  25. url = entry.get("href") or entry.get("url") or ""
  26. title = entry.get("title") or url or "(无标题)"
  27. body = entry.get("body") or entry.get("content") or ""
  28. if len(body) > max_body_chars:
  29. body = body[:max_body_chars] + "…"
  30. lines.append(f"{i}. {title}\n {url}\n {body}")
  31. return "\n\n".join(lines)