1
0

09_A2A_WithAgent.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. """
  2. A2A 协议 + HelloAgents SimpleAgent 集成案例
  3. 展示如何将 A2A 协议的 Agent 作为工具集成到 SimpleAgent 中
  4. """
  5. from hello_agents.protocols import A2AServer, A2AClient
  6. from hello_agents import SimpleAgent, HelloAgentsLLM
  7. from hello_agents.tools import ToolRegistry, Tool, ToolParameter
  8. import threading
  9. import time
  10. from typing import Dict, Any
  11. # ============================================================
  12. # 1. 创建专业 A2A Agent 服务
  13. # ============================================================
  14. # 技术专家 Agent
  15. tech_expert = A2AServer(
  16. name="tech_expert",
  17. description="技术专家,回答技术相关问题",
  18. version="1.0.0"
  19. )
  20. @tech_expert.skill("answer")
  21. def answer_tech_question(text: str) -> str:
  22. """回答技术问题"""
  23. import re
  24. match = re.search(r'answer\s+(.+)', text, re.IGNORECASE)
  25. question = match.group(1).strip() if match else text
  26. print(f" [技术专家] 回答问题: {question}")
  27. return f"技术回答:关于'{question}',这是一个技术问题的专业解答..."
  28. # 销售顾问 Agent
  29. sales_advisor = A2AServer(
  30. name="sales_advisor",
  31. description="销售顾问,回答销售问题",
  32. version="1.0.0"
  33. )
  34. @sales_advisor.skill("answer")
  35. def answer_sales_question(text: str) -> str:
  36. """回答销售问题"""
  37. import re
  38. match = re.search(r'answer\s+(.+)', text, re.IGNORECASE)
  39. question = match.group(1).strip() if match else text
  40. print(f" [销售顾问] 回答问题: {question}")
  41. return f"销售回答:关于'{question}',我们有特别优惠..."
  42. # ============================================================
  43. # 2. 启动 A2A Agent 服务
  44. # ============================================================
  45. print("="*60)
  46. print("🚀 启动专业 Agent 服务")
  47. print("="*60)
  48. threading.Thread(target=lambda: tech_expert.run(port=6000), daemon=True).start()
  49. threading.Thread(target=lambda: sales_advisor.run(port=6001), daemon=True).start()
  50. print("✓ 技术专家 Agent 启动在 http://localhost:6000")
  51. print("✓ 销售顾问 Agent 启动在 http://localhost:6001")
  52. print("\n⏳ 等待服务启动...")
  53. time.sleep(3)
  54. # ============================================================
  55. # 3. 创建 A2A 工具(封装 A2A Agent 为 Tool)
  56. # ============================================================
  57. class A2ATool(Tool):
  58. """将 A2A Agent 封装为 HelloAgents Tool"""
  59. def __init__(self, name: str, description: str, agent_url: str, skill_name: str = "answer"):
  60. self.agent_url = agent_url
  61. self.skill_name = skill_name
  62. self.client = A2AClient(agent_url)
  63. self._name = name
  64. self._description = description
  65. self._parameters = [
  66. ToolParameter(
  67. name="question",
  68. type="string",
  69. description="要问的问题",
  70. required=True
  71. )
  72. ]
  73. @property
  74. def name(self) -> str:
  75. return self._name
  76. @property
  77. def description(self) -> str:
  78. return self._description
  79. def get_parameters(self) -> list[ToolParameter]:
  80. """获取工具参数"""
  81. return self._parameters
  82. def run(self, **kwargs) -> str:
  83. """执行工具"""
  84. question = kwargs.get('question', '')
  85. result = self.client.execute_skill(self.skill_name, f"answer {question}")
  86. if result.get('status') == 'success':
  87. return result.get('result', 'No response')
  88. else:
  89. return f"Error: {result.get('error', 'Unknown error')}"
  90. # 创建工具
  91. tech_tool = A2ATool(
  92. name="tech_expert",
  93. description="技术专家,回答技术相关问题",
  94. agent_url="http://localhost:6000"
  95. )
  96. sales_tool = A2ATool(
  97. name="sales_advisor",
  98. description="销售顾问,回答销售相关问题",
  99. agent_url="http://localhost:6001"
  100. )
  101. # ============================================================
  102. # 4. 创建 SimpleAgent(使用 A2A 工具)
  103. # ============================================================
  104. print("\n" + "="*60)
  105. print("🤖 创建接待员 SimpleAgent")
  106. print("="*60)
  107. # 初始化 LLM
  108. llm = HelloAgentsLLM()
  109. # 创建接待员 Agent
  110. receptionist = SimpleAgent(
  111. name="接待员",
  112. llm=llm,
  113. system_prompt="""你是客服接待员,负责:
  114. 1. 分析客户问题类型(技术问题 or 销售问题)
  115. 2. 使用合适的工具(tech_expert 或 sales_advisor)获取答案
  116. 3. 整理答案并返回给客户
  117. 可用工具:
  118. - tech_expert: 回答技术问题
  119. - sales_advisor: 回答销售问题
  120. 请保持礼貌和专业。"""
  121. )
  122. # 添加 A2A 工具
  123. receptionist.add_tool(tech_tool)
  124. receptionist.add_tool(sales_tool)
  125. print("✓ 接待员 Agent 创建完成")
  126. print("✓ 已集成 A2A 工具: tech_expert, sales_advisor")
  127. # ============================================================
  128. # 5. 测试集成系统
  129. # ============================================================
  130. print("\n" + "="*60)
  131. print("🧪 测试 A2A + SimpleAgent 集成")
  132. print("="*60)
  133. # 测试问题
  134. test_questions = [
  135. "你们的产品有什么优惠活动吗?",
  136. "如何配置服务器的SSL证书?",
  137. "我想了解一下价格方案"
  138. ]
  139. for i, question in enumerate(test_questions, 1):
  140. print(f"\n问题 {i}: {question}")
  141. print("-" * 60)
  142. try:
  143. # 使用 SimpleAgent 的 run 方法
  144. response = receptionist.run(question)
  145. print(f"回答: {response}")
  146. except Exception as e:
  147. print(f"错误: {str(e)}")
  148. import traceback
  149. traceback.print_exc()
  150. print()
  151. # ============================================================
  152. # 6. 保持服务运行
  153. # ============================================================
  154. print("="*60)
  155. print("💡 系统仍在运行")
  156. print("="*60)
  157. print("你可以继续测试或按 Ctrl+C 停止\n")
  158. try:
  159. while True:
  160. time.sleep(1)
  161. except KeyboardInterrupt:
  162. print("\n\n✅ 系统已停止")