과도한 훈련 중단: LangGraph와 WHOOP으로 Bio-Hacker Agent 구축
Source: Dev.to
우리는 모두 그런 경험을 해봤습니다. 캘린더에 **“무거운 하체 운동일”**이 잡혀 있지만, 일어나면 마치 트럭에 치인 듯한 느낌이 듭니다. 심박 변동성(HRV)은 바닥에 깔려 있고 회복 점수는 겨우 **14 %**에 불과합니다. 전통적으로는 (부상의 위험을 감수하면서) 억지로 진행하거나 수동으로 일정을 조정하곤 했죠.
하지만 우리는 개발자입니다. 수동으로 일을 하지 않죠.
이번 튜토리얼에서는 바이오‑해커 에이전트를 구축합니다 – 다음을 자동으로 수행하는 시스템:
- WHOOP API를 통해 바이오메트릭을 모니터링합니다.
- 회복 지표가 임계값 이하로 떨어지면 Google Calendar를 재작성하고 맞춤형 저강도 영양 계획을 제안합니다.
튜토리얼을 마치면 웨어러블 IoT 데이터와 실행 가능한 AI 의사결정을 최첨단 스택을 사용해 연결하는 방법을 이해하게 됩니다:
- Python 3.10+
- LangGraph (상태 머신 오케스트레이션)
- Pydantic‑AI (스키마 기반 LLM 출력)
- Google Calendar API
- WHOOP Recovery API
데이터 흐름 개요
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
사전 요구 사항
| 항목 | 필요한 이유 |
|---|---|
| WHOOP Developer Account | Recovery API에 접근 |
| Google Cloud Console (Calendar API enabled) | 캘린더 이벤트를 프로그래밍 방식으로 업데이트 |
| Python 3.10+ | 최신 언어 기능 |
langgraph, pydantic-ai, google-api-python-client | 에이전트를 위한 핵심 라이브러리 |
1️⃣ Pydantic으로 에이전트의 “뇌” 정의
from pydantic import BaseModel, Field
from typing import List, Optional
class RecoveryAction(BaseModel):
"""Schema for the agent’s decision output."""
is_pivot_needed: bool = Field(
description="True if HRV is below 50 % of the 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 day"
)
2️⃣ LangGraph로 의사결정 그래프 구축
from langgraph.graph import StateGraph, END
from typing import TypedDict, List
# ----------------------------------------------------------------------
# State definition (typed dict for static checking)
# ----------------------------------------------------------------------
class AgentState(TypedDict):
hrv_score: int
recovery_percent: int
calendar_events: List[str]
action_plan: RecoveryAction
# ----------------------------------------------------------------------
# Node: fetch biometrics from WHOOP (simulated here)
# ----------------------------------------------------------------------
def check_biometrics(state: AgentState):
# Real implementation would call WHOOP API
# Simulating a “Red Recovery” day:
return {"hrv_score": 35, "recovery_percent": 22}
# ----------------------------------------------------------------------
# Node: analyze metrics and decide whether to pivot
# ----------------------------------------------------------------------
def analyze_and_pivot(state: AgentState):
# LLM (e.g., GPT‑4o) would normally generate this decision
if state["recovery_percent"] < 30:
# Example pivot decision
return {
"is_pivot_needed": True,
"new_workout_type": "Yoga",
"reasoning": "HRV below threshold; recommend low‑intensity activity.",
"suggested_calories": 1800,
}
else:
return {
"is_pivot_needed": False,
"new_workout_type": None,
"reasoning": "Metrics within normal range.",
"suggested_calories": 2500,
}
# ----------------------------------------------------------------------
# Assemble the graph
# ----------------------------------------------------------------------
graph = StateGraph(AgentState)
graph.add_node("fetch", check_biometrics)
graph.add_node("decide", analyze_and_pivot)
graph.set_entry_point("fetch")
graph.add_edge("fetch", "decide")
graph.add_edge("decide", END)
app = graph.compile()
생산 팁: OAuth 토큰 갱신, 오류 재시도 처리를 하고, 사용자 프라이버시를 존중하세요 (PHI를 저장한다면 HIPAA를 준수).
4️⃣ 회복 중심 식단 만들기
def generate_recipe(action: RecoveryAction):
prompt = (
f"Create a meal plan for {action.suggested_calories} calories "
f"focused on anti‑inflammatory ingredients for someone with low HRV."
)
# Call your LLM provider here (OpenAI, Anthropic, etc.)
# response = client.chat.completions.create(...)
print("Recipe generated for recovery day!")
5️⃣ Next Steps & Extensions
- Slack / 푸시 알림 – 일어나자마자 바로 알림을 받으세요.
- MyFitnessPal 연동 – 매크로 목표를 자동으로 기록합니다.
- 수면 데이터 분석 – WHOOP 수면 단계 데이터를 활용해 보다 풍부한 결정을 내립니다.
Further Reading
프로덕션 급 건강‑테크 에이전트에 대해 더 깊이 파고들고 싶다면 WellAlly Blog를 참고하세요 – 최고 수준의 장수 스타트업에서 사용하는 아키텍처 청사진을 다룹니다.
행복한 해킹 되시고, 회복이 언제나 최적이길 바랍니다!
아래에 댓글을 남기거나 직접 만든 바이오‑해킹 스크립트를 공유해 주세요! 그리고 AI‑구동 웰니스의 미래에 대한 더 많은 인사이트를 보려면 wellally.tech/blog 방문을 잊지 마세요.