orchestrator.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """总控Agent - 负责路由和状态管理"""
  2. from typing import Dict, Any, Optional
  3. from hello_agents import SimpleAgent
  4. from ..services.llm_service import get_llm
  5. from .tutor_agent import TutorAgent
  6. from .debug_agent import DebugAgent
  7. from .review_agent import ReviewAgent
  8. from .arch_agent import ArchAgent
  9. from .coach_agent import CoachAgent
  10. ORCHESTRATOR_PROMPT = """你是一个智能路由系统。你的任务是分析用户输入,决定应该交给哪个Agent处理。
  11. **可用的Agent:**
  12. 1. tutor - 编程导师:回答编程概念、解释代码、提供学习建议
  13. 2. debug - 调试助手:分析错误信息、帮助修复代码bug
  14. 3. review - 代码审查员:审查代码质量、发现潜在问题、提供优化建议
  15. 4. arch - 架构师:设计系统架构、技术选型、解决架构问题
  16. 5. coach - 学习教练:规划学习路径、跟踪进度、提供学习建议
  17. **判断规则:**
  18. - 如果用户在问学习路径、课程推荐、学习计划、进度相关 → 选择 coach
  19. - 如果用户在问编程概念、原理、怎么用 → 选择 tutor
  20. - 如果用户在报告错误、贴了报错信息、代码不工作 → 选择 debug
  21. - 如果用户贴了代码想让帮忙看看、想优化代码 → 选择 review
  22. - 如果用户在问系统设计、架构、技术选型 → 选择 arch
  23. - 如果用户输入模棱两可,同时涉及多个领域 → 选择最匹配核心意图的那个,不要选 tutor 作为默认兜底
  24. **关键规则:**
  25. - 用户问"这段代码有什么问题"→ 优先 debug(检查是否报错),不是 review
  26. - 用户问"帮我写个XX功能"→ 优先 tutor(指导怎么写),不是 review
  27. - 用户问"设计一个XX系统"→ 优先 arch,不是 tutor
  28. - 只有完全无法判断时才用 tutor 兜底
  29. **输出格式(只输出一个词):**
  30. tutor 或 debug 或 review 或 arch 或 coach
  31. """
  32. class Orchestrator:
  33. """总控Agent"""
  34. def __init__(self):
  35. self.llm = get_llm()
  36. # 创建路由Agent
  37. self.router = SimpleAgent(
  38. name="路由器",
  39. llm=self.llm,
  40. system_prompt=ORCHESTRATOR_PROMPT,
  41. )
  42. # 创建子Agent
  43. self.agents = {
  44. "tutor": TutorAgent(),
  45. "debug": DebugAgent(),
  46. "review": ReviewAgent(),
  47. "arch": ArchAgent(),
  48. "coach": CoachAgent(),
  49. }
  50. print("Orchestrator初始化完成,已加载Agent:", list(self.agents.keys()))
  51. def route(self, user_input: str, context: Optional[Dict[str, Any]] = None) -> str:
  52. """路由用户输入到合适的Agent"""
  53. # 让LLM判断应该路由到哪个Agent
  54. router_response = self.router.run(
  55. f"用户输入:{user_input}\n\n请判断应该交给哪个Agent处理。"
  56. )
  57. # 解析路由结果
  58. agent_name = router_response.strip().lower()
  59. if agent_name not in self.agents:
  60. agent_name = "tutor" # 默认使用tutor
  61. print(f"路由结果: {agent_name}")
  62. # 调用对应的Agent(传递上下文)
  63. agent = self.agents[agent_name]
  64. return agent.chat(user_input, context=context), agent_name
  65. # 全局实例
  66. _orchestrator = None
  67. def get_orchestrator() -> Orchestrator:
  68. """获取Orchestrator实例(单例)"""
  69. global _orchestrator
  70. if _orchestrator is None:
  71. _orchestrator = Orchestrator()
  72. return _orchestrator