08_CustomA2AAgent.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from hello_agents.protocols.a2a.implementation import A2AServer, A2A_AVAILABLE
  2. def create_custom_agent():
  3. """创建自定义智能体"""
  4. if not A2A_AVAILABLE:
  5. print("请先安装 A2A SDK: pip install a2a-sdk")
  6. return None
  7. # 创建智能体
  8. agent = A2AServer(
  9. name="my-custom-agent",
  10. description="我的自定义智能体",
  11. capabilities={"custom": ["skill1", "skill2"]}
  12. )
  13. # 添加技能
  14. @agent.skill("greet")
  15. def greet_user(name: str) -> str:
  16. """问候用户"""
  17. return f"你好,{name}!我是自定义智能体。"
  18. @agent.skill("calculate")
  19. def simple_calculate(expression: str) -> str:
  20. """简单计算"""
  21. try:
  22. # 安全的计算(仅支持基本运算)
  23. allowed_chars = set('0123456789+-*/(). ')
  24. if all(c in allowed_chars for c in expression):
  25. result = eval(expression)
  26. return f"计算结果: {expression} = {result}"
  27. else:
  28. return "错误: 只支持基本数学运算"
  29. except Exception as e:
  30. return f"计算错误: {e}"
  31. return agent
  32. # 创建并测试自定义智能体
  33. custom_agent = create_custom_agent()
  34. if custom_agent:
  35. # 测试技能
  36. print("测试问候技能:")
  37. result1 = custom_agent.skills["greet"]("张三")
  38. print(result1)
  39. print("\n测试计算技能:")
  40. result2 = custom_agent.skills["calculate"]("10 + 5 * 2")
  41. print(result2)