"""Neo agent: an OpenAI tool-calling loop that runs *inside* the FastAPI backend, so every data tool executes against SQLite with the authenticated `uid`. The model only proposes tool calls; this module decides and executes them. The RAG service is exposed to the model as one tool among several (`search_knowledge_base`) and never receives user identity. Commit 1 scope: read/query tools + knowledge search. Write tools (draft + user-confirmed commit) are added in a later change; `pending_writes` is already threaded through the response shape so the frontend contract is stable. """ import json import os import re import traceback import uuid from datetime import date, datetime, timezone # pyrefly: ignore [missing-import] from fastapi import HTTPException # pyrefly: ignore [missing-import] from sqlalchemy.orm import Session # pyrefly: ignore [missing-import] from sqlalchemy import cast, Integer from shared import ( DailyLogTable, CycleLogTable, ANCVisitsTable, dateToEpoch, ) from rag_client import rag_ask # ── Environment ────────────────────────────────────────────────────────────── # The repo-root .env is already loaded by `shared` (imported above) at process # start, so there's no separate loader here — it would be a redundant copy. # OpenAI is the only configured provider in this project's env, and its SDK # supports function calling. Override the model via AGENT_MODEL if desired. AGENT_MODEL = os.environ.get("AGENT_MODEL", "gpt-4o") MAX_TOOL_ITERS = 6 # Cap rows fed back to the model to keep the context (and cost) bounded. MAX_ROWS = 60 # The three conversation threads the app routes messages between. A cheap model # classifies the best thread for a message so routing reflects the model's # understanding, not just keyword hits. Set AGENT_CLASSIFY_MODEL="" to disable. TABS = ("baby", "pregnancy", "ttc") CLASSIFY_MODEL = os.environ.get("AGENT_CLASSIFY_MODEL", "gpt-4o-mini") # Screens the agent may send the user to. Each maps a model-facing id to the # React Navigation route name (see src/navigation/MainNavigator.tsx) and a # human label for the button the app renders. Navigation is surfaced to the app # as an action the user taps — the agent proposes, the user moves — so it can # never yank someone off the screen unexpectedly. NAV_TARGETS: dict[str, dict[str, str]] = { "home": {"route": "Home", "label": "Open Home"}, "quick_help": {"route": "QuickHelp", "label": "Open Quick Help"}, "store": {"route": "NeoStore", "label": "Open the Neo Store"}, "cart": {"route": "Cart", "label": "View Cart"}, "profile": {"route": "Profile", "label": "Open Profile"}, "log_symptoms": {"route": "SymptomLog", "label": "Log today's symptoms"}, "cycle_tracker": {"route": "CycleTracker", "label": "Open Cycle Tracker"}, "cycle_history": {"route": "CycleHistory", "label": "View Cycle History"}, "anc_visits": {"route": "ANCVisits", "label": "Open ANC Visits"}, "routine": {"route": "Routine", "label": "Open your Routine"}, "visit_prep": {"route": "VisitPrep", "label": "Prepare for your visit"}, "baby_development": {"route": "BabyDevelopment", "label": "See Baby Development"}, "facility_map": {"route": "FacilityMap", "label": "Find nearby facilities"}, "recommendations": {"route": "AllRecommendations", "label": "See Recommendations"}, "edit_goals": {"route": "EditGoals", "label": "Edit your Goals"}, "consultations": {"route": "Consultations", "label": "Open Consultations"}, "preconception_checklist": {"route": "PreconceptionChecklist", "label": "Open Preconception Checklist"}, "wishlist": {"route": "Wishlist", "label": "Open your Wishlist"}, } # A compact id->label guide injected into the navigate tool description so the # model can map natural phrases ("NeoStore", "cycle tracker", "ANC visits") to # the right screen id. _SCREEN_GUIDE = "; ".join(f"'{sid}' = {meta['label']}" for sid, meta in NAV_TARGETS.items()) # ── Deterministic navigation intent ────────────────────────────────────────── # Explicit "take me to / open / show me " requests must reliably produce # a shortcut even when the LLM doesn't choose the navigate_to_screen tool (some # models prefer to "answer" or search instead). This rule-based matcher runs # before the model and guarantees navigation for clear commands. It also works # when the agent is disabled (RAG-only) since it lives in the chat route. _NAV_VERB = re.compile( r"\b(take me to|bring me to|go to|open|show me|show my|navigate to|see my|see the|" r"view my|view the|let me see|jump to|i want to see|i want to open|can you open|can you show)\b" ) # Most-specific aliases first so e.g. "cycle history" wins over "cycle tracker". _NAV_ALIASES: list[tuple[tuple[str, ...], str]] = [ (("neostore", "neo store", "the store", "shop", "marketplace"), "store"), (("cycle history", "past cycles", "my cycles"), "cycle_history"), (("cycle tracker", "track my cycle", "log my cycle", "fertility tracker"), "cycle_tracker"), (("anc visit", "anc visits", "antenatal visit", "antenatal care", "anc record"), "anc_visits"), (("visit prep", "prepare for my visit", "prep for my visit", "visit preparation"), "visit_prep"), (("baby development", "baby's development", "milestones"), "baby_development"), (("quick help", "emergency help"), "quick_help"), (("symptom log", "log symptoms", "log symptom", "log my symptoms", "record symptoms"), "log_symptoms"), (("preconception checklist", "preconception", "checklist"), "preconception_checklist"), (("facilities", "facility map", "clinic near", "hospital near", "nearby clinic", "find a clinic"), "facility_map"), (("consultations", "consultation"), "consultations"), (("recommendations", "recommendation"), "recommendations"), (("wishlist", "wish list"), "wishlist"), (("routine", "daily routine"), "routine"), (("cart", "basket", "shopping cart"), "cart"), (("edit goals", "my goals", "goals"), "edit_goals"), (("profile", "account settings"), "profile"), (("home screen", "dashboard", "home page", "home"), "home"), ] _NAV_FILLER = re.compile( r"\b(the|my|a|an|to|please|app|screen|page|section|now|for me|me|go|open|take)\b" ) def match_navigation(question: str) -> tuple[dict | None, bool]: """Detect an explicit app-navigation request. Returns (nav, is_pure): * nav — {screen, route, label} for the matched screen, or None. * is_pure — True when the message is essentially *only* the command (e.g. "take me to the NeoStore"), so the chat route can short-circuit with just the shortcut instead of an LLM answer. Word-boundary matching avoids false hits ("home" won't match "homeopathy"). """ q = (question or "").lower().strip() if not q: return None, False has_verb = bool(_NAV_VERB.search(q)) for aliases, sid in _NAV_ALIASES: for alias in aliases: if not re.search(rf"\b{re.escape(alias)}\b", q): continue if not (has_verb or q in aliases): continue # bare topic mention without intent — let the model handle it # Purity: strip the verb, the matched alias, and filler; if nothing # meaningful remains, it's a direct navigation command. remainder = _NAV_VERB.sub(" ", q) remainder = re.sub(rf"\b{re.escape(alias)}\b", " ", remainder, count=1) remainder = _NAV_FILLER.sub(" ", remainder) remainder = re.sub(r"[^\w]+", " ", remainder).strip() meta = NAV_TARGETS[sid] return {"screen": sid, "route": meta["route"], "label": meta["label"]}, remainder == "" return None, False class AgentUnavailable(Exception): """Raised when no agent LLM is configured, so the caller can fall back to plain RAG answering.""" def agent_enabled() -> bool: return bool(os.environ.get("OPENAI_API_KEY")) def _client(): # Imported lazily so the backend still boots if the SDK is absent. # pyrefly: ignore [missing-import] from openai import AsyncOpenAI key = os.environ.get("OPENAI_API_KEY") if not key: return None return AsyncOpenAI(api_key=key) # ── System prompt ──────────────────────────────────────────────────────────── # Mirrors the "Neo" persona + safety rules in rag/src/pipeline.ts so the agent # and the RAG answers speak with one voice, plus tool-use guidance. NEO_SYSTEM = """You are Neo, a specialized medical assistant created by the Neonatal Dao team, dedicated to pregnancy, maternal health, neonatal care, and infant development (0-3 years). You give evidence-based answers that are thorough, warm, and clear enough for a non-medical parent to understand. You are familiar with clinical guidelines from Nigeria, Ghana, Kenya, and the UK. SAFETY RULES — NON-NEGOTIABLE: - Never ask for or record personally identifiable information. - Never provide a specific diagnosis; describe possibilities and always direct the user to a qualified healthcare professional for diagnosis and treatment. - Never provide dosage instructions for prescription medications. - If the user describes an emergency (seizure, stopped breathing, severe bleeding, unresponsive child), tell them to contact emergency services immediately before anything else. YOU ARE EMBEDDED INSIDE THE ASKNEO APP (mobile + web). The app has its own screens you can take the user to — the "NeoStore" (in-app shop), "Cycle Tracker", "ANC Visits", "Routine", "Quick Help", "Profile", "Symptom Log", and more. These are PARTS OF THIS APP, not external sites or knowledge-base topics. USING TOOLS: - NAVIGATION COMES FIRST for app-destination requests. If the user asks to go to / open / take me to / show me / navigate to a part of the app (e.g. "take me to the NeoStore", "open cycle tracker", "show my ANC visits", "go to my routine"), call `navigate_to_screen` with the matching screen — do NOT call search_knowledge_base for it and do NOT say you can't open it. App screen names are never things to look up in the knowledge base. - For general medical/clinical questions, call `search_knowledge_base` and ground your answer in what it returns. Mark anything not from it as general guidance. - For questions about THIS user's own tracked data (their logs, cycles, antenatal visits, profile, next appointment), call the relevant get_* tool — never guess or fabricate their data. - When the user wants to LOG or RECORD something (a daily log, a cycle entry, an ANC visit), call the matching draft_* tool. A draft is NOT saved: it is shown to the user as a confirmation card. After drafting, tell the user you've prepared the entry and ask them to confirm it below — never say it has been saved. - You may also offer `navigate_to_screen` proactively when a screen is the natural next step (e.g. suggesting the user log symptoms). The app renders it as a button the user taps, so phrase it naturally ("tap the button below to open it") and never claim you changed the screen yourself. - You may call several tools before answering. When you have enough, answer in clear, warm prose. Do not mention tool names or internal mechanics to the user.""" # ── Tool schemas (OpenAI function-calling format) ──────────────────────────── TOOLS = [ { "type": "function", "function": { "name": "search_knowledge_base", "description": ( "Search the maternal/neonatal/infant medical knowledge base for " "evidence-based general guidance. Use for any clinical or medical " "question that is not about the user's own logged data." ), "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "A focused, self-contained medical question or topic.", } }, "required": ["query"], }, }, }, { "type": "function", "function": { "name": "get_profile", "description": ( "Get the current user's profile: stage (ttc/pregnancy/newmom/partner), " "goals, due date, baby date of birth, and birth/feeding intentions." ), "parameters": {"type": "object", "properties": {}}, }, }, { "type": "function", "function": { "name": "get_daily_logs", "description": ( "Get the user's daily health logs (mood, energy, symptoms, medications, " "sleep, kick counts, baby feedings/nappies, water intake) within an " "optional date range. Returns most recent entries." ), "parameters": { "type": "object", "properties": { "from_date": {"type": "string", "description": "Inclusive start date YYYY-MM-DD. Omit for no lower bound."}, "to_date": {"type": "string", "description": "Inclusive end date YYYY-MM-DD. Omit for today."}, }, }, }, }, { "type": "function", "function": { "name": "get_cycle_logs", "description": ( "Get the user's fertility/cycle logs (flow intensity, basal body " "temperature, cervical mucus, OPK/HPT results, intercourse, symptoms) " "within a date range. Use for TTC / cycle-tracking questions." ), "parameters": { "type": "object", "properties": { "from_date": {"type": "string", "description": "Inclusive start date YYYY-MM-DD."}, "to_date": {"type": "string", "description": "Inclusive end date YYYY-MM-DD."}, }, "required": ["from_date", "to_date"], }, }, }, { "type": "function", "function": { "name": "get_anc_visits", "description": ( "Get the user's antenatal care (ANC) visit records, including " "measurements, lab results, prescriptions, and the next appointment date." ), "parameters": {"type": "object", "properties": {}}, }, }, { "type": "function", "function": { "name": "navigate_to_screen", "description": ( "Take the user to a screen inside the AskNeo app (surfaced as a " "one-tap button). ALWAYS use this — not search_knowledge_base — when " "the user asks to open / go to / be taken to / see a part of the app. " "Map their words to the closest screen id. Available screens: " f"{_SCREEN_GUIDE}. Example: 'take me to the NeoStore' -> screen='store'." ), "parameters": { "type": "object", "properties": { "screen": { "type": "string", "enum": list(NAV_TARGETS.keys()), "description": "The screen id to open (see the list in this tool's description).", }, "reason": { "type": "string", "description": "A short, friendly label for why this helps (shown to no one; for your own framing).", }, }, "required": ["screen"], }, }, }, # ── Draft (confirmed-write) tools ──────────────────────────────────────── # These DO NOT write to the database. They prepare a validated entry that is # returned to the app as a pending write; the user confirms it in the chat # before it is committed via the normal endpoint. Always tell the user the # entry is prepared and awaiting their confirmation — never that it is saved. { "type": "function", "function": { "name": "draft_daily_log", "description": ( "Prepare (do NOT save) a daily health log entry for the user to confirm. " "Use when the user asks to log/record how they or their baby are doing today." ), "parameters": { "type": "object", "properties": { "date_key": {"type": "string", "description": "Entry date YYYY-MM-DD. Defaults to today if omitted."}, "stage": {"type": "string", "enum": ["pregnancy", "newmom"]}, "mood": {"type": "integer", "description": "Mood rating 1 (low) to 5 (great)."}, "energy": {"type": "string", "enum": ["low", "medium", "high"]}, "symptoms": {"type": "array", "items": {"type": "string"}}, "symptom_severity": {"type": "string", "enum": ["mild", "moderate", "severe"]}, "sleep_hours": {"type": "number"}, "sleep_quality": {"type": "string", "enum": ["poor", "okay", "good"]}, "kick_count": {"type": "integer"}, "baby_feedings": {"type": "integer"}, "baby_nappies": {"type": "integer"}, "baby_mood": {"type": "string", "enum": ["settled", "fussy", "unsettled"]}, "water_glasses": {"type": "integer"}, "notes": {"type": "string"}, }, }, }, }, { "type": "function", "function": { "name": "draft_cycle_log", "description": ( "Prepare (do NOT save) a fertility/cycle log entry for the user to confirm. " "Use for TTC tracking: period, BBT, OPK/HPT results, intercourse, symptoms." ), "parameters": { "type": "object", "properties": { "date_key": {"type": "string", "description": "Entry date YYYY-MM-DD. Defaults to today if omitted."}, "is_period_start": {"type": "boolean"}, "is_period_flow": {"type": "boolean"}, "flow_intensity": {"type": "string", "enum": ["spotting", "light", "medium", "heavy"]}, "bbt_temp": {"type": "number", "description": "Basal body temperature."}, "cm_type": {"type": "string", "enum": ["dry", "sticky", "creamy", "watery", "egg-white"]}, "opk_result": {"type": "string", "enum": ["negative", "positive", "peak"]}, "hpt_result": {"type": "string", "enum": ["negative", "faint-positive", "positive"]}, "had_sex": {"type": "boolean"}, "used_protection": {"type": "boolean"}, "mood": {"type": "string"}, "symptoms": {"type": "array", "items": {"type": "string"}}, "notes": {"type": "string"}, }, }, }, }, { "type": "function", "function": { "name": "draft_anc_visit", "description": ( "Prepare (do NOT save) an antenatal care (ANC) visit record for the user to " "confirm. Use when the user wants to log details from a clinic visit." ), "parameters": { "type": "object", "properties": { "visit_date": {"type": "string", "description": "Visit date YYYY-MM-DD. Defaults to today if omitted."}, "gestational_week": {"type": "number"}, "weight": {"type": "number"}, "blood_pressure_sys": {"type": "number"}, "blood_pressure_dia": {"type": "number"}, "fundal_height": {"type": "number"}, "baby_heart_rate": {"type": "number"}, "urine_protein": {"type": "string", "enum": ["negative", "positive", "trace"]}, "urine_glucose": {"type": "string", "enum": ["negative", "positive", "trace"]}, "pcv": {"type": "number"}, "malaria_test": {"type": "string", "enum": ["negative", "positive"]}, "blood_group": {"type": "string"}, "hiv_status": {"type": "string", "enum": ["non-reactive", "reactive"]}, "hbs_ag": {"type": "string", "enum": ["negative", "positive"]}, "vdrl": {"type": "string", "enum": ["negative", "positive"]}, "genotype": {"type": "string"}, "class_topics": {"type": "array", "items": {"type": "string"}}, "prescriptions": {"type": "string"}, "concern_flagged": {"type": "boolean"}, "referred_to_doctor": {"type": "boolean"}, "next_appointment_date": {"type": "string", "description": "YYYY-MM-DD"}, "notes": {"type": "string"}, }, }, }, }, ] # ── Serialization helpers ──────────────────────────────────────────────────── def _epoch_to_date(v) -> str | None: if v is None or v == "": return None try: return datetime.fromtimestamp(int(float(v))).strftime("%Y-%m-%d") except (ValueError, TypeError, OSError): return None def _parse_date(s: str | None) -> date | None: if not s: return None try: return datetime.strptime(s.strip(), "%Y-%m-%d").date() except (ValueError, AttributeError): return None def _serialize_row(row, date_cols: list[str], json_cols: list[str]) -> dict: out = {k: v for k, v in row.__dict__.items() if k != "_sa_instance_state"} out.pop("uid", None) # the model doesn't need the internal user id for c in date_cols: if c in out: out[c] = _epoch_to_date(out[c]) for c in json_cols: if c in out: try: out[c] = json.loads(out[c]) if out[c] else [] except (ValueError, TypeError): out[c] = [] return out def _query_daily(db: Session, uid: str, from_date: str | None, to_date: str | None) -> list[dict]: q = db.query(DailyLogTable).filter(DailyLogTable.uid == uid) fd, td = _parse_date(from_date), _parse_date(to_date) if fd: q = q.filter(cast(DailyLogTable.date_key, Integer) >= dateToEpoch(fd)) if td: q = q.filter(cast(DailyLogTable.date_key, Integer) <= dateToEpoch(td)) rows = q.order_by(DailyLogTable.date_key.desc()).limit(MAX_ROWS).all() return [_serialize_row(r, ["date_key"], ["symptoms", "baby_symptoms", "medications"]) for r in rows] def _query_cycle(db: Session, uid: str, from_date: str | None, to_date: str | None) -> list[dict]: q = db.query(CycleLogTable).filter(CycleLogTable.uid == uid) fd, td = _parse_date(from_date), _parse_date(to_date) if fd: q = q.filter(cast(CycleLogTable.date_key, Integer) >= dateToEpoch(fd)) if td: q = q.filter(cast(CycleLogTable.date_key, Integer) <= dateToEpoch(td)) rows = q.order_by(CycleLogTable.date_key.desc()).limit(MAX_ROWS).all() return [_serialize_row(r, ["date_key"], ["symptoms"]) for r in rows] def _query_anc(db: Session, uid: str) -> list[dict]: rows = ( db.query(ANCVisitsTable) .filter(ANCVisitsTable.uid == uid) .order_by(ANCVisitsTable.visit_date.desc()) .limit(MAX_ROWS) .all() ) return [ _serialize_row(r, ["visit_date", "next_appointment_date", "added_at"], ["class_topics"]) for r in rows ] # ── Draft (confirmed-write) builders ───────────────────────────────────────── # Each builds the exact snake_case payload the corresponding POST endpoint # expects (mirrors the frontend toServerPayload shapes), filling safe defaults # for omitted fields. No DB writes happen here — the payload is returned as a # pending write for the user to confirm. def _s(v) -> str | None: """Numbers are stored as strings server-side; pass strings/None through.""" return None if v is None else str(v) def _draft_daily_payload(args: dict) -> dict: return { "date_key": args.get("date_key") or date.today().isoformat(), "last_updated": datetime.now(timezone.utc).isoformat(), "stage": args.get("stage"), "mood": args.get("mood"), "energy": args.get("energy"), "symptoms": args.get("symptoms") or [], "symptom_severity": args.get("symptom_severity"), "medications": args.get("medications") or [], "sleep_hours": _s(args.get("sleep_hours")), "sleep_quality": args.get("sleep_quality"), "kick_count": args.get("kick_count"), "baby_feedings": args.get("baby_feedings"), "baby_nappies": args.get("baby_nappies"), "baby_sleep_hours": _s(args.get("baby_sleep_hours")), "baby_mood": args.get("baby_mood"), "baby_symptoms": args.get("baby_symptoms") or [], "baby_symptom_severity": args.get("baby_symptom_severity"), "water_glasses": args.get("water_glasses"), "notes": args.get("notes") or "", } def _draft_cycle_payload(args: dict) -> dict: # The server's CycleLogBaseModel requires these scalars to be present, so # default them rather than omit. return { "date_key": args.get("date_key") or date.today().isoformat(), "is_period_start": bool(args.get("is_period_start", False)), "is_period_flow": bool(args.get("is_period_flow", False)), "flow_intensity": args.get("flow_intensity"), "bbt_temp": _s(args.get("bbt_temp")) or "", "cm_type": args.get("cm_type"), "opk_result": args.get("opk_result"), "hpt_result": args.get("hpt_result"), "had_sex": bool(args.get("had_sex", False)), "used_protection": bool(args.get("used_protection", False)), "mood": args.get("mood") or "", "symptoms": args.get("symptoms") or [], "notes": args.get("notes") or "", } def _draft_anc_payload(args: dict) -> dict: # Every field must be present (the server model treats `str | None` fields as # required-but-nullable), mirroring the frontend payload exactly. return { "visit_date": args.get("visit_date") or date.today().isoformat(), "gestational_week": _s(args.get("gestational_week")), "weight": _s(args.get("weight")), "blood_pressure_sys": _s(args.get("blood_pressure_sys")), "blood_pressure_dia": _s(args.get("blood_pressure_dia")), "fundal_height": _s(args.get("fundal_height")), "baby_heart_rate": _s(args.get("baby_heart_rate")), "urine_protein": args.get("urine_protein"), "urine_glucose": args.get("urine_glucose"), "pcv": _s(args.get("pcv")), "malaria_test": args.get("malaria_test"), "blood_group": args.get("blood_group"), "hiv_status": args.get("hiv_status"), "hbs_ag": args.get("hbs_ag"), "vdrl": args.get("vdrl"), "genotype": args.get("genotype"), "class_topics": args.get("class_topics") or [], "prescriptions": args.get("prescriptions"), "concern_flagged": bool(args.get("concern_flagged", False)), "referred_to_doctor": bool(args.get("referred_to_doctor", False)), "next_appointment_date": args.get("next_appointment_date"), "notes": args.get("notes"), "added_at": date.today().isoformat(), } def _summarize(parts: list[str]) -> str: return ", ".join(p for p in parts if p) _DRAFTS = { "draft_daily_log": ("daily-log", "/user/daily-logs", _draft_daily_payload), "draft_cycle_log": ("cycle-log", "/user/cycle-logs", _draft_cycle_payload), "draft_anc_visit": ("anc-visit", "/user/anc-visits", _draft_anc_payload), } def _draft_summary(kind: str, p: dict) -> str: if kind == "daily-log": bits = [ f"mood {p['mood']}/5" if p.get("mood") is not None else "", f"energy {p['energy']}" if p.get("energy") else "", f"slept {p['sleep_hours']}h" if p.get("sleep_hours") else "", f"symptoms: {', '.join(p['symptoms'])}" if p.get("symptoms") else "", f"{p['water_glasses']} glasses water" if p.get("water_glasses") is not None else "", ] return f"Daily log for {p['date_key']}" + (f" — {_summarize(bits)}" if _summarize(bits) else "") if kind == "cycle-log": bits = [ "period start" if p.get("is_period_start") else "", f"flow {p['flow_intensity']}" if p.get("flow_intensity") else "", f"BBT {p['bbt_temp']}" if p.get("bbt_temp") else "", f"OPK {p['opk_result']}" if p.get("opk_result") else "", f"HPT {p['hpt_result']}" if p.get("hpt_result") else "", f"symptoms: {', '.join(p['symptoms'])}" if p.get("symptoms") else "", ] return f"Cycle log for {p['date_key']}" + (f" — {_summarize(bits)}" if _summarize(bits) else "") # anc-visit bits = [ f"{p['gestational_week']}wks" if p.get("gestational_week") else "", f"BP {p['blood_pressure_sys']}/{p['blood_pressure_dia']}" if p.get("blood_pressure_sys") else "", f"weight {p['weight']}kg" if p.get("weight") else "", f"next appt {p['next_appointment_date']}" if p.get("next_appointment_date") else "", ] return f"ANC visit on {p['visit_date']}" + (f" — {_summarize(bits)}" if _summarize(bits) else "") # ── Tool execution ─────────────────────────────────────────────────────────── async def _execute_tool(name: str, args: dict, db: Session, uid: str, profile: dict, pending_writes: list, navigations: list) -> dict: try: if name == "navigate_to_screen": screen = (args.get("screen") or "").strip() target = NAV_TARGETS.get(screen) if not target: return {"error": f"unknown screen: {screen}"} # De-dupe: one shortcut per screen per turn. if not any(n["screen"] == screen for n in navigations): navigations.append({ "screen": screen, "route": target["route"], "label": target["label"], }) return { "status": "offered", "label": target["label"], "note": ( "A button labeled '" + target["label"] + "' is now shown to the user. " "Invite them to tap it; do not claim you opened the screen yourself." ), } if name == "search_knowledge_base": query = (args.get("query") or "").strip() if not query: return {"error": "query is required"} try: data = await rag_ask(query, []) return {"answer": data.get("answer", ""), "sources": data.get("sources", [])} except HTTPException as ex: # Degrade gracefully: the agent can still answer from its own # knowledge and tell the user the knowledge base is unavailable. return {"error": str(ex.detail)} if name == "get_profile": return {"profile": profile or {}} if name == "get_daily_logs": return {"logs": _query_daily(db, uid, args.get("from_date"), args.get("to_date"))} if name == "get_cycle_logs": return {"logs": _query_cycle(db, uid, args.get("from_date"), args.get("to_date"))} if name == "get_anc_visits": return {"visits": _query_anc(db, uid)} if name in _DRAFTS: kind, endpoint, builder = _DRAFTS[name] payload = builder(args) summary = _draft_summary(kind, payload) pending_writes.append({ "id": uuid.uuid4().hex, "type": kind, "endpoint": endpoint, "summary": summary, "payload": payload, }) return { "status": "drafted", "summary": summary, "note": ( "Prepared and shown to the user for confirmation. It is NOT saved yet. " "Tell the user you've prepared this entry and ask them to confirm it below." ), } return {"error": f"unknown tool: {name}"} except Exception as ex: # never let a tool error crash the whole turn traceback.print_exc() return {"error": f"tool '{name}' failed: {ex}"} # ── Thread / tab awareness ─────────────────────────────────────────────────── def _thread_context(profile: dict, current_tab: str | None) -> str: """A short system note giving the agent the user's stage and current thread, so its answer is framed for the right context (TTC vs pregnancy vs baby).""" bits: list[str] = [] stage = (profile or {}).get("stage") if stage: bits.append(f"the user's life stage is '{stage}'") if current_tab in TABS: bits.append(f"this message is in the '{current_tab}' conversation thread") if not bits: return "" return "Context for tailoring your answer (do not restate verbatim): " + "; ".join(bits) + "." _TAB_CLASSIFY_SYSTEM = ( "You route a maternal-health chat message to exactly one of three conversation threads:\n" "- ttc: trying to conceive — fertility, ovulation, cycle/period tracking, conception attempts.\n" "- pregnancy: an ongoing pregnancy — antenatal care, labour/delivery, the unborn baby.\n" "- baby: a child already born (0–3 years) — newborn/infant feeding, sleep, milestones, illness.\n" "Use the conversation for context and pick the single best thread for the user's latest message. " "If it is ambiguous or a follow-up, prefer the user's current thread. " 'Respond with JSON only: {"tab": "ttc" | "pregnancy" | "baby"}.' ) async def classify_tab( question: str, history: list[dict], current_tab: str | None = None, profile: dict | None = None, ) -> str | None: """Classify which thread a message belongs to, using a cheap model. Returns one of TABS or None (no model configured, disabled, or any failure) — callers treat None as "keep the client's existing routing".""" if not CLASSIFY_MODEL: return None client = _client() if client is None: return None stage = (profile or {}).get("stage") hints: list[str] = [] if current_tab in TABS: hints.append(f"Current thread: {current_tab}.") if stage: hints.append(f"User's life stage: {stage}.") prefix = (" ".join(hints) + "\n\n") if hints else "" messages: list[dict] = [{"role": "system", "content": _TAB_CLASSIFY_SYSTEM}] for h in history[-4:]: role, content = h.get("role"), h.get("content") if role in ("user", "assistant") and content: messages.append({"role": role, "content": content}) messages.append({"role": "user", "content": f"{prefix}Latest message: {question}"}) try: resp = await client.chat.completions.create( model=CLASSIFY_MODEL, messages=messages, temperature=0, max_tokens=20, response_format={"type": "json_object"}, ) raw = resp.choices[0].message.content or "{}" tab = json.loads(raw).get("tab") return tab if tab in TABS else None except Exception: traceback.print_exc() return None # ── Agent loop ─────────────────────────────────────────────────────────────── async def run_agent( question: str, history: list[dict], db: Session, uid: str, profile: dict, current_tab: str | None = None, ) -> dict: """Run the tool-calling loop and return {answer, sources, pending_writes, provider, model}. Raises AgentUnavailable if no LLM is configured.""" client = _client() if client is None: raise AgentUnavailable() messages: list[dict] = [{"role": "system", "content": NEO_SYSTEM}] thread_ctx = _thread_context(profile, current_tab) if thread_ctx: messages.append({"role": "system", "content": thread_ctx}) for h in history[-8:]: role, content = h.get("role"), h.get("content") if role in ("user", "assistant") and content: messages.append({"role": role, "content": content}) messages.append({"role": "user", "content": question}) collected_sources: list[dict] = [] pending_writes: list[dict] = [] navigations: list[dict] = [] last_model = AGENT_MODEL for _ in range(MAX_TOOL_ITERS): resp = await client.chat.completions.create( model=AGENT_MODEL, messages=messages, tools=TOOLS, tool_choice="auto", temperature=0.3, ) last_model = resp.model or last_model msg = resp.choices[0].message if not msg.tool_calls: return { "answer": msg.content or "", "sources": collected_sources, "pending_writes": pending_writes, "navigations": navigations, "provider": "openai", "model": last_model, } # Echo the assistant's tool-call message, then a tool result per call. messages.append({ "role": "assistant", "content": msg.content, "tool_calls": [ { "id": tc.id, "type": "function", "function": {"name": tc.function.name, "arguments": tc.function.arguments}, } for tc in msg.tool_calls ], }) for tc in msg.tool_calls: try: args = json.loads(tc.function.arguments or "{}") except (ValueError, TypeError): args = {} result = await _execute_tool(tc.function.name, args, db, uid, profile, pending_writes, navigations) if tc.function.name == "search_knowledge_base" and isinstance(result.get("sources"), list): collected_sources.extend(result["sources"]) messages.append({ "role": "tool", "tool_call_id": tc.id, "content": json.dumps(result, default=str), }) # Tool budget exhausted — ask for a final answer with no further tools. resp = await client.chat.completions.create( model=AGENT_MODEL, messages=messages + [{"role": "user", "content": "Give your best final answer now without using tools."}], temperature=0.3, ) return { "answer": resp.choices[0].message.content or "", "sources": collected_sources, "pending_writes": pending_writes, "navigations": navigations, "provider": "openai", "model": last_model, }