| 1 | from graphrag_sdk.models import GenerativeModel |
| 2 | from graphrag_sdk.agents import Agent |
| 3 | from .orchestrator_runner import OrchestratorRunner |
| 4 | from graphrag_sdk.fixtures.prompts import ( |
| 5 | ORCHESTRATOR_SYSTEM, |
| 6 | ORCHESTRATOR_EXECUTION_PLAN_PROMPT, |
| 7 | ) |
| 8 | from graphrag_sdk.helpers import extract_json |
| 9 | from .execution_plan import ( |
| 10 | ExecutionPlan, |
| 11 | ) |
| 12 | import logging |
| 13 | |
| 14 | logger = logging.getLogger(__name__) |
| 15 | |
| 16 | |
| 17 | class Orchestrator: |
| 18 | |
| 19 | _agents = [] |
| 20 | _chat = None |
| 21 | |
| 22 | def __init__(self, model: GenerativeModel, backstory: str = ""): |
| 23 | self._model = model |
| 24 | self._backstory = backstory |
| 25 | |
| 26 | def _get_chat(self): |
| 27 | if self._chat is None: |
| 28 | self._chat = self._model.with_system_instruction( |
| 29 | ORCHESTRATOR_SYSTEM.replace("#BACKSTORY", self._backstory).replace( |
| 30 | "#AGENTS", |
| 31 | ",".join([str(agent) for agent in self._agents]), |
| 32 | ) |
| 33 | ).start_chat({"response_validation": False}) |
| 34 | |
| 35 | return self._chat |
| 36 | |
| 37 | def register_agent(self, agent: Agent): |
| 38 | self._agents.append(agent) |
| 39 | |
| 40 | def ask(self, question: str): |
| 41 | return self.runner(question).run() |
| 42 | |
| 43 | def runner(self, question: str) -> OrchestratorRunner: |
| 44 | plan = self._create_execution_plan(question) |
| 45 | |
| 46 | return OrchestratorRunner( |
| 47 | self._get_chat(), self._agents, plan, user_question=question |
| 48 | ) |
| 49 | |
| 50 | def _create_execution_plan(self, question: str): |
| 51 | try: |
| 52 | response = self._get_chat().send_message( |
| 53 | ORCHESTRATOR_EXECUTION_PLAN_PROMPT.replace("#QUESTION", question) |
| 54 | ) |
| 55 | |
| 56 | logger.debug(f"Execution plan response: {response.text}") |
| 57 | |
| 58 | plan = ExecutionPlan.from_json( |
| 59 | extract_json(response.text, skip_repair=True) |
| 60 | ) |
| 61 | |
| 62 | logger.debug(f"Execution plan: {plan}") |
| 63 | |
| 64 | return plan |
| 65 | except Exception as e: |
| 66 | logger.error(f"Failed to create plan: {e}") |
| 67 | raise e |