subagent_example.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. """
  2. Sub-Agent 使用示例
  3. 演示如何使用 Sub-Agent 机制处理复杂任务。
  4. """
  5. import asyncio
  6. import os
  7. from agent import AgentRunner, AgentConfig
  8. from agent.llm.providers.gemini import create_gemini_llm_call
  9. from agent.agent_registry import get_agent_registry
  10. from agent.models.agent import AgentDefinition
  11. async def example_basic_subagent():
  12. """示例 1: 使用内置 Sub-Agent"""
  13. print("=== 示例 1: 使用内置 Sub-Agent ===\n")
  14. # 配置主 Agent
  15. config = AgentConfig(
  16. agent_type="primary",
  17. max_iterations=20,
  18. skills_dir="./skills",
  19. )
  20. runner = AgentRunner(
  21. llm_call=create_gemini_llm_call(os.getenv("GEMINI_API_KEY")),
  22. config=config,
  23. )
  24. # 主 Agent 会自动知道如何使用 Task 工具启动 Sub-Agent
  25. task = """
  26. 分析这个 Python 项目的架构:
  27. 1. 找出所有主要的模块和它们的职责
  28. 2. 识别核心的数据流
  29. 3. 列出使用的外部依赖
  30. 请使用 explore sub-agent 来探索代码库。
  31. """
  32. async for event in runner.run(task=task, model="gemini-2.0-flash-exp"):
  33. if event.type == "tool_call" and event.data.get("tool") == "task":
  34. print(f"🚀 启动 Sub-Agent: {event.data['args']['subagent_type']}")
  35. print(f" 任务: {event.data['args']['description']}")
  36. elif event.type == "tool_result" and event.data.get("tool") == "task":
  37. metadata = event.data.get("metadata", {})
  38. print(f"✅ Sub-Agent 完成")
  39. print(f" Sub-Trace ID: {metadata.get('sub_trace_id')}")
  40. print(f" 工具调用: {metadata.get('tool_summary')}")
  41. elif event.type == "conclusion":
  42. print(f"\n📋 最终结果:\n{event.data['content']}")
  43. async def example_custom_subagent():
  44. """示例 2: 定义和使用自定义 Sub-Agent"""
  45. print("\n=== 示例 2: 自定义 Sub-Agent ===\n")
  46. # 1. 定义自定义 Sub-Agent
  47. security_scanner = AgentDefinition(
  48. name="security-scanner",
  49. description="安全扫描专家,查找常见漏洞和安全问题",
  50. mode="subagent",
  51. allowed_tools=[
  52. "read_file",
  53. "search_code",
  54. "list_files",
  55. ],
  56. denied_tools=[
  57. "write_file",
  58. "edit_file",
  59. "execute_bash",
  60. ],
  61. system_prompt="""你是一个安全扫描专家。专注于:
  62. 1. 查找常见安全漏洞:
  63. - SQL 注入
  64. - XSS 攻击
  65. - CSRF 漏洞
  66. - 不安全的序列化
  67. - 路径遍历
  68. 2. 检查敏感信息泄露:
  69. - 硬编码的密钥和密码
  70. - API token
  71. - 数据库凭据
  72. 3. 依赖项安全:
  73. - 过时的依赖
  74. - 已知漏洞的包
  75. 输出格式:
  76. - **漏洞类型**: [类型名称]
  77. - **严重程度**: [高/中/低]
  78. - **位置**: [文件路径:行号]
  79. - **描述**: [详细说明]
  80. - **修复建议**: [如何修复]
  81. """,
  82. max_iterations=25,
  83. temperature=0.2, # 更精确的分析
  84. )
  85. # 2. 注册到全局注册表
  86. get_agent_registry().register(security_scanner)
  87. print(f"✓ 注册自定义 Sub-Agent: {security_scanner.name}")
  88. # 3. 使用自定义 Sub-Agent
  89. config = AgentConfig(
  90. agent_type="primary",
  91. max_iterations=20,
  92. )
  93. runner = AgentRunner(
  94. llm_call=create_gemini_llm_call(os.getenv("GEMINI_API_KEY")),
  95. config=config,
  96. )
  97. task = """
  98. 对这个项目进行安全审计,使用 security-scanner sub-agent。
  99. 重点关注:
  100. 1. 认证和授权相关代码
  101. 2. 数据库交互代码
  102. 3. 用户输入处理
  103. """
  104. async for event in runner.run(task=task, model="gemini-2.0-flash-exp"):
  105. if event.type == "tool_call" and event.data.get("tool") == "task":
  106. print(f"🔍 启动安全扫描...")
  107. elif event.type == "conclusion":
  108. print(f"\n🔒 安全审计报告:\n{event.data['content']}")
  109. async def example_multiple_subagents():
  110. """示例 3: 并行使用多个 Sub-Agent"""
  111. print("\n=== 示例 3: 并行使用多个 Sub-Agent ===\n")
  112. config = AgentConfig(
  113. agent_type="primary",
  114. max_iterations=30,
  115. )
  116. runner = AgentRunner(
  117. llm_call=create_gemini_llm_call(os.getenv("GEMINI_API_KEY")),
  118. config=config,
  119. )
  120. task = """
  121. 完整分析这个项目:
  122. 1. 使用 explore sub-agent 探索代码结构
  123. 2. 使用 analyst sub-agent 分析技术栈和依赖
  124. 3. 综合两个分析结果,给出项目概览
  125. 可以并行启动多个 sub-agent 来加快速度。
  126. """
  127. subagent_results = {}
  128. async for event in runner.run(task=task, model="gemini-2.0-flash-exp"):
  129. if event.type == "tool_call" and event.data.get("tool") == "task":
  130. agent_type = event.data['args']['subagent_type']
  131. print(f"🔄 启动 Sub-Agent: {agent_type}")
  132. elif event.type == "tool_result" and event.data.get("tool") == "task":
  133. metadata = event.data.get("metadata", {})
  134. agent_type = metadata.get("subagent_type")
  135. subagent_results[agent_type] = {
  136. "sub_trace_id": metadata.get("sub_trace_id"),
  137. "summary": metadata.get("tool_summary"),
  138. }
  139. print(f"✅ {agent_type} 完成: {metadata.get('tool_summary')}")
  140. elif event.type == "conclusion":
  141. print(f"\n📊 综合分析报告:\n{event.data['content']}")
  142. print(f"\n📈 Sub-Agent 使用统计:")
  143. for agent_type, result in subagent_results.items():
  144. print(f" - {agent_type}: {result['summary']}")
  145. async def example_subagent_config_file():
  146. """示例 4: 从配置文件加载 Sub-Agent"""
  147. print("\n=== 示例 4: 配置文件方式 ===\n")
  148. # 1. 从配置文件加载
  149. # 假设有 sub_agents.json:
  150. # {
  151. # "agents": {
  152. # "code-reviewer": {
  153. # "description": "代码审查专家",
  154. # "mode": "subagent",
  155. # "allowed_tools": ["read_file", "search_code"],
  156. # "system_prompt": "你是代码审查专家..."
  157. # }
  158. # }
  159. # }
  160. registry = get_agent_registry()
  161. # 如果配置文件存在
  162. config_path = "sub_agents.json"
  163. if os.path.exists(config_path):
  164. registry.load_from_config(config_path)
  165. print(f"✓ 从 {config_path} 加载 Agent 配置")
  166. # 2. 列出所有可用的 Sub-Agent
  167. print("\n可用的 Sub-Agent:")
  168. for agent in registry.list_subagents():
  169. print(f" - {agent.name}: {agent.description}")
  170. async def main():
  171. """运行所有示例"""
  172. # 示例 1: 基本使用
  173. await example_basic_subagent()
  174. # 示例 2: 自定义 Sub-Agent
  175. await example_custom_subagent()
  176. # 示例 3: 并行使用多个 Sub-Agent
  177. await example_multiple_subagents()
  178. # 示例 4: 配置文件方式
  179. await example_subagent_config_file()
  180. if __name__ == "__main__":
  181. asyncio.run(main())