1
0

09_A2A_Network.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. """
  2. 10.3.3 使用 HelloAgents A2A 工具
  3. (3)创建Agent网络
  4. """
  5. from hello_agents.protocols import A2AServer, A2AClient
  6. import threading
  7. import time
  8. # 1. 创建多个Agent服务
  9. researcher = A2AServer(
  10. name="researcher",
  11. description="研究员"
  12. )
  13. @researcher.skill("research")
  14. def do_research(text: str) -> str:
  15. import re
  16. match = re.search(r'research\s+(.+)', text, re.IGNORECASE)
  17. topic = match.group(1).strip() if match else text
  18. return str({"topic": topic, "findings": f"{topic}的研究结果"})
  19. writer = A2AServer(
  20. name="writer",
  21. description="撰写员"
  22. )
  23. @writer.skill("write")
  24. def write_article(text: str) -> str:
  25. import re
  26. match = re.search(r'write\s+(.+)', text, re.IGNORECASE)
  27. content = match.group(1).strip() if match else text
  28. # 尝试解析研究数据
  29. try:
  30. data = eval(content)
  31. topic = data.get("topic", "未知主题")
  32. findings = data.get("findings", "无研究结果")
  33. except:
  34. topic = "未知主题"
  35. findings = content
  36. return f"# {topic}\n\n基于研究:{findings}\n\n文章内容..."
  37. editor = A2AServer(
  38. name="editor",
  39. description="编辑"
  40. )
  41. @editor.skill("edit")
  42. def edit_article(text: str) -> str:
  43. import re
  44. match = re.search(r'edit\s+(.+)', text, re.IGNORECASE)
  45. article = match.group(1).strip() if match else text
  46. result = {
  47. "article": article + "\n\n[已编辑优化]",
  48. "feedback": "文章质量良好",
  49. "approved": True
  50. }
  51. return str(result)
  52. # 2. 启动所有服务
  53. threading.Thread(target=lambda: researcher.run(port=5000), daemon=True).start()
  54. threading.Thread(target=lambda: writer.run(port=5001), daemon=True).start()
  55. threading.Thread(target=lambda: editor.run(port=5002), daemon=True).start()
  56. time.sleep(2) # 等待服务启动
  57. # 3. 创建客户端连接到各个Agent
  58. researcher_client = A2AClient("http://localhost:5000")
  59. writer_client = A2AClient("http://localhost:5001")
  60. editor_client = A2AClient("http://localhost:5002")
  61. # 4. 协作流程
  62. def create_content(topic):
  63. # 步骤1:研究
  64. research = researcher_client.execute_skill("research", f"research {topic}")
  65. research_data = research.get('result', '')
  66. # 步骤2:撰写
  67. article = writer_client.execute_skill("write", f"write {research_data}")
  68. article_content = article.get('result', '')
  69. # 步骤3:编辑
  70. final = editor_client.execute_skill("edit", f"edit {article_content}")
  71. return final.get('result', '')
  72. # 使用
  73. if __name__ == "__main__":
  74. result = create_content("AI在医疗领域的应用")
  75. print(f"\n最终结果:\n{result}")