Spaces:
Runtime error
Runtime error
File size: 11,671 Bytes
1ffd0a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | """
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)
|