构建 AI 健康代理:使用 LangGraph 和实时 CGM 数据自动化您的饮食
Source: Dev.to
管理代谢健康不应像一份全职工作。随着 AI Health Agents 和 Continuous Glucose Monitoring (CGM) 的兴起,我们终于可以从被动追踪转向主动干预。想象一下,一个能够实时监测你的 Dexcom 数据的代理,当检测到血糖控制不佳时,会自动重新生成你的每周购物清单。
在本教程中,我们将探讨如何使用 LangGraph、OpenAI Function Calling 和 Supabase 构建一个 Agentic Dietitian。我们将利用 LLM orchestration 和有状态的工作流,弥合生物信号与可执行饮食调整之间的鸿沟。阅读完本指南后,你将了解如何实现一个闭环系统,将生理数据转化为个性化的营养方案。
架构:闭环健康反馈系统
与普通聊天机器人不同,具备代理能力的系统需要保持状态并根据不断变化的数据做出决策。我们使用 LangGraph 来管理监控、分析和执行的循环。
graph TD
A[Dexcom API: Real‑time Glucose] --> B{Health Monitor Node}
B -- Glucose Spike Detected --> C[Dietary Analyst Node]
B -- Glucose Stable --> D[Log Activity]
C --> E[OpenAI Function Calling: Modify Grocery List]
E --> F[Supabase: Persist Changes]
F --> G[Notification to User]
G --> A
前置条件
- LangGraph – 用于构建有状态的代理工作流。
- OpenAI SDK – 用于推理引擎(GPT‑4o)。
- Supabase – 用于存储用户资料和购物清单。
- Dexcom Developer API – 用于访问 CGM 数据(我们将在演示中对其进行模拟)。
第一步:定义代理状态
在 LangGraph 中,State 是一个共享的模式,它会随着在不同节点之间的传递而演变。我们的代理需要跟踪当前的血糖水平、用户的健康目标以及待处理的购物清单更改。
from typing import TypedDict, List
from langgraph.graph import StateGraph, END
class AgentState(TypedDict):
glucose_level: float
trend: str # e.g., "rising", "falling", "stable"
current_grocery_list: List[str]
health_summary: str
action_taken: bool
步骤 2:集成实时数据(Dexcom)
我们定义一个工具来获取最新的葡萄糖读数。在生产环境中,您需要使用 OAuth2 连接 Dexcom API。
def fetch_glucose_data(user_id: str):
# Mocking Dexcom API response
# In reality: requests.get(DEXCOM_URL, headers=auth_headers)
return {
"value": 185.5, # mg/dL (a bit high!)
"trend": "rising_fast"
}
第三步:AI 推理与函数调用
当代理检测到血糖峰值时,它不应仅仅“聊天”——而应“行动”。我们使用 OpenAI 的函数调用,让 LLM 与我们的 Supabase 数据库交互,以移除高血糖指数食物并建议更好的替代品。
import openai
from typing import List
def modify_grocery_list(items_to_remove: List[str], items_to_add: List[str]) -> str:
"""
Updates the user's grocery list in Supabase to improve glycemic response.
"""
# Logic to update Supabase table goes here
print(f"Removing: {items_to_remove}, Adding: {items_to_add}")
return "Grocery list updated successfully."
# Define the tool for the LLM
tools = [{
"name": "modify_grocery_list",
"description": "Adjust the grocery list based on blood sugar trends",
"parameters": {
"type": "object",
"properties": {
"items_to_remove": {
"type": "array",
"items": {"type": "string"},
"description": "Foods to remove from the list"
},
"items_to_add": {
"type": "array",
"items": {"type": "string"},
"description": "Foods to add to the list"
}
},
"required": ["items_to_remove", "items_to_add"]
}
}]
第 4 步:构建 LangGraph
现在,让我们把所有部件连接起来。图会根据血糖趋势决定是否触发饮食调整。
workflow = StateGraph(AgentState)
def monitor_glucose_node(state: AgentState):
data = fetch_glucose_data("user_123")
return {"glucose_level": data["value"], "trend": data["trend"]}
def dietitian_node(state: AgentState):
if state["glucose_level"] > 180:
# Call LLM to decide what to swap in the grocery list
# Example: "Since the user is spiking, swap white bread for quinoa."
return {
"health_summary": "High glucose detected. Adjusting list.",
"action_taken": True
}
return {"action_taken": False}
workflow.add_node("monitor", monitor_glucose_node)
workflow.add_node("dietitian", dietitian_node)
workflow.set_entry_point("monitor")
workflow.add_edge("monitor", "dietitian")
workflow.add_edge("dietitian", END)
app = workflow.compile()
“官方”方法:提升你的代理
构建原型很容易,但要打造符合 HIPAA 标准、可投入生产的健康代理则是另一回事。你需要处理诸如传感器错误、数据缺口和用户偏好等边缘情况。
想获取更多面向生产的示例和构建自主代理的高级模式,请查看 WellAlly Tech Blog 的技术深度解析。他们涵盖了从 RAG 优化到远超基础教程的复杂代理工作流。 🥑
结论:主动健康的未来
通过将 LangGraph 用于工作流管理、OpenAI 用于智能,我们已经从一个简单的“追踪器”升级为一个“飞行员”。这个代理不仅会告诉你血糖偏高,还会主动确保你的厨房在下周拥有更好的食材选择。
接下来会做什么?
- 多模态输入 – 使用 GPT‑4o 分析你的餐食照片,并将特定食物与血糖峰值关联起来。
- 长期记忆 – 将数月的数据存储在 Supabase 中,使代理能够学习到燕麦粥(尤其是)会让你血糖升高,即使它对大多数人来说是“健康”的。
- 用户偏好处理 – 将饮食限制、文化食物和预算约束纳入决策循环。
通过这些扩展,你的代理营养师可以发展为真正个性化的健康伴侣。祝开发愉快!
AI 健康社区
您正在 AI 健康领域构建吗?在下方留下评论,或分享您对代理工作流如何改变患者结果的看法!🚀💻
关注我,获取更多关于 AI、代理和现代网页开发的“公开学习”教程。