Weather disaster management — before / after / after-disrupted#

Notebook version of the three-script screencast in examples/screencast/weather_alert/.

The task. Grade a forecast, brief the right department, get a human to sign off on mild alerts, send the alert. Survive the relay and the operator saying no.

The original. NirDiamant/GenAI_Agents → Weather_Disaster_Management_AI_AGENT.ipynb, Part 1. It fetches OpenWeatherMap data, asks a local LLM to name a disaster type and grade its severity, routes to one department with route_response, asks a human (blocking input()) for low/medium alerts and auto-approves the rest, then sends an e-mail or runs handle_no_approval.

Three things the routing hides, all reproduced below:

  • route_response’s first branch is return "emergency_response" followed by a bare "send_email_alert" string. A second target was evidently intended; it is unreachable.

  • get_human_verification auto-approves anything that is not "low" or "medium", so a hurricane whose severity call failed is routed to civil defense and e-mailed with no human in the loop.

  • send_email_alert wraps smtplib in try/except and the graph ends as if the alert had gone out.

Hand-wired (before.py)

GOAP (after.py)

Which department

route_response string matching, one dead branch

preconditions on severe / flood_or_storm

Who needs a human

if severity in ["low", "medium"] inside a node

approve_alert with precondition severe: False

Human says no

verify_approval_router → handle_no_approval

action failure → stuck handler relaxes the goal → withhold_alert

Relay down

try/except, message appended, graph ends

ActionQos retry, then blacklist and SMS fallback

No threat

routed to civil defense and e-mailed

log_all_clear

1. The hand-wired version#

before.py keeps the nodes, the edges and both routers verbatim. The weather API, the LLM, input() and SMTP are fixtures and flags. Read route_response first.

import inspect

from examples.screencast.weather_alert import before

print(inspect.getsource(before.route_response))
print(inspect.getsource(before.verify_approval_router))
def route_response(
    state: WeatherState,
) -> Literal[
    "emergency_response",
    "send_email_alert",
    "civil_defense_response",
    "public_works_response",
]:
    """Route to appropriate department based on disaster type and severity"""
    disaster = state["disaster_type"].strip().lower()
    severity = state["severity"].strip().lower()

    if severity in ["critical", "high"]:
        return "emergency_response"
        "send_email_alert"
    elif "flood" in disaster or "storm" in disaster:
        return "public_works_response"
    else:
        return "civil_defense_response"

def verify_approval_router(
    state: WeatherState,
) -> Literal["send_email_alert", "handle_no_approval"]:
    """Route based on human approval decision"""
    return "send_email_alert" if state["human_approved"] else "handle_no_approval"
print(before.build_graph().compile().get_graph().draw_mermaid())
---
config:
  flowchart:
    curve: linear
---
graph TD;
	__start__([<p>__start__</p>]):::first
	get_weather(get_weather)
	analyze_disaster(analyze_disaster)
	assess_severity(assess_severity)
	data_logging(data_logging)
	emergency_response(emergency_response)
	civil_defense_response(civil_defense_response)
	public_works_response(public_works_response)
	get_human_verification(get_human_verification)
	send_email_alert(send_email_alert)
	handle_no_approval(handle_no_approval)
	__end__([<p>__end__</p>]):::last
	__start__ --> get_weather;
	analyze_disaster --> assess_severity;
	assess_severity --> data_logging;
	civil_defense_response --> get_human_verification;
	data_logging -.-> civil_defense_response;
	data_logging -.-> emergency_response;
	data_logging -.-> public_works_response;
	data_logging -.-> send_email_alert;
	emergency_response --> send_email_alert;
	get_human_verification -.-> handle_no_approval;
	get_human_verification -.-> send_email_alert;
	get_weather --> analyze_disaster;
	public_works_response --> get_human_verification;
	handle_no_approval --> __end__;
	send_email_alert --> __end__;
	classDef default fill:#f2f0ff,line-height:1.2
	classDef first fill-opacity:0
	classDef last fill:#bfb6fc
for label in ("hurricane", "flood", "heatwave", "calm"):
    print(f"--- {label} ---")
    final = before.run(label)
    print(f"  alerts={final['alerts']} human_asked={final['human_asked']}\n")
--- hurricane ---
  [data_logging] Port Mayfield: Hurricane / Critical
  [emergency_response] Emergency plan for a Hurricane (Critical) in Port Mayfield: immediate actions, shelters, evacuation routes.
  [send_email_alert] e-mail sent for Port Mayfield
  alerts=['Email alert sent'] human_asked=False

--- flood ---
  [data_logging] Riverton: Flood / Medium
  [public_works_response] Public works plan for a Flood (Medium) in Riverton: drainage, road closures, sandbags.
  [get_human_verification] operator says y
  [send_email_alert] e-mail sent for Riverton
  alerts=['Email alert sent'] human_asked=True

--- heatwave ---
  [data_logging] Dry Gulch: Heatwave / Medium
  [civil_defense_response] Civil defense plan for a Heatwave (Medium) in Dry Gulch: public safety advisories, cooling centres.
  [get_human_verification] operator says y
  [send_email_alert] e-mail sent for Dry Gulch
  alerts=['Email alert sent'] human_asked=True

--- calm ---
  [data_logging] Fairweather: No Immediate Threat / Low
  [civil_defense_response] Civil defense plan for a No Immediate Threat (Low) in Fairweather: public safety advisories, cooling centres.
  [get_human_verification] operator says y
  [send_email_alert] e-mail sent for Fairweather
  alerts=['Email alert sent'] human_asked=True

The calm forecast was routed to civil defense and e-mailed: route_response has no branch for “no immediate threat”. Now the three failure modes.

print("--- operator rejects the flood alert ---")
final = before.run("flood", approve=False)
print(f"  alerts={final['alerts']}\n  {final['messages'][-1].content}\n")

print("--- the severity LLM call fails during a hurricane ---")
final = before.run("hurricane", severity="Assessment Failed")
print(f"  routed to {final['department']}; human_asked={final['human_asked']}; alerts={final['alerts']}\n")

print("--- SMTP is down during a hurricane ---")
final = before.run("hurricane", smtp_down=True)
print(f"  alerts={final['alerts']}\n  {final['messages'][-1].content}")
--- operator rejects the flood alert ---
  [data_logging] Riverton: Flood / Medium
  [public_works_response] Public works plan for a Flood (Medium) in Riverton: drainage, road closures, sandbags.
  [get_human_verification] operator says n
  [handle_no_approval] Verification was not approved by human, Email not sent
  alerts=[]
  Alert not sent for Riverton - Weather severity level 'Medium' was deemed non-critical by human operator and verification was not approved.

--- the severity LLM call fails during a hurricane ---
  [data_logging] Port Mayfield: Hurricane / Assessment Failed
  [civil_defense_response] Civil defense plan for a Hurricane (Assessment Failed) in Port Mayfield: public safety advisories, cooling centres.
  [get_human_verification] auto-approved assessment failed severity alert
  [send_email_alert] e-mail sent for Port Mayfield
  routed to civil_defense_response; human_asked=False; alerts=['Email alert sent']

--- SMTP is down during a hurricane ---
  [data_logging] Port Mayfield: Hurricane / Critical
  [emergency_response] Emergency plan for a Hurricane (Critical) in Port Mayfield: immediate actions, shelters, evacuation routes.
  [send_email_alert] failed: [Errno 61] Connection refused (graph continues)
  alerts=[]
  Failed to send email alert: [Errno 61] Connection refused

2. The GOAP version: the forecast is a set of facts#

A FunctionalSensor grades the forecast once and writes threat, severe, flood_or_storm, and approved when the event is severe. That last line is the auto-approval policy. Eight actions carry the rest as preconditions; the goal is forecast_handled.

from examples.screencast.weather_alert.after import (
    SCENARIOS, FakeSmtp, assess, build_actions, build_goal, build_graph, initial_world_state,
)

for label, weather in SCENARIOS.items():
    print(f"{label:10s} ->", assess({"weather": weather}))
print()
for a in build_actions():
    extras = ("  [approve/deny]" if a.require_human_approval else "") + (f"  qos={a.qos.max_attempts} attempts" if a.qos else "")
    print(f"{a.name:22s} cost={a.cost:<4} pre={dict(a.preconditions)}  eff={dict(a.effects)}{extras}")
  [assess] Port Mayfield: Hurricane / Critical
hurricane  -> {'disaster_type': 'Hurricane', 'severity': 'Critical', 'threat': True, 'severe': True, 'flood_or_storm': False, 'approved': True}
  [assess] Riverton: Flood / Medium
flood      -> {'disaster_type': 'Flood', 'severity': 'Medium', 'threat': True, 'severe': False, 'flood_or_storm': True}
  [assess] Dry Gulch: Heatwave / Medium
heatwave   -> {'disaster_type': 'Heatwave', 'severity': 'Medium', 'threat': True, 'severe': False, 'flood_or_storm': False}
  [assess] Fairweather: No Immediate Threat / Low
calm       -> {'disaster_type': 'No Immediate Threat', 'severity': 'Low', 'threat': False, 'severe': False, 'flood_or_storm': False}

emergency_response     cost=1.0  pre={'threat': True, 'severe': True}  eff={'plan_ready': True, 'department_notified': True}
public_works_response  cost=1.0  pre={'threat': True, 'severe': False, 'flood_or_storm': True}  eff={'plan_ready': True, 'department_notified': True}
civil_defense_response cost=1.0  pre={'threat': True, 'severe': False, 'flood_or_storm': False}  eff={'plan_ready': True, 'department_notified': True}
approve_alert          cost=1.0  pre={'plan_ready': True, 'severe': False}  eff={'approved': True}  [approve/deny]
send_email_alert       cost=1.0  pre={'plan_ready': True, 'approved': True}  eff={'alert_sent': True, 'forecast_handled': True}  qos=3 attempts
send_sms_alert         cost=3.0  pre={'plan_ready': True, 'approved': True}  eff={'alert_sent': True, 'forecast_handled': True}
withhold_alert         cost=1.0  pre={'plan_ready': True}  eff={'decision_logged': True}
log_all_clear          cost=1.0  pre={'threat': False}  eff={'forecast_handled': True}

The same four forecasts. The hurricane is severe, so no human is asked. The flood and the heatwave pause at approve_alert. The calm forecast runs log_all_clear and sends nothing.

from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command


def handle(label: str, resume=True) -> dict:
    graph = build_graph()
    compiled = graph.compile(checkpointer=MemorySaver())
    config = {"configurable": {"thread_id": label}}
    print(f"--- {label}: {SCENARIOS[label]['city']} ---")
    result = compiled.invoke(
        graph.initial_state(build_goal(), initial_world_state(SCENARIOS[label])), config=config
    )
    if "__interrupt__" in result:
        ask = result["__interrupt__"][0].value
        print(f"  [human] {ask['type']} for {ask['action']} -> {resume}")
        result = compiled.invoke(Command(resume=resume), config=config)
    print(f"  status: {result['status']}  steps: {[h['action_name'] for h in result['execution_history']]}\n")
    return result


for label in SCENARIOS:
    handle(label)
--- hurricane: Port Mayfield ---
  [assess] Port Mayfield: Hurricane / Critical
  [emergency_response] Emergency plan for a Hurricane (Critical) in Port Mayfield: immediate actions, shelters, evacuation routes.
  [smtp] sent 'Weather Alert: Critical Hurricane in Port Mayfield' on attempt 1
  status: goal_achieved  steps: ['emergency_response', 'send_email_alert']

--- flood: Riverton ---
  [assess] Riverton: Flood / Medium
  [public_works_response] Public works plan for a Flood (Medium) in Riverton: drainage, road closures, sandbags.
  [human] goap_action_approval for approve_alert -> True
  [approve_alert] operator approved
  [smtp] sent 'Weather Alert: Medium Flood in Riverton' on attempt 1
  status: goal_achieved  steps: ['public_works_response', 'approve_alert', 'send_email_alert']

--- heatwave: Dry Gulch ---
  [assess] Dry Gulch: Heatwave / Medium
  [civil_defense_response] Civil defense plan for a Heatwave (Medium) in Dry Gulch: public safety advisories, cooling centres.
  [human] goap_action_approval for approve_alert -> True
  [approve_alert] operator approved
  [smtp] sent 'Weather Alert: Medium Heatwave in Dry Gulch' on attempt 1
  status: goal_achieved  steps: ['civil_defense_response', 'approve_alert', 'send_email_alert']

--- calm: Fairweather ---
  [assess] Fairweather: No Immediate Threat / Low
  [log_all_clear] Fairweather: no immediate threat, nothing sent
  status: goal_achieved  steps: ['log_all_clear']

3. Disruption: the operator says no, the relay flaps, the relay dies#

A denial fails approve_alert with the operator’s reason attached. The observer blacklists it, and now no action produces approved, so the planner has no path to forecast_handled. That is where the FunctionalStuckHandler runs: it relaxes the goal to decision_logged and records the reason, and withhold_alert is the plan. The run ends goal_achieved against the relaxed goal, which is visible in the result.

import logging, sys

logging.basicConfig(stream=sys.stdout, format="  log  %(message)s", level=logging.WARNING, force=True)

from examples.screencast.weather_alert import after_disrupted

denied = after_disrupted.denied_alert()
============================================================
  DISRUPTION 1 — the operator denies the flood alert
============================================================
  [assess] Riverton: Flood / Medium
  [public_works_response] Public works plan for a Flood (Medium) in Riverton: drainage, road closures, sandbags.
  [human] approval for approve_alert -> DENY ('river gauge is stable')
  log  Action 'approve_alert' failed: human_approval_denied: river gauge is stable
  log  No plan for goal {'forecast_handled': True}: Every remaining path to the goal needs an action the operator denied: approve_alert (river gauge is stable). Retries and ActionQos do not apply to a denial: add an alternative action, attach a stuck handler that relaxes the goal, or run again once the decision changes.
  [withhold_alert] Alert for Riverton withheld: river gauge is stable
  status: goal_achieved  goal: {'decision_logged': True}  replans: 1  blacklisted: ['approve_alert']
    ok   public_works_response
    FAIL approve_alert — human_approval_denied: river gauge is stable
    ok   withhold_alert
  alert_sent=False channel=None decision_log='Alert for Riverton withheld: river gauge is stable'

A dropped SMTP connection is retried inside the action by ActionQos (no re-plan, one history entry). A relay that rejects the message outright is not retryable: the action fails, is blacklisted, and send_sms_alert (cost 3) is the next cheapest route to the same effect.

flaky = after_disrupted.flaky_smtp()
dead = after_disrupted.dead_smtp()
============================================================
  DISRUPTION 2 — the SMTP connection drops once (ActionQos retries)
============================================================
  [assess] Port Mayfield: Hurricane / Critical
  [emergency_response] Emergency plan for a Hurricane (Critical) in Port Mayfield: immediate actions, shelters, evacuation routes.
  [smtp] sent 'Weather Alert: Critical Hurricane in Port Mayfield' on attempt 2
  smtp attempts: 2
  status: goal_achieved  goal: {'forecast_handled': True}  replans: 0  blacklisted: []
    ok   emergency_response
    ok   send_email_alert
  alert_sent=True channel=email decision_log=None

============================================================
  DISRUPTION 3 — the relay rejects the message outright (SMS fallback)
============================================================
  [assess] Port Mayfield: Hurricane / Critical
  [emergency_response] Emergency plan for a Hurricane (Critical) in Port Mayfield: immediate actions, shelters, evacuation routes.
  log  Action 'send_email_alert' failed: SMTP relay rejected the message (550)
  [send_sms_alert] SMS: Critical Hurricane in Port Mayfield
  smtp attempts: 1
  status: goal_achieved  goal: {'forecast_handled': True}  replans: 1  blacklisted: ['send_email_alert']
    ok   emergency_response
    FAIL send_email_alert — SMTP relay rejected the message (550)
    ok   send_sms_alert
  alert_sent=True channel=sms decision_log=None

4. What replaced what#

Hand-wired piece

GOAP replacement

route_response (3 branches, 1 unreachable literal)

preconditions on severe / flood_or_storm / threat

get_human_verification (input() loop + auto-approve else)

approve_alert with require_human_approval=True; approved: True from the sensor when severe

verify_approval_router + handle_no_approval

blacklist, stuck handler, withhold_alert

try/except around smtplib

ActionQos(max_attempts=3, retryable_exceptions=(ConnectionError,)), then send_sms_alert

“No immediate threat” → civil defense → e-mail

log_all_clear

The integration test tests/integration/test_screencast_weather_alert.py pins the four paths, the gate payload, the denial-and-relax path, both relay failures and the async path, and keeps the hand-wired version faithful to upstream (dead literal included).