ciro-backend / src /backend /agents /planning.py
HAK-16's picture
Initial deploy
1ffd0a4 verified
Raw History Blame Contribute Delete
11.7 kB
"""
Action Planning Agent β€” third reasoning stage of the CIRO pipeline.
Responsibility
--------------
Given the detection verdict, risk tier, and situation report, generate a
concrete, prioritized response plan. For flood/traffic crises, fetches real
alternate routes from Google Maps via the fetch_routes_tool before finalising
the plan.
Output contract
---------------
Returns a `ResponsePlan` Pydantic model via the SDK's structured-output path.
"""
from __future__ import annotations
import json
import logging
from typing import Literal
from agents import Agent, function_tool
from pydantic import BaseModel, ConfigDict, Field
from backend.agents.analysis import SituationReport
from backend.agents.detection import DetectionOutput
from backend.core.model import get_gemini_model
from backend.core.runner import run_agent
from backend.models.agent_result import AgentResult
from backend.models.risk import RiskTieringResult
from backend.services.maps import RouteOption
from backend.services.maps import fetch_routes as _fetch_routes_impl
logger = logging.getLogger(__name__)
# ── Output schemas ────────────────────────────────────────────────────────
class ActionItem(BaseModel):
"""A single response action in the plan."""
model_config = ConfigDict(extra="forbid")
action: str
assigned_to: str
priority: Literal["critical", "high", "medium"]
class ResponsePlan(BaseModel):
"""Full coordinated response plan produced by the planning agent."""
model_config = ConfigDict(extra="forbid")
immediate_actions: list[ActionItem] = Field(default_factory=list)
short_term_actions: list[ActionItem] = Field(default_factory=list)
route_options: list[RouteOption] = Field(default_factory=list)
recommended_route: RouteOption | None = None
resources_needed: list[str] = Field(default_factory=list)
estimated_response_time: str
plan_summary: str
confidence: float = Field(default=0.8, ge=0.0, le=1.0)
# ── Maps function tool ────────────────────────────────────────────────────
async def _fetch_routes_tool_impl(origin: str, destination: str) -> str:
"""Business logic for fetch_routes_tool β€” separated for unit testing."""
routes = await _fetch_routes_impl(origin, destination)
if not routes:
return json.dumps({
"routes": [],
"count": 0,
"status": "NO_ROUTES",
"suggestion": (
"No routes returned β€” GOOGLE_MAPS_API_KEY may be unset or the "
"address format may be invalid. Use Pakistani sector format: "
"'G-10 Markaz, Islamabad'. Proceed with plan_summary noting "
"that alternate route data is unavailable."
),
})
return json.dumps({
"routes": [r.model_dump() for r in routes],
"count": len(routes),
"status": "OK",
})
@function_tool
async def fetch_routes_tool(origin: str, destination: str) -> str:
"""Fetch real alternate route options from the Google Maps Directions API.
Use when:
- The crisis type is flood, traffic_jam, or road_blockage.
- Vehicles need to be rerouted around the affected area.
- The response plan must name specific alternate roads.
Do NOT use for:
- Fire-only or building_collapse scenarios where traffic rerouting
is not the primary response action.
- When the crisis has no road-access impact.
Args:
origin: Starting point as Pakistani address or "lat,lon" string.
Example: "G-10 Markaz, Islamabad" or "33.6844,73.0479".
destination: End point that bypasses the affected area.
Example: "F-10 Markaz, Islamabad" or "Kashmir Highway, Islamabad".
Returns:
JSON with:
routes: list of {summary, distance_km, duration_minutes, polyline, is_recommended}
count: number of routes
status: "OK" | "NO_ROUTES"
On failure includes a suggestion field to guide plan fallback.
"""
return await _fetch_routes_tool_impl(origin, destination)
# ── Agent definition ──────────────────────────────────────────────────────
_INSTRUCTIONS = """\
You are a crisis response planner for Pakistani urban areas (Islamabad, Karachi, Lahore).
You receive the full situational picture: crisis type, location, risk level, severity (1-5), a plain-language situation summary, and β€” for traffic/flood crises β€” pre-fetched alternate route data.
Your job is to produce a ResponsePlan with:
1. immediate_actions (0-5 min): critical interventions that prevent escalation right now.
2. short_term_actions (5-30 min): follow-up coordination, resource staging, public alerts.
3. resources_needed: specific units, e.g. "2 fire trucks from F-11 station", "Rescue 1122 ambulance", "traffic wardens at G-9 Markaz".
4. estimated_response_time: realistic for Pakistani emergency services (police ~8 min, fire brigade ~15 min, Rescue 1122 ~10 min in major cities).
5. route_options + recommended_route: copy the routes exactly from the "### Available Routes ###" section of the input if provided. Set recommended_route to the one with is_recommended=true. If no routes are provided, leave both as empty/null and note this in plan_summary.
6. plan_summary: one clear paragraph a non-technical coordinator can act on. No JSON, no jargon.
7. confidence: your confidence in this plan (0.0-1.0).
Be specific to the Pakistani context: name real roads (Margalla Road, Kashmir Highway, Islamabad Expressway, Khayaban-e-Iqbal), real services (Islamabad Police, CDA, Rescue 1122), and sector names.
Return the result strictly as the ResponsePlan schema.
"""
# Note: tools are NOT registered here β€” Gemini's OpenAI-compat endpoint does not
# support function calling + JSON-mode structured output simultaneously.
# Routes are pre-fetched in run_planning() and injected into the prompt.
planning_agent = Agent(
name="action_planning_agent",
instructions=_INSTRUCTIONS,
model=get_gemini_model(),
output_type=ResponsePlan,
)
# ── Input formatting ──────────────────────────────────────────────────────
# Crisis types that benefit from traffic rerouting.
_REROUTE_TYPES: frozenset[str] = frozenset({"flood", "traffic_jam", "road_blockage"})
# General Islamabad bypass destination used when fetching alternate routes.
# Routes are fetched from the crisis location β†’ this point, giving the Maps
# API enough geographic distance to return meaningful alternatives.
_ISLAMABAD_DESTINATION = "Zero Point Interchange, Islamabad"
def _format_inputs(
detection: DetectionOutput,
risk: RiskTieringResult,
analysis: SituationReport,
routes: list[RouteOption],
) -> str:
"""Render upstream pipeline context as a structured planning prompt."""
lines: list[str] = [
"### Crisis Context ###",
f"Crisis Type : {detection.crisis_type}",
f"Location : {detection.location_label} ({detection.coordinates})",
f"Detection Conf : {detection.confidence:.2f}",
"",
"### Risk Assessment ###",
f"Risk Level : {risk.risk_level}",
f"Requires Emergency Services: {risk.requires_emergency_services}",
f"Requires Crowd Verification: {risk.requires_crowd_verification}",
f"Auto Response Actions : {risk.auto_response_actions or 'none'}",
"",
"### Situation Report ###",
f"Severity : {analysis.severity}/5 ({analysis.severity_label})",
f"Affected Pop : {analysis.affected_population_estimate}",
f"Impacts : {', '.join(analysis.impacts)}",
f"Confidence : {analysis.confidence:.2f}",
f"Summary : {analysis.explanation}",
f"Missing Info : {', '.join(analysis.missing_info) if analysis.missing_info else 'none'}",
]
if routes:
lines += ["", f"### Available Routes ({len(routes)}) ###"]
for r in routes:
lines.append(
f" - summary={r.summary!r} distance_km={r.distance_km}"
f" duration_minutes={r.duration_minutes}"
f" polyline={r.polyline!r}"
f" is_recommended={r.is_recommended}"
)
lines.append(
"Copy these routes verbatim into route_options. Set recommended_route "
"to the entry where is_recommended=true."
)
else:
lines += [
"",
"### Available Routes ###",
"No route data available (Maps API key unset or unavailable).",
"Set route_options=[] and recommended_route=null. Note this in plan_summary.",
]
lines.append("")
lines.append("Generate a complete ResponsePlan based on the above.")
return "\n".join(lines)
# ── Synthetic shortcut ────────────────────────────────────────────────────
def _synthetic_no_crisis_plan(reason: str) -> AgentResult:
"""Return a trivial no-action plan without consuming a Gemini call."""
plan = ResponsePlan(
immediate_actions=[],
short_term_actions=[],
route_options=[],
recommended_route=None,
resources_needed=[],
estimated_response_time="N/A",
plan_summary=reason,
confidence=1.0,
)
return AgentResult(
agent_name=planning_agent.name,
success=True,
output=plan.model_dump(),
reasoning=reason,
confidence=1.0,
)
# ── Pipeline entry point ──────────────────────────────────────────────────
async def run_planning(
detection: DetectionOutput,
risk: RiskTieringResult,
analysis: SituationReport,
) -> AgentResult:
"""Run the action planning agent.
Pre-fetches alternate routes from Google Maps for traffic-impacted crisis
types and injects them into the prompt before calling Gemini. This avoids
the Gemini compatibility limitation where function calling and JSON-mode
structured output cannot be used together.
Args:
detection: Phase 5 detection verdict.
risk: Phase 6 risk tier result.
analysis: Phase 7 situation report.
Returns:
An `AgentResult` whose `output` is a `ResponsePlan` dict.
"""
if not detection.crisis_detected:
return _synthetic_no_crisis_plan(
"No crisis detected in the previous stage; planning skipped."
)
# Pre-fetch routes for crisis types that involve traffic rerouting.
routes: list[RouteOption] = []
if detection.crisis_type in _REROUTE_TYPES and detection.coordinates:
lat, lon = detection.coordinates
origin = f"{lat},{lon}"
routes = await _fetch_routes_impl(origin, _ISLAMABAD_DESTINATION)
logger.info(
"Pre-fetched %d route(s) for %s crisis at %s",
len(routes),
detection.crisis_type,
detection.location_label,
)
prompt = _format_inputs(detection, risk, analysis, routes)
return await run_agent(planning_agent, prompt)