Files
Agentswarm/orchestrator/planner.py
T
2026-06-08 17:32:34 +08:00

262 lines
11 KiB
Python

"""LLM task planner (Manager-first fallback).
Ported from agent_swarm_v4. This planner is used ONLY as a fallback to decompose a
swarm objective into specialist subtasks when the Manager's orchestration_plan does
not provide an explicit agent breakdown AND the operator opts in via
``ENABLE_PLANNER_FALLBACK``. It never overrides a Manager-supplied plan.
It degrades gracefully: with no API key or on any error it returns a static
implementation -> testing -> documentation plan, so the runtime never hard-depends on
the model being reachable.
"""
import json
import logging
import os
from typing import List, Dict
logger = logging.getLogger(__name__)
try:
from openai import AsyncOpenAI
except Exception: # pragma: no cover - only when openai is absent
AsyncOpenAI = None
def _planner_timeout() -> float:
try:
return float(os.getenv("PLANNER_TIMEOUT_SECONDS", "45") or 45)
except ValueError:
return 45.0
def _max_subtasks() -> int:
try:
return int(os.getenv("MAX_SUBTASKS", "6") or 6)
except ValueError:
return 6
class Planner:
"""Decomposes an objective into specialist subtask specs."""
def __init__(self):
api_key = os.getenv("OPENAI_API_KEY") or os.getenv("MODEL_API_KEY")
api_base = (
os.getenv("OPENAI_API_BASE")
or os.getenv("MODEL_API_BASE")
or "https://api.openai.com/v1"
)
model = (
os.getenv("OPENAI_MODEL")
or os.getenv("MODEL_NAME")
or os.getenv("MODEL_ID")
or "gpt-4o-mini"
)
self.model = os.getenv("MASTER_REVIEW_MODEL", model)
self.client = (
AsyncOpenAI(api_key=api_key, base_url=api_base)
if (api_key and AsyncOpenAI is not None)
else None
)
def _static_plan(self, run_id: str) -> List[Dict]:
return [
{
"subtask_id": f"{run_id}-implementation",
"description": "Implement the core code required by the user request.",
"required_capabilities": ["python", "code_generation"],
"role": "implementation",
"depends_on": [],
},
{
"subtask_id": f"{run_id}-testing",
"description": "Write tests for the implemented functionality.",
"required_capabilities": ["testing", "pytest"],
"role": "testing",
"depends_on": [f"{run_id}-implementation"],
},
{
"subtask_id": f"{run_id}-documentation",
"description": "Write concise documentation based on the implementation and tests.",
"required_capabilities": ["technical-writing", "general"],
"role": "documentation",
"depends_on": [f"{run_id}-implementation", f"{run_id}-testing"],
},
]
async def build_plan(self, run_id: str, objective: str) -> List[Dict]:
"""Return specialist subtask specs for an objective, or a static fallback."""
fallback = self._static_plan(run_id)
if not self.client:
return fallback
try:
response = await self.client.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": (
"Break the request into at most 6 specialist subtasks. "
"Return JSON with key 'subtasks'; each subtask has subtask_id, "
"description, role, required_capabilities (list), depends_on (list of subtask_ids)."
),
},
{"role": "user", "content": f"Run id: {run_id}\nObjective: {objective}"},
],
response_format={"type": "json_object"},
timeout=_planner_timeout(),
)
content = response.choices[0].message.content or "{}"
subtasks = (json.loads(content) or {}).get("subtasks")
if not subtasks:
return fallback
return subtasks[: _max_subtasks()]
except Exception as e:
logger.warning(f"Planner LLM call failed ({e}); using static fallback plan")
return fallback
async def review(self, objective: str, tasks: List[Dict], results: Dict) -> Dict:
"""Judge whether the combined specialist results are good enough.
Returns {accepted: bool, summary: str, retry_tasks: [task_id, ...]}. Falls back to a
deterministic consistency heuristic when no model is available or the call fails, so the
review gate degrades safely instead of blocking the run.
"""
artifact_summary = self._summarize_results(results)
if self.client:
try:
response = await self.client.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": (
"Evaluate whether the specialist results jointly satisfy the objective and are "
"semantically aligned. Compare claimed error behavior, function/API names, and usage "
"examples across specialists. Reject when behavior claims conflict or the objective is "
"unmet. Return JSON with keys: accepted (bool), summary (str), retry_tasks (list of the "
"result keys that must be redone)."
),
},
{
"role": "user",
"content": json.dumps(
{
"objective": objective,
"tasks": tasks,
"results": artifact_summary,
"result_keys": list(results.keys()),
},
ensure_ascii=False,
),
},
],
response_format={"type": "json_object"},
timeout=_planner_timeout(),
)
result = json.loads(response.choices[0].message.content or "{}")
if result:
result.setdefault("accepted", True)
result.setdefault("summary", "accepted")
result.setdefault("retry_tasks", [])
# Only keep retry targets that are real result keys.
result["retry_tasks"] = [t for t in result["retry_tasks"] if t in results]
return result
except Exception as e:
logger.warning(f"Review LLM call failed ({e}); using heuristic consistency check")
consistency = self._heuristic_consistency_check(results)
if not consistency["accepted"]:
return consistency
return {"accepted": True, "summary": "fallback acceptance", "retry_tasks": []}
async def synthesize(self, objective: str, results: Dict) -> str:
"""Compose one coherent answer from the specialist results.
Uses the model when available; otherwise concatenates specialist summaries so a
unified response always exists.
"""
summary = self._summarize_results(results)
deterministic = " | ".join(
f"{key}: {value.get('summary') or value.get('changes') or 'no summary'}"
for key, value in summary.items()
) or objective
if not self.client:
return deterministic
try:
response = await self.client.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": (
"Synthesize the specialist results into one concise, user-facing answer to the "
"objective. Resolve overlaps in favor of implementation semantics."
),
},
{
"role": "user",
"content": json.dumps(
{"objective": objective, "results": summary}, ensure_ascii=False
),
},
],
timeout=_planner_timeout(),
)
return (response.choices[0].message.content or "").strip() or deterministic
except Exception as e:
logger.warning(f"Synthesis LLM call failed ({e}); using concatenated summary")
return deterministic
def _summarize_results(self, results: Dict) -> Dict:
summary = {}
for task_id, payload in results.items():
result = (payload or {}).get("result", {}) or {}
subtasks = result.get("subtasks", []) or []
files, combined_changes, combined_summary = [], [], []
for item in subtasks:
files.extend(item.get("files_modified", []) or [])
if item.get("changes"):
combined_changes.append(item.get("changes"))
if item.get("summary"):
combined_summary.append(item.get("summary"))
if not combined_summary and result.get("summary"):
combined_summary.append(result.get("summary"))
summary[task_id] = {
"files_modified": files,
"summary": " ".join(combined_summary),
"changes": " ".join(combined_changes),
}
return summary
def _heuristic_consistency_check(self, results: Dict) -> Dict:
combined_text, task_ids = [], []
for task_id, payload in results.items():
task_ids.append(task_id)
result = (payload or {}).get("result", {}) or {}
for item in result.get("subtasks", []) or []:
combined_text.append(item.get("summary", "") or "")
combined_text.append(item.get("changes", "") or "")
for file_item in item.get("files", []) or []:
combined_text.append(file_item.get("content", "") or "")
joined = "\n".join(combined_text).lower()
if ("valueerror" in joined) and ("zerodivisionerror" in joined or "zero division" in joined):
retry = [t for t in task_ids if "documentation" in t or "testing" in t] or task_ids
return {
"accepted": False,
"summary": "conflicting error semantics detected between specialists",
"retry_tasks": retry,
}
if ("pytest" in joined) and ("unittest" in joined):
retry = [t for t in task_ids if "testing" in t or "documentation" in t] or task_ids
return {
"accepted": False,
"summary": "conflicting test framework expectations detected between specialists",
"retry_tasks": retry,
}
return {"accepted": True, "summary": "heuristic consistency acceptance", "retry_tasks": []}
planner = Planner()