Stop me if this sounds familiar: You wake up feeling like a zombie ๐ง, your stress levels are through the roof, and your Apple Watch is screaming that your cortisol is peaking. You know you should eat something restorative, but you end up grabbing a sugary donut instead. What if your biological data could talk directly to your calendar?
Today, we are building HormoneAgent, an advanced AI Agent designed for biohacking enthusiasts. Using LangGraph, LangChain, and the HealthKit API, weโll create an automated workflow that senses physiological shiftsโlike sleep deprivation or hormonal spikesโand dynamically updates your nutrition plan via the Notion SDK. We are moving past simple chatbots into the world of personalized nutrition and autonomous LLM workflows.
The Architecture: Why LangGraph?
Traditional linear chains (like standard LangChain) struggle with loops and state management. When dealing with health data, we need a "cyclic" approach: monitor data -> analyze state -> decide on action -> update records -> repeat.
Here is how the HormoneAgent data flow looks:
graph TD
A[Start: HealthKit Trigger] --> B{Check Cortisol/Sleep}
B -- Normal --> C[Log Daily Status]
B -- Abnormal --> D[Analyze Nutritional Needs]
D --> E[Generate AI Diet Advice]
E --> F[Call Notion API]
F --> G[Update Weekly Meal Plan]
G --> H[End Loop]
C --> H
Prerequisites
To follow along, youโll need:
- Python 3.10+
- LangGraph & LangChain: For the agent logic.
- Notion SDK: To interact with your workspace.
- OpenAI API Key: To power the decision-making (GPT-4o recommended).
Step 1: Defining the Agent State
In LangGraph, everything revolves around the State. We need a way to track the user's current metrics and the agent's recommendations.
from typing import TypedDict, Annotated, List
from langgraph.graph import StateGraph, END
class AgentState(TypedDict):
cortisol_level: float
sleep_hours: float
current_phase: str # e.g., Follicular, Luteal, or High Stress
recommendations: List[str]
notion_updated: bool
Step 2: Building the "Bio-Analyzer" Node
This node acts as the "brain." It evaluates the raw data from the HealthKit API and decides if an intervention is necessary.
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
llm = ChatOpenAI(model="gpt-4o", temperature=0)
def analyze_health_data(state: AgentState):
cortisol = state['cortisol_level']
sleep = state['sleep_hours']
prompt = f"""
User Data: Cortisol {cortisol} ng/dL, Sleep {sleep} hours.
If Cortisol > 18 or Sleep < 6, trigger a 'High Stress' recovery diet.
Otherwise, maintain 'Standard' nutrition.
Return only the phase name.
"""
response = llm.invoke([HumanMessage(content=prompt)])
return {"current_phase": response.content.strip()}
Step 3: Integrating the Notion SDK
When our agent detects an anomaly, it shouldn't just tell us; it should act. We use the Notion SDK to modify our actual meal plan.
import os
from notion_client import Client
notion = Client(auth=os.environ["NOTION_TOKEN"])
DATABASE_ID = "your_database_id"
def update_notion_plan(state: AgentState):
if state['current_phase'] == "High Stress":
advice = "Increase Magnesium intake. Focus on complex carbs and leafy greens. Avoid caffeine."
notion.pages.create(
parent={"database_id": DATABASE_ID},
properties={
"Name": {"title": [{"text": {"content": "Urgent Bio-Update: Recovery Mode"}}]},
"Advice": {"rich_text": [{"text": {"content": advice}}]},
"Status": {"select": {"name": "High Priority"}}
}
)
return {"notion_updated": True, "recommendations": [advice]}
return {"notion_updated": False}
Step 4: Compiling the Graph
Now, we wire it all together into a stateful graph.
workflow = StateGraph(AgentState)
# Add Nodes
workflow.add_node("analyzer", analyze_health_data)
workflow.add_node("notion_updater", update_notion_plan)
# Define Edges
workflow.set_entry_point("analyzer")
workflow.add_edge("analyzer", "notion_updater")
workflow.add_edge("notion_updater", END)
# Compile
app = workflow.compile()
# Run it!
inputs = {"cortisol_level": 22.5, "sleep_hours": 4.5}
for output in app.stream(inputs):
print(output)
The "Official" Way to Build Production Agents ๐ฅ
While this prototype is a great "Learning in Public" project, building production-grade healthcare or productivity agents requires stricter validation, error handling, and security layers.
For more advanced patterns on handling long-term memory in agents and production-ready LangGraph architectures, I highly recommend checking out the deep dives over at WellAlly Blog. They cover the intersection of AI and wellness in a way thatโs much more scalable than a weekend script!
Conclusion
By combining LangGraph with real-world health telemetry, weโve built more than a scriptโweโve built a digital twin that looks out for our well-being. The future of AI isn't just generating text; it's closing the loop between our physical bodies and our digital tools.
What would you automate next?
- [ ] Syncing workout intensity with glucose levels?
- [ ] Auto-ordering groceries based on hormone cycles?
Let me know in the comments! ๐ ๐๐ป
Top comments (0)