subagent_example.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. Sub-Agent 使用示例
  3. 演示如何使用 Sub-Agent 机制处理复杂任务。
  4. 注意:本示例中的 AgentDefinition 和 get_agent_registry 尚未实现,
  5. 此处仅用于演示未来的设计方向。当前可用的 subagent 功能通过
  6. runner.run(messages, config=RunConfig(...)) 和工具层的 subagent 工具实现。
  7. """
  8. import asyncio
  9. import os
  10. from agent import AgentRunner
  11. from agent.core.runner import RunConfig
  12. from agent.trace import Trace, Message
  13. from agent.llm import create_gemini_llm_call
  14. async def example_basic_subagent():
  15. """示例 1: 使用 Agent 执行任务(通过 subagent 工具自动委托子任务)"""
  16. print("=== 示例 1: 基本 Agent 执行 ===\n")
  17. runner = AgentRunner(
  18. llm_call=create_gemini_llm_call(os.getenv("GEMINI_API_KEY")),
  19. )
  20. task = """
  21. 分析这个 Python 项目的架构:
  22. 1. 找出所有主要的模块和它们的职责
  23. 2. 识别核心的数据流
  24. 3. 列出使用的外部依赖
  25. 请使用 subagent explore 模式来探索代码库。
  26. """
  27. async for item in runner.run(
  28. messages=[{"role": "user", "content": task}],
  29. config=RunConfig(
  30. model="gemini-2.0-flash-exp",
  31. max_iterations=20,
  32. name="项目架构分析",
  33. ),
  34. ):
  35. if isinstance(item, Trace):
  36. if item.status == "running":
  37. print(f"[Trace] 开始: {item.trace_id[:8]}")
  38. elif item.status == "completed":
  39. print(f"[Trace] 完成 (tokens: {item.total_tokens})")
  40. elif isinstance(item, Message):
  41. if item.role == "assistant":
  42. content = item.content
  43. if isinstance(content, dict):
  44. text = content.get("text", "")
  45. tool_calls = content.get("tool_calls")
  46. if tool_calls:
  47. for tc in tool_calls:
  48. tool_name = tc.get("function", {}).get("name", "")
  49. if tool_name == "subagent":
  50. print(f" 启动 Sub-Agent...")
  51. elif text:
  52. print(f"\n最终结果:\n{text[:500]}")
  53. async def main():
  54. """运行示例"""
  55. await example_basic_subagent()
  56. if __name__ == "__main__":
  57. asyncio.run(main())