ProjectCraft / agents /plan_agent.py
yania-n's picture
fix: increase max_tokens to 8192 and request minified JSON to prevent truncation
c10ebf0
Raw History Blame Contribute Delete
3.2 kB
"""Plan Agent — generates the full structured project plan from user inputs using claude-sonnet-4-6."""
import json, os
import anthropic
from core.planner import ProjectPlan, parse_plan_json, ERROR_MESSAGES
from core.sanitizer import sanitize_objective, sanitize_tasks
# PROMPT v1.0
SYSTEM_PROMPT = """
You are a senior project planning expert.
Return ONLY minified valid JSON — no markdown, no explanation, no extra whitespace.
Schema: {"phases":[...],"raci":[...],"workload":[...],"timeline_warning":"string or null"}
Phase: {"id":"str","name":"str","start_offset_days":int,"duration_days":int,"owner_team":"str","tasks":["str"],"is_critical_path":bool,"slack_days":int}
RACI: {"task":"str","responsible":["str"],"accountable":"str","consulted":["str"],"informed":["str"]}
Workload: {"team_name":"str","weeks":[{"week_label":"str","load_score":float}]}
Rules:
- is_critical_path:true only on phases where slack_days==0
- Phases sorted by ascending start_offset_days
- Every team in at least one RACI entry
- load_score 0-10; provide weekly entries for each team covering the full project duration
- Minimum 4 phases
- timeline_warning: brief note if scope vs timeline is unrealistic, else null
"""
def _build_user_message(
objective: str,
tasks: str,
teams: list,
start_date: str,
end_date: str,
) -> str:
"""Build the user message from sanitized inputs."""
clean_objective = sanitize_objective(objective)
clean_tasks = sanitize_tasks(tasks)
team_names = ", ".join(t["name"] if isinstance(t, dict) else t for t in teams) if teams else "No teams specified"
date_range = ""
if start_date or end_date:
date_range = f"\nDate range: {start_date or 'unspecified'} to {end_date or 'unspecified'}"
return (
f"Objective: {clean_objective}\n"
f"Tasks: {clean_tasks}\n"
f"Teams: {team_names}"
f"{date_range}"
)
async def _call_sonnet(user_message: str) -> ProjectPlan:
"""Call claude-sonnet-4-6 and parse the response into a ProjectPlan."""
client = anthropic.AsyncAnthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
try:
response = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=8192,
system=SYSTEM_PROMPT,
messages=[{"role": "user", "content": user_message}],
)
raw_text = response.content[0].text
return parse_plan_json(raw_text)
except anthropic.APITimeoutError as exc:
raise RuntimeError(ERROR_MESSAGES["timeout"]) from exc
except anthropic.RateLimitError as exc:
raise RuntimeError(ERROR_MESSAGES["rate_limit"]) from exc
except Exception as exc:
raise ValueError(ERROR_MESSAGES["bad_json"]) from exc
async def run(
objective: str,
tasks: str,
teams: list,
start_date: str = "",
end_date: str = "",
) -> ProjectPlan:
"""Main entry point. Builds message and calls Sonnet. Returns ProjectPlan."""
user_message = _build_user_message(objective, tasks, teams, start_date, end_date)
plan = await _call_sonnet(user_message)
if not plan.phases:
raise ValueError(ERROR_MESSAGES["no_phases"])
return plan