webfetch.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """
  2. WebFetch Tool - 通过 Bun 适配器调用 OpenCode
  3. 网页抓取功能,包括 HTML 转 Markdown、内容提取等复杂逻辑。
  4. """
  5. from typing import Optional
  6. from agent.tools import tool, ToolResult, ToolContext
  7. from agent.tools.adapters.opencode_bun_adapter import OpenCodeBunAdapter
  8. # 创建适配器实例
  9. _adapter = None
  10. def _get_adapter():
  11. global _adapter
  12. if _adapter is None:
  13. _adapter = OpenCodeBunAdapter()
  14. return _adapter
  15. @tool(description="抓取网页内容并转换为 Markdown 格式")
  16. async def webfetch(
  17. url: str,
  18. format: str = "markdown",
  19. timeout: Optional[int] = None,
  20. uid: str = "",
  21. context: Optional[ToolContext] = None
  22. ) -> ToolResult:
  23. """
  24. 抓取网页内容
  25. 使用 OpenCode 的 webfetch 工具(通过 Bun 适配器调用)。
  26. 包含 HTML 到 Markdown 转换、内容清理等功能。
  27. Args:
  28. url: 网页 URL
  29. format: 输出格式(markdown, text, html),默认 markdown
  30. timeout: 超时时间(秒)
  31. uid: 用户 ID
  32. context: 工具上下文
  33. Returns:
  34. ToolResult: 网页内容
  35. """
  36. adapter = _get_adapter()
  37. args = {
  38. "url": url,
  39. "format": format,
  40. }
  41. if timeout is not None:
  42. args["timeout"] = timeout
  43. return await adapter.adapt_execute(
  44. tool_name="webfetch",
  45. args=args,
  46. context=context
  47. )