DEV Community

Beck_Moulton
Beck_Moulton

Posted on

Stop Overtraining: Build a Bio-Hacker Agent with LangGraph and WHOOP

We’ve all been there. You have a "Heavy Leg Day" blocked on your calendar, but you wake up feeling like a truck hit you. Your Heart Rate Variability (HRV) is in the gutter, and your recovery score is a measly 14%. Traditionally, you'd either push through and risk injury or manually move things around.

But we are developers. We don't do things manually.

In this tutorial, we are building a Bio-Hacker Agent. This is a sophisticated agentic automation system that uses LangGraph to monitor your biometrics via the WHOOP API. If your recovery metrics drop below a certain threshold, the agent autonomously re-writes your Google Calendar and suggests a personalized, low-intensity nutrition plan.

By the end of this post, you'll understand how to bridge the gap between wearable IoT data and actionable AI decision-making using a state-of-the-art tech stack including Pydantic AI and LangGraph.


The Architecture: Biometric Feedback Loop

Before we dive into the code, let’s look at the data flow. We aren't just building a simple script; we are building a state machine that makes decisions based on physiological "vitals."

graph TD
    A[Start: Daily Sync] --> B[Fetch WHOOP Recovery Data]
    B --> C{Is HRV/Recovery Low?}
    C -- "No (Green Zone)" --> D[Keep Existing Schedule]
    C -- "Yes (Red/Yellow Zone)" --> E[Agent: Initiate Pivot]
    E --> F[Google Calendar API: Reschedule Workout]
    E --> G[Pydantic AI: Generate Anti-Inflammatory Recipe]
    F --> H[Notify User via Slack/Push]
    G --> H
    D --> I[End]
    H --> I
Enter fullscreen mode Exit fullscreen mode

Prerequisites

To follow along, you’ll need:

  • WHOOP Developer Account: To access the Recovery API.
  • Google Cloud Console: With Calendar API enabled.
  • Tech Stack: Python 3.10+, langgraph, pydantic-ai, and google-api-python-client.

Step 1: Defining the Agent State

We use Pydantic AI to define the structure of our agent's "brain." This ensures that when the AI decides to change our schedule, it follows a strict schema that won't break our APIs.

from pydantic import BaseModel, Field
from typing import List, Optional

class RecoveryAction(BaseModel):
    is_pivot_needed: bool = Field(description="True if HRV is below 50% of 7-day average")
    new_workout_type: Optional[str] = Field(description="Recommended activity (e.g., Yoga, Zone 2 Walk)")
    reasoning: str = Field(description="Explanation for the change based on metrics")
    suggested_calories: int = Field(description="Adjusted calorie target for low intensity")
Enter fullscreen mode Exit fullscreen mode

Step 2: Building the LangGraph Logic

LangGraph allows us to treat the AI's decision process as a directed graph. This is much more robust than a simple "if/else" chain because it allows for retries and complex state management.

from langgraph.graph import StateGraph, END
from typing import TypedDict

class AgentState(TypedDict):
    hrv_score: int
    recovery_percent: int
    calendar_events: List[str]
    action_plan: RecoveryAction

def check_biometrics(state: AgentState):
    # Logic to fetch from WHOOP API would go here
    # For now, let's simulate a 'Red Recovery' day
    return {"hrv_score": 35, "recovery_percent": 22}

def analyze_and_pivot(state: AgentState):
    # This is where the LLM (GPT-4o) makes a decision
    if state["recovery_percent"] < 50:
        return {
            "action_plan": RecoveryAction(
                is_pivot_needed=True,
                new_workout_type="Rest & Mobility",
                reasoning="HRV is 30% below baseline. High risk of CNS fatigue.",
                suggested_calories=2100
            )
        }
    return {"action_plan": RecoveryAction(is_pivot_needed=False)}

# Construct the Graph
workflow = StateGraph(AgentState)
workflow.add_node("fetch_data", check_biometrics)
workflow.add_node("analyze", analyze_and_pivot)

workflow.set_entry_point("fetch_data")
workflow.add_edge("fetch_data", "analyze")
workflow.add_edge("analyze", END)

app = workflow.compile()
Enter fullscreen mode Exit fullscreen mode

Step 3: Executing Calendar Adjustments

If the agent decides a pivot is necessary, it triggers the Google Calendar tool. Here is a snippet of how the agent interacts with external APIs to actually "do the work."

from googleapiclient.discovery import build

def update_calendar(action: RecoveryAction):
    if not action.is_pivot_needed:
        print("Sticking to the plan. Get after it! 💪")
        return

    service = build('calendar', 'v3', credentials=creds)
    event = {
        'summary': f'🌱 {action.new_workout_type} (AI Adjusted)',
        'description': f'Reason: {action.reasoning}',
        'start': {'dateTime': '2023-10-27T09:00:00Z', 'timeZone': 'UTC'},
        'end': {'dateTime': '2023-10-27T10:00:00Z', 'timeZone': 'UTC'},
    }
    # Logic to find current 'Workout' and update it
    print(f"Calendar Updated: {action.new_workout_type}")
Enter fullscreen mode Exit fullscreen mode

The "Official" Way to Build Health-Tech AI

While this DIY agent is a great start, building production-ready health-tech agents requires handling edge cases like OAuth token refreshing, HIPAA compliance (if applicable), and complex biometric signal processing.

For more advanced patterns on integrating LLMs with wearable data and production-ready agentic architectures, I highly recommend checking out the deep-dive articles at WellAlly Blog. They cover the intersection of AI and Longevity in much greater detail, providing the architectural blueprints used by top-tier health startups.


Step 4: Generating the Recovery Recipe

The final piece of our Bio-Hacker agent is nutrition. Using the suggested_calories from our Pydantic model, we can prompt an LLM to generate a meal plan that aids recovery.

def generate_recipe(action: RecoveryAction):
    prompt = f"Create a meal plan for {action.suggested_calories} calories focused on anti-inflammatory ingredients for someone with low HRV."
    # Call OpenAI/Anthropic...
    print(f"Recipe generated for recovery day!")
Enter fullscreen mode Exit fullscreen mode

Conclusion

By combining LangGraph and WHOOP, we’ve moved from "static" scheduling to "dynamic" bio-adaptive living. This agent doesn't just follow instructions; it listens to your body and acts on your behalf.

What's next for your Bio-Hacker Agent?

  1. Add Slack notifications to alert you the moment you wake up.
  2. Integrate MyFitnessPal to auto-log your macro targets.
  3. Expand to include sleep data analysis.

If you enjoyed this build, drop a comment below or share your own bio-hacking scripts! And don't forget to visit wellally.tech/blog for more insights into the future of AI-driven wellness.

Top comments (0)