1
0

10_AgentNegotiation.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. 10.3.4 在智能体中使用A2A工具
  3. (3)高级用法:Agent间协商
  4. """
  5. from hello_agents.protocols import A2AServer, A2AClient
  6. import threading
  7. import time
  8. # 创建两个需要协商的Agent
  9. agent1 = A2AServer(
  10. name="agent1",
  11. description="Agent 1"
  12. )
  13. @agent1.skill("propose")
  14. def handle_proposal(text: str) -> str:
  15. """处理协商提案"""
  16. import re
  17. import json
  18. # 解析提案
  19. match = re.search(r'propose\s+(.+)', text, re.IGNORECASE)
  20. proposal_str = match.group(1).strip() if match else text
  21. try:
  22. proposal = eval(proposal_str)
  23. task = proposal.get("task")
  24. deadline = proposal.get("deadline")
  25. # 评估提案
  26. if deadline >= 7: # 至少需要7天
  27. result = {"accepted": True, "message": "接受提案"}
  28. else:
  29. result = {
  30. "accepted": False,
  31. "message": "时间太紧",
  32. "counter_proposal": {"deadline": 7}
  33. }
  34. return str(result)
  35. except:
  36. return str({"accepted": False, "message": "无效的提案格式"})
  37. agent2 = A2AServer(
  38. name="agent2",
  39. description="Agent 2"
  40. )
  41. @agent2.skill("negotiate")
  42. def negotiate_task(text: str) -> str:
  43. """发起协商"""
  44. import re
  45. # 解析任务和截止日期
  46. match = re.search(r'negotiate\s+task:(.+?)\s+deadline:(\d+)', text, re.IGNORECASE)
  47. if match:
  48. task = match.group(1).strip()
  49. deadline = int(match.group(2))
  50. # 向agent1发送提案
  51. proposal = {"task": task, "deadline": deadline}
  52. return str({"status": "negotiating", "proposal": proposal})
  53. else:
  54. return str({"status": "error", "message": "无效的协商请求"})
  55. # 启动服务
  56. if __name__ == "__main__":
  57. threading.Thread(target=lambda: agent1.run(port=7000), daemon=True).start()
  58. threading.Thread(target=lambda: agent2.run(port=7001), daemon=True).start()
  59. time.sleep(2)
  60. # 测试协商流程
  61. client1 = A2AClient("http://localhost:7000")
  62. client2 = A2AClient("http://localhost:7001")
  63. # Agent2发起协商
  64. negotiation = client2.execute_skill("negotiate", "negotiate task:开发新功能 deadline:5")
  65. print(f"协商请求:{negotiation.get('result')}")
  66. # Agent1评估提案
  67. proposal = client1.execute_skill("propose", "propose {'task': '开发新功能', 'deadline': 5}")
  68. print(f"提案评估:{proposal.get('result')}")
  69. # 保持服务运行
  70. try:
  71. while True:
  72. time.sleep(1)
  73. except KeyboardInterrupt:
  74. print("\n服务已停止")