Download agent.py from Yaoyeeng/Nurse-Rostering-AI-Agent: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/Yaoyeeng/Nurse-Rostering-AI-Agent/resolve/main/agent.py
- Command line
-
hf download hf://spaces/Yaoyeeng/Nurse-Rostering-AI-Agent/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/Yaoyeeng/Nurse-Rostering-AI-Agent/resolve/main/agent.py
10.3 kB
| """ | |
| 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 βββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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) | |