你的 CGM 应该帮你点午餐:使用 LangGraph 构建自主健康代理 🥗🤖

发布: (2026年1月31日 GMT+8 09:30)
5 分钟阅读
原文: Dev.to

I’m happy to translate the article for you, but I need the actual text of the post. Could you please paste the content you’d like translated (excluding any code blocks or URLs you want to keep unchanged)? Once I have the text, I’ll provide a Simplified Chinese translation while preserving the original formatting and markdown.

介绍

我们都有过这样的经历:连续血糖监测仪(CGM)向你发送“血糖偏高”警报,你的大脑立刻进入恐慌模式。该吃东西吗?该吃什么?在血糖飙升的紧张时刻,做出理性、低血糖指数的决定非常困难。

如果你的健康数据不仅仅是提醒你,而是为你采取行动呢?在本教程中,我们将使用 LangGraph、OpenAI 函数调用和 Dexcom API 构建一个 健康管家。该 AI 代理实时监测血糖水平,并在检测到血糖峰值或骤降时,自动与外卖平台 API(如美团或饿了么)交互,推荐并下单低 GI(血糖生成指数)餐食。

架构图

graph TD
    A[Start: Dexcom Monitor] --> B{Glucose Stable?}
    B -- Yes --> C[Wait 5 Mins]
    C --> A
    B -- No: Spike/Crash --> D[Analyze Nutritional Needs]
    D --> E[OpenAI Function Calling: Search Low‑GI Meals]
    E --> F[Fetch Meituan/Ele.me Options]
    F --> G[Propose Order to User]
    G -- Approved --> H[Execute Delivery API]
    G -- Denied --> A
    H --> I[Log Event & Monitor Recovery]
    I --> A

先决条件

  • Node.js (v18+)
  • LangChain & LangGraph SDKs (@langchain/langgraph, @langchain/openai)
  • Dexcom 开发者账户(沙盒 API 访问)
  • OpenAI API 密钥(使用 GPT‑4o 以获得最佳推理)

定义代理状态

import { StateGraph, Annotation } from "@langchain/langgraph";

// Define our state schema
const AgentState = Annotation.Root({
  glucoseLevel: Annotation(),
  trend: Annotation(), // 'rising', 'falling', 'stable'
  recommendations: Annotation(),
  orderPlaced: Annotation(),
  userAlerted: Annotation(),
});

状态是唯一可信来源:它跟踪当前的血糖值、其趋势以及任何推荐的食物项目。

Dexcom 获取节点

async function checkGlucoseNode(state) {
  console.log("Checking CGM data... 🩸");

  // Real-world: const response = await fetch('https://api.dexcom.com/v3/users/self/egvs/...');
  // Mocking a "Spike" scenario:
  const mockGlucose = 185;
  const mockTrend = "risingFast";

  return {
    glucoseLevel: mockGlucose,
    trend: mockTrend,
  };
}

此节点模拟 OAuth 流程,并返回血糖读数和趋势。

食品搜索工具(OpenAI函数调用)

import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { z } from "zod";

const foodSearchTool = tool(
  async ({ query, maxCalories }) => {
    // Logic to call Meituan/Ele.me/UberEats API
    return `Found: Grilled Chicken Salad, Quinoa Bowl (Max ${maxCalories} kcal)`;
  },
  {
    name: "search_delivery_food",
    description: "Searches for healthy food options based on nutritional needs.",
    schema: z.object({
      query: z.string(),
      maxCalories: z.number(),
    }),
  }
);

const model = new ChatOpenAI({ modelName: "gpt-4o" }).bindTools([foodSearchTool]);

该工具使大型语言模型能够从外送服务请求低GI的餐食选项。

构建工作流

const workflow = new StateGraph(AgentState)
  .addNode("monitor", checkGlucoseNode)
  .addNode("analyzer", async (state) => {
    const response = await model.invoke([
      ["system", "You are a medical nutrition assistant. Suggest a low-GI meal."],
      ["user", `My glucose is ${state.glucoseLevel} and ${state.trend}. Find me a meal.`],
    ]);
    return { recommendations: [response] };
  })
  .addEdge("__start__", "monitor")
  .addConditionalEdges("monitor", (state) => {
    if (state.glucoseLevel > 160 || state.glucoseLevel < 70) return "analyzer";
    return "monitor";
  })
  .addEdge("analyzer", "monitor"); // Simplified loop

const app = workflow.compile();

该图从 monitor 节点开始,当血糖超出范围时有条件地路由到 analyzer,随后再回到 monitor

生产考虑

虽然此概念验证展示了核心思路,但要实现生产级健康代理,需要解决以下问题:

  • 可靠的错误处理和重试机制
  • 符合 HIPAA 标准的数据处理和存储
  • 用于个性化营养建议的检索增强生成(RAG)
  • 具有人机交互(HITL)模式的安全工具调用
  • 用于实时响应的低延迟边缘部署

如需深入讨论这些主题,请参阅 WellAlly 技术博客 上的工程指南(搜索 “stateful AI agents in healthcare”)。

下一步

  • 添加一个 Human‑in‑the‑Loop 节点,在调用 payment API 之前需要生物特征确认。
  • 实现一个 feedback loop,使 agent 学习哪些 meals 最能有效稳定 glucose levels
  • 将数据源扩展到包括多模态健康输入(例如,vision + CGM)。

祝编码愉快,保持健康! 🥑💻

Back to Blog

相关文章

阅读更多 »