""" agent.py — Simulated AI Rostering Agent Implements the 5-step agent flow: 1. Analyze → identify unfilled shifts 2. Filter → find eligible nurses with capacity 3. Outreach → simulate SMS/WhatsApp messages (mock Twilio) 4. Resolve → simulate nurse responses 5. Update → fill the roster and report back In production, replace the clearly-marked simulation blocks with: • LLM API calls (OpenAI / Anthropic / Gemini) for natural-language reasoning • Twilio / WhatsApp Business API for real outreach • Database writes for persistence """ from __future__ import annotations import random import time from dataclasses import dataclass from datetime import date from typing import Generator from mock_data import ( Nurse, ShiftSlot, eligible_nurses_for_slot, get_unfilled_slots, week_number, ) # ── Agent response streaming ───────────────────────────────────────────────── @dataclass class AgentStep: """One chunk of the agent's thought process, streamed to the UI.""" phase: str # e.g. "🔍 Analyze", "📲 Outreach" message: str # markdown-formatted content def run_agent( roster: list[ShiftSlot], nurses: list[Nurse], user_prompt: str, ) -> Generator[AgentStep, None, list[ShiftSlot]]: """Generator that yields AgentSteps and mutates the roster in-place. The caller iterates over yielded steps to build the chat log, then collects the final roster state. """ # ────────────────────────────────────────────────────────────────────── # STEP 1 — ANALYZE # In production: send the roster + prompt to an LLM to identify intent # and extract which gaps to fill. # ────────────────────────────────────────────────────────────────────── unfilled = get_unfilled_slots(roster) if not unfilled: yield AgentStep( phase="✅ Complete", message="All shifts are fully staffed — no action needed.", ) return roster yield AgentStep( phase="🔍 Step 1 — Analyze", message=_format_gap_analysis(unfilled, roster), ) # ────────────────────────────────────────────────────────────────────── # STEP 2 — FILTER ELIGIBLE NURSES # In production: query the HR database / BQ for nurse availability, # leave balance, skills match, etc. # ────────────────────────────────────────────────────────────────────── fill_plan: list[tuple[ShiftSlot, list[Nurse]]] = [] for slot in unfilled: eligible = eligible_nurses_for_slot(slot, nurses, roster) fill_plan.append((slot, eligible)) yield AgentStep( phase="🎯 Step 2 — Filter Eligible Nurses", message=_format_eligibility(fill_plan, roster), ) # ────────────────────────────────────────────────────────────────────── # STEP 3 — OUTREACH (MOCKED) # In production: call Twilio REST API or WhatsApp Business API here. # Example: # from twilio.rest import Client # client = Client(ACCOUNT_SID, AUTH_TOKEN) # client.messages.create(body=msg, from_=TWILIO_NUM, to=nurse.phone) # ────────────────────────────────────────────────────────────────────── outreach_log = _simulate_outreach(fill_plan) yield AgentStep( phase="📲 Step 3 — Outreach (Simulated SMS/WhatsApp)", message=outreach_log, ) # ────────────────────────────────────────────────────────────────────── # STEP 4 — RESOLVE RESPONSES # In production: poll for incoming webhook responses from Twilio, # or use an async callback handler. # ────────────────────────────────────────────────────────────────────── assignments, resolution_log = _simulate_responses(fill_plan) yield AgentStep( phase="📩 Step 4 — Nurse Responses", message=resolution_log, ) # ────────────────────────────────────────────────────────────────────── # STEP 5 — UPDATE ROSTER # In production: write to BigQuery / Postgres, notify the manager, # update the calendar system. # ────────────────────────────────────────────────────────────────────── for slot, nurse in assignments: if nurse not in slot.assigned: slot.assigned.append(nurse) remaining = get_unfilled_slots(roster) yield AgentStep( phase="✅ Step 5 — Roster Updated", message=_format_completion(assignments, remaining), ) return roster # ── Formatting helpers ──────────────────────────────────────────────────────── def _format_gap_analysis(unfilled: list[ShiftSlot], roster: list[ShiftSlot]) -> str: lines = [f"Found **{len(unfilled)} unfilled shift(s)** across the 2-week roster:\n"] lines.append("| # | Date | Day | Shift | Hours | Vacancies |") lines.append("|---|------|-----|-------|-------|-----------|") for i, s in enumerate(unfilled, 1): day_name = s.day.strftime("%A") lines.append( f"| {i} | {s.day.strftime('%d %b')} | {day_name} " f"| {s.shift_name} | {s.shift_hours} | {s.vacancies} |" ) return "\n".join(lines) def _format_eligibility( fill_plan: list[tuple[ShiftSlot, list[Nurse]]], roster: list[ShiftSlot], ) -> str: lines = ["Searching the 20-nurse pool for availability…\n"] for slot, eligible in fill_plan: day_name = slot.day.strftime("%A") lines.append( f"**{slot.day.strftime('%d %b')} ({day_name}) — {slot.shift_name}** " f"→ {len(eligible)} eligible nurses" ) top3 = eligible[:3] for n in top3: week = week_number(slot, roster) from mock_data import nurse_shifts_in_week current = nurse_shifts_in_week(n, roster, week) lines.append(f" - {n.name} — {current}/5 shifts this week") if len(eligible) > 3: lines.append(f" - … and {len(eligible) - 3} more\n") else: lines.append("") return "\n".join(lines) def _simulate_outreach(fill_plan: list[tuple[ShiftSlot, list[Nurse]]]) -> str: """Mock SMS/WhatsApp outreach to top-3 eligible nurses per gap.""" lines = ["Sending shift-cover requests…\n"] lines.append("```") for slot, eligible in fill_plan: top3 = eligible[:3] day_str = slot.day.strftime("%d %b (%A)") for n in top3: lines.append( f"📱 → {n.name} ({n.phone})\n" f' "Hi {n.name.replace("Nurse ", "")}, ' f"can you cover {slot.shift_name} shift on {day_str} " f'({slot.shift_hours})? Reply YES to confirm."' ) lines.append("") lines.append("```") lines.append(f"\n✅ **{sum(min(3, len(e)) for _, e in fill_plan)} messages sent** — awaiting responses…") return "\n".join(lines) def _simulate_responses( fill_plan: list[tuple[ShiftSlot, list[Nurse]]], ) -> tuple[list[tuple[ShiftSlot, Nurse]], str]: """Simulate nurse replies — first eligible nurse always says YES.""" rng = random.Random(99) assignments: list[tuple[ShiftSlot, Nurse]] = [] lines = ["Responses received:\n"] lines.append("```") for slot, eligible in fill_plan: filled = False top3 = eligible[:3] for i, n in enumerate(top3): # Simulate: first nurse accepts, others may decline if not filled and (i == 0 or rng.random() > 0.5): lines.append(f"✅ {n.name}: \"YES — I'll take it!\"") assignments.append((slot, n)) filled = True else: lines.append(f"❌ {n.name}: \"Sorry, can't make it.\"") if not filled: lines.append(f"⚠️ No confirmation yet for {slot.day.strftime('%d %b')} {slot.shift_name}") lines.append("") lines.append("```") return assignments, "\n".join(lines) def _format_completion( assignments: list[tuple[ShiftSlot, Nurse]], remaining: list[ShiftSlot], ) -> str: lines = [f"**{len(assignments)} shift(s) filled successfully!**\n"] lines.append("| Date | Shift | Assigned To |") lines.append("|------|-------|-------------|") for slot, nurse in assignments: lines.append( f"| {slot.day.strftime('%d %b (%a)')} | {slot.shift_name} | {nurse.name} |" ) lines.append("") if remaining: lines.append( f"⚠️ **{len(remaining)} shift(s) still unfilled** — " "consider extending outreach to part-time or agency staff." ) else: lines.append("🎉 **All shifts are now fully covered!** Roster is complete.") return "\n".join(lines)