构建自主 AI 营养师:从血糖预测到 Instacart 结账

发布: (2026年1月19日 GMT+8 08:45)
5 min read
原文: Dev.to

Source: Dev.to

我们都经历过这种情形:站在满是调味品的冰箱前,思考该吃什么才能避免下午三点能量骤降。手动制定饮食计划令人筋疲力尽,而在 MyFitnessPal 等应用中记录卡路里又像是第二份工作。如果你的电脑能把这些全都搞定,那该多好?

概览

在本教程中,我们将构建一个高性能的 自主 AI 营养师代理。这不仅仅是一个聊天机器人;它是一个端到端的系统,能够:

  1. 基于血糖趋势预测您的营养需求。
  2. 检查您的储藏室库存。
  3. 将缺少的食材填入您的 Instacart 购物车。

该代理以 推理循环 的方式运行:它摄取健康数据,参考历史趋势,并执行真实世界的操作。

graph TD
    A[User Input/Glucose Monitor] --> B{AI Agent Brain}
    B --> C[MyFitnessPal API – GraphQL]
    B --> D[Reclaim API – Inventory Check]
    C --> E[Meal Plan Generation]
    D --> E
    E --> F[Selenium Executor]
    F --> G[Instacart Shopping Cart]
    G --> H[User Notification]

前置条件

  • Python 3.10+
  • langchain 与 OpenAI SDK
  • Selenium(配合无头 Chrome 驱动)
  • 基础 GraphQL 知识(用于获取 MyFitnessPal 数据)

获取 MyFitnessPal 最近的宏量营养素

大多数现代健身应用都公开 GraphQL 接口。下面的代码片段获取最近 24 小时的宏量营养数据。

import requests

def get_mfp_macros(user_id: str, auth_token: str):
    """
    Fetches the last 24 hours of macro data from MyFitnessPal.
    """
    url = "https://www.myfitnesspal.com/graphql"
    headers = {"Authorization": f"Bearer {auth_token}"}

    query = """
    query GetDailyNutrients($userId: ID!) {
        user(id: $userId) {
            dailySummary(last: 1) {
                calories
                carbs
                protein
                fat
            }
        }
    }
    """

    response = requests.post(
        url,
        json={"query": query, "variables": {"userId": user_id}},
        headers=headers,
    )
    return response.json()["data"]["user"]["dailySummary"][0]

定义 LangChain 工具

我们使用 LangChain 代理来决定调用哪个工具——通过 Reclaim API 检查储藏室库存或在 Instacart 上订购缺少的物品。

from langchain.agents import initialize_agent, Tool, AgentType
from langchain.chat_models import ChatOpenAI

# Mock inventory check (replace with real Reclaim API call)
def inventory_check(_: str) -> str:
    return "Milk: 0, Eggs: 2, Chicken: 500g"

# Selenium executor will be defined later
def selenium_cart_executor(items_list):
    # placeholder – actual implementation follows
    pass

tools = [
    Tool(
        name="InventoryCheck",
        func=inventory_check,
        description="Checks the current food inventory in the user's kitchen."
    ),
    Tool(
        name="InstacartOrder",
        func=selenium_cart_executor,
        description="Adds specific ingredients to the Instacart shopping cart."
    ),
]

llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)

agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
)

prompt = (
    "Based on my low blood sugar prediction, I need a high‑protein meal. "
    "Check my inventory and order what's missing for a Grilled Chicken Salad."
)
agent.run(prompt)

使用 Selenium 自动化 Instacart

Instacart 并未公开 “添加到购物车” API,因此我们使用 Selenium 模拟用户流程。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

def selenium_cart_executor(items_list):
    """
    Automates the browser to add items to Instacart.
    """
    driver = webdriver.Chrome()
    driver.get("https://www.instacart.com")

    # TODO: Add login flow here (e.g., using saved cookies or credentials)

    for item in items_list:
        search_bar = driver.find_element(By.ID, "search-bar-input")
        search_bar.clear()
        search_bar.send_keys(item)
        search_bar.send_keys(Keys.ENTER)

        # Click 'Add to Cart' on the first result
        add_button = driver.find_element(
            By.XPATH, "//button[@aria-label='Add to Cart']"
        )
        add_button.click()

    driver.quit()
    return "Successfully added items to your Instacart cart!"

可扩展性考虑

  • 速率限制 – 对外部 API 的请求进行限流。
  • 会话持久化 – 重用已认证的 Selenium 会话或存储 Cookie。
  • 反馈循环 – 验证已添加的商品是否有库存,并向用户确认。

Further Reading

对于生产级别的代理框架和安全最佳实践,请参阅 WellAlly 博客(链接: https://wellally.com/blog)。这些文章涵盖了健康技术集成和 LLM 编排的高级模式,超出基础教程的范围。

接下来是什么?

  • Fine‑tuning – 在您的个人血糖反应上训练模型。
  • Voice integration – “Hey AI,我感到头晕,请帮我改晚餐。”
  • Visual verification – 使用 GPT‑4o 分析您冰箱的照片并确认库存。

如果您对 MyFitnessPal GraphQL 架构或 Selenium 稳定性有任何疑问,请随时在下方留言!

Back to Blog

相关文章

阅读更多 »

Rapg:基于 TUI 的密钥管理器

我们都有这种经历。你加入一个新项目,首先听到的就是:“在 Slack 的置顶消息里查找 .env 文件”。或者你有多个 .env …

技术是赋能者,而非救世主

为什么思考的清晰度比你使用的工具更重要。Technology 常被视为一种魔法开关——只要打开,它就能让一切改善。新的 software,...

踏入 agentic coding

使用 Copilot Agent 的经验 我主要使用 GitHub Copilot 进行 inline edits 和 PR reviews,让我的大脑完成大部分思考。最近我决定 t...