{"slug": "from-heartbeat-to-hospital-building-a-closed-loop-health-agent-with-langgraph", "title": "From Heartbeat to Hospital: Building a Closed-Loop Health Agent with LangGraph", "summary": "A developer has built a closed-loop health assistant using LangGraph, LangChain, and the HealthKit API. The system detects heart rate anomalies, verifies symptoms with the user, and automatically books doctor appointments through hospital APIs. The workflow uses a state machine to manage loops and user interruptions for safety.", "body_md": "We live in an era where our watches know more about our hearts than we do. But there’s a massive gap between receiving a \"High Heart Rate\" notification and actually sitting in a doctor's office. Most health apps just give you data; they don't give you a solution. Today, we are bridging that gap by building a **closed-loop health assistant** using **LangGraph**, **LangChain**, and the **HealthKit API**.\n\nBy leveraging **AI Agents** and advanced **LLM healthcare automation**, we can create a system that doesn't just monitor—it acts. We’ll be using a **LangGraph state machine** to orchestrate a complex workflow: detecting anomalies, verifying symptoms with the user, and automatically interacting with hospital booking APIs. 🏥💻\n\nUnlike simple linear chains, health interventions require loops and state persistence. If a user is feeling fine despite a high heart rate, we might just log it. If they feel dizzy, we book an appointment.\n\nHere is how the data flows through our LangGraph agent:\n\n``` php\ngraph TD\n    A[Start: HealthKit Alert] --> B{Analyze Heart Data}\n    B -- Normal --> C[Log & End]\n    B -- Anomaly Detected --> D[Ask User for Symptoms]\n    D --> E{User Response}\n    E -- \"I'm fine\" --> F[Log Observation]\n    E -- \"I feel dizzy/pain\" --> G[Search Available Doctors]\n    G --> H[Confirm Appointment Time]\n    H --> I[Execute Booking API]\n    I --> J[Notify User & Send Calendar Invite]\n    F --> K[End]\n    J --> K\n```\n\nTo follow this advanced tutorial, you'll need:\n\nIn LangGraph, the `State`\n\nobject is the single source of truth. It tracks the conversation history, health metrics, and whether a booking is required.\n\n``` python\nfrom typing import Annotated, TypedDict, List, Union\nfrom langgraph.graph.message import add_messages\n\nclass AgentState(TypedDict):\n    # Tracks the conversation history\n    messages: Annotated[list, add_messages]\n    # Current health vitals\n    vitals: dict\n    # Booking status\n    booking_confirmed: bool\n    # User symptoms\n    symptoms: List[str]\n```\n\nOur agent needs to interact with the real world. We’ll define two tools: one to fetch health data and one to book appointments.\n\n``` python\nfrom langchain_core.tools import tool\n\n@tool\ndef fetch_health_metrics():\n    \"\"\"Fetches the latest heart rate data from HealthKit.\"\"\"\n    # In a real app, this calls the iOS Bridge\n    return {\"heart_rate\": 115, \"status\": \"Tachycardia Detected\", \"timestamp\": \"2023-10-27T10:30:00\"}\n\n@tool\ndef book_doctor_appointment(specialty: str, preferred_time: str):\n    \"\"\"Books an appointment via the hospital API.\"\"\"\n    print(f\"CONFIRMED: Booking {specialty} for {preferred_time}\")\n    return {\"status\": \"Success\", \"appointment_id\": \"REF-9921\", \"doctor\": \"Dr. Smith\"}\n```\n\nNow, we define the nodes and the logic that governs the transitions. We use a `ToolNode`\n\nto handle the execution of our Python functions.\n\n``` python\nfrom langgraph.prebuilt import ToolNode\nfrom langgraph.graph import StateGraph, END\n\n# Define the Logic Node\ndef analyze_data(state: AgentState):\n    # Logic to decide if we need to escalate to a doctor\n    vitals = state.get(\"vitals\", {})\n    if vitals.get(\"heart_rate\", 0) > 100:\n        return {\"messages\": [(\"system\", \"Heart rate is high. I must ask the user about symptoms.\")]}\n    return {\"messages\": [(\"system\", \"Everything looks normal.\")]}\n\n# Build the Graph\nworkflow = StateGraph(AgentState)\n\nworkflow.add_node(\"monitor\", analyze_data)\nworkflow.add_node(\"tools\", ToolNode([fetch_health_metrics, book_doctor_appointment]))\n\nworkflow.set_entry_point(\"monitor\")\n# ... (Additional edges and logic would go here)\n```\n\nA critical aspect of healthcare agents is safety. We don't want the AI booking surgery without a \"Yes\" from the human. LangGraph's `interrupt`\n\nfeature allows us to pause execution until the user provides input. 🛑\n\n```\n# In a real implementation, we use a breakpoint before the booking tool\n# to ensure the user has explicitly agreed to the time and date.\n```\n\nBuilding a toy agent is easy; building a HIPAA-compliant, production-grade health system is a different beast. For deep dives into advanced state-management patterns and enterprise AI deployment, I highly recommend checking out the ** WellAlly Tech Blog**.\n\nThey provide excellent resources on:\n\nIt’s been a massive source of inspiration for how I structure my production LangGraph instances!\n\nBy moving from a \"reactive\" dashboard to a \"proactive\" agent, we change the user experience from anxiety-inducing alerts to seamless care coordination. LangGraph provides the perfect framework for this because it treats \"loops\" and \"state\" as first-class citizens.\n\n**What do you think?** Would you trust an AI agent to book your doctor's appointment? Let's discuss in the comments below! 👇\n\n*If you enjoyed this tutorial, don't forget to **Follow** for more \"Learning in Public\" AI content!* 🚀", "url": "https://wpnews.pro/news/from-heartbeat-to-hospital-building-a-closed-loop-health-agent-with-langgraph", "canonical_source": "https://dev.to/beck_moulton/from-heartbeat-to-hospital-building-a-closed-loop-health-agent-with-langgraph-1pjm", "published_at": "2026-09-02 00:44:00+00:00", "updated_at": "2026-09-02 01:22:49.502790+00:00", "lang": "en", "topics": ["ai-agents", "developer-tools", "artificial-intelligence"], "entities": ["LangGraph", "LangChain", "HealthKit API", "AI Agents", "LLM"], "alternates": {"html": "https://wpnews.pro/news/from-heartbeat-to-hospital-building-a-closed-loop-health-agent-with-langgraph", "markdown": "https://wpnews.pro/news/from-heartbeat-to-hospital-building-a-closed-loop-health-agent-with-langgraph.md", "text": "https://wpnews.pro/news/from-heartbeat-to-hospital-building-a-closed-loop-health-agent-with-langgraph.txt", "jsonld": "https://wpnews.pro/news/from-heartbeat-to-hospital-building-a-closed-loop-health-agent-with-langgraph.jsonld"}}