hello_agents_bridge.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. """工具桥接:把 PaperMind 工具注册表适配为 HelloAgents 框架的 ToolRegistry
  2. 项目的 Function Calling 工具通过桥接成为框架原生 Tool(ToolResponse 协议),
  3. 供框架的 SimpleAgent/ReActAgent 直接调度,享受框架的熔断器与参数校验能力。
  4. """
  5. from __future__ import annotations
  6. import asyncio
  7. import inspect
  8. import logging
  9. from typing import Any, Optional
  10. from hello_agents.tools.base import Tool, ToolParameter
  11. from hello_agents.tools.registry import ToolRegistry as HelloAgentsToolRegistry
  12. from hello_agents.tools.response import ToolResponse, ToolStatus
  13. from backend.tools.base import Tool as PaperMindTool
  14. from backend.tools.base import ToolRegistry as PaperMindToolRegistry
  15. logger = logging.getLogger(__name__)
  16. class PaperMindHelloAgentsTool(Tool):
  17. """框架 Tool 适配器:把 PaperMind 工具包装为框架原生工具
  18. - arun: 项目工具为 async 函数时直接 await
  19. - run: 同步执行(内部用事件循环驱动 async 工具)
  20. """
  21. def __init__(self, tool: PaperMindTool) -> None:
  22. super().__init__(name=tool.name, description=tool.description)
  23. self._func = tool.func
  24. self._schema = tool.to_schema()
  25. def to_openai_schema(self) -> dict[str, Any]:
  26. """直接沿用项目工具的 OpenAI function calling schema(参数定义更完整)"""
  27. return self._schema
  28. def get_parameters(self) -> list[ToolParameter]:
  29. """从项目工具 schema 转换出框架 ToolParameter 列表"""
  30. params: list[ToolParameter] = []
  31. properties = self._schema.get("function", {}).get("parameters", {}).get("properties", {})
  32. required = self._schema.get("function", {}).get("parameters", {}).get("required", [])
  33. for pname, pspec in properties.items():
  34. params.append(
  35. ToolParameter(
  36. name=pname,
  37. type=pspec.get("type", "string"),
  38. description=pspec.get("description", ""),
  39. required=pname in required,
  40. )
  41. )
  42. return params
  43. def run(self, parameters: dict[str, Any]) -> ToolResponse:
  44. """同步执行项目工具,返回框架 ToolResponse"""
  45. try:
  46. if inspect.iscoroutinefunction(self._func):
  47. result = asyncio.run(self._func(**parameters))
  48. else:
  49. result = self._func(**parameters)
  50. return self._to_success_response(result)
  51. except Exception as exc:
  52. logger.warning("工具 %s 执行失败: %s", self.name, exc)
  53. return ToolResponse(
  54. status=ToolStatus.ERROR,
  55. text=f"工具执行失败: {exc}",
  56. error_info={"tool": self.name, "message": str(exc)},
  57. )
  58. async def arun(self, parameters: dict[str, Any]) -> ToolResponse:
  59. """异步执行项目工具(优先路径),返回框架 ToolResponse"""
  60. try:
  61. if inspect.iscoroutinefunction(self._func):
  62. result = await self._func(**parameters)
  63. else:
  64. result = await asyncio.to_thread(self._func, **parameters)
  65. return self._to_success_response(result)
  66. except Exception as exc:
  67. logger.warning("工具 %s 执行失败: %s", self.name, exc)
  68. return ToolResponse(
  69. status=ToolStatus.ERROR,
  70. text=f"工具执行失败: {exc}",
  71. error_info={"tool": self.name, "message": str(exc)},
  72. )
  73. def _to_success_response(self, result: Any) -> ToolResponse:
  74. """把项目工具返回值转为 ToolResponse:字符串走 text,结构化对象走 data"""
  75. if isinstance(result, str):
  76. return ToolResponse(status=ToolStatus.SUCCESS, text=result)
  77. if isinstance(result, dict):
  78. return ToolResponse(status=ToolStatus.SUCCESS, text="ok", data=result)
  79. return ToolResponse(status=ToolStatus.SUCCESS, text=str(result))
  80. def build_hello_agents_registry(
  81. registry: PaperMindToolRegistry,
  82. tool_names: Optional[list[str]] = None,
  83. ) -> HelloAgentsToolRegistry:
  84. """把 PaperMind 工具注册表转换为 HelloAgents 框架工具注册表
  85. Args:
  86. registry: 项目工具注册表
  87. tool_names: 仅桥接指定工具子集(None 表示全部)
  88. Returns:
  89. HelloAgents ToolRegistry,框架 Agent 可直接使用
  90. """
  91. ha_registry = HelloAgentsToolRegistry()
  92. names = tool_names or registry.names()
  93. for name in names:
  94. tool = registry.get(name)
  95. if tool is None:
  96. logger.warning("桥接跳过:未注册的工具 %s", name)
  97. continue
  98. ha_registry.register_tool(PaperMindHelloAgentsTool(tool))
  99. return ha_registry