Build an Autonomous AI Nutritionist: From Blood Sugar Prediction to Instacart Checkout
Source: Dev.to
We’ve all been there: staring at a fridge full of condiments, wondering what to eat that won’t make our energy levels crash by 3 PM. Manual meal planning is exhausting, and calorie counting in apps like MyFitnessPal feels like a second job. What if your computer could do it all for you?
Overview
In this tutorial we build a high‑performance Autonomous AI Nutritionist Agent. This isn’t just a chatbot; it’s an end‑to‑end system that:
- Predicts your nutritional needs based on blood‑sugar trends.
- Checks your pantry inventory.
- Populates your Instacart shopping cart with missing ingredients.
The agent operates as a reasoning loop: it ingests health data, consults historical trends, and executes real‑world actions.
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]
Prerequisites
- Python 3.10+
langchain& OpenAI SDK- Selenium (with a headless Chrome driver)
- Basic GraphQL knowledge (for MyFitnessPal data fetching)
Fetching Recent Macronutrients from MyFitnessPal
Most modern fitness apps expose GraphQL endpoints. The snippet below pulls the last 24 hours of macro data.
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]
Defining LangChain Tools
We use LangChain agents to decide which tool to invoke—checking pantry inventory via the Reclaim API or ordering missing items on 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)
Automating Instacart with Selenium
Instacart does not expose a public “Add to Cart” API, so we simulate the user journey with 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!"
Scaling Considerations
- Rate limits – throttle requests to external APIs.
- Session persistence – reuse authenticated Selenium sessions or store cookies.
- Feedback loops – verify that added items are in stock and confirm with the user.
Further Reading
For production‑grade agent frameworks and security best practices, see the technical deep‑dives on the WellAlly Blog (link: https://wellally.com/blog). The posts cover advanced patterns for health‑tech integrations and LLM orchestration beyond basic tutorials.
What’s Next?
- Fine‑tuning – train a model on your personal glucose responses.
- Voice integration – “Hey AI, I’m feeling light‑headed, fix my dinner.”
- Visual verification – use GPT‑4o to analyze photos of your fridge and confirm inventory.
Got questions about the MyFitnessPal GraphQL schema or Selenium stability? Feel free to leave a comment below!