자율 AI 영양사 구축: 혈당 예측에서 Instacart 체크아웃까지
Source: Dev.to
우리는 모두 그런 경험을 해봤습니다. 양념이 가득 든 냉장고 앞에 서서, 오후 3시까지 에너지 수준이 급락하지 않을 음식을 고민하고 있죠. 수동으로 식단을 짜는 일은 지치게 하고, MyFitnessPal 같은 앱에 칼로리를 입력하는 것은 마치 두 번째 직업을 갖는 듯합니다. 컴퓨터가 이 모든 일을 대신해 준다면 어떨까요?
Source:
개요
이 튜토리얼에서는 고성능 자율 AI 영양사 에이전트를 구축합니다. 이것은 단순한 챗봇이 아니라 다음과 같은 기능을 갖춘 엔드‑투‑엔드 시스템입니다:
- 혈당 추세를 기반으로 영양 요구량을 예측합니다.
- 식료품 저장고 재고를 확인합니다.
- 부족한 재료를 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):
"""
MyFitnessPal에서 지난 24 시간 동안의 매크로 데이터를 가져옵니다.
"""
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은 공개된 “Add to Cart” 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!"
확장 고려 사항
- Rate limits – 외부 API에 대한 요청을 제한합니다.
- Session persistence – 인증된 Selenium 세션을 재사용하거나 쿠키를 저장합니다.
- Feedback loops – 추가된 항목이 재고가 있는지 확인하고 사용자에게 확인합니다.
추가 읽기
프로덕션 수준의 에이전트 프레임워크와 보안 모범 사례에 대해서는 WellAlly Blog(링크: https://wellally.com/blog)의 기술 심층 분석을 참조하십시오. 해당 게시물들은 기본 튜토리얼을 넘어 건강‑테크 통합 및 LLM 오케스트레이션을 위한 고급 패턴을 다룹니다.
다음은 무엇인가요?
- Fine‑tuning – 개인 혈당 반응에 모델을 학습시킵니다.
- Voice integration – “Hey AI, 어지럽고, 저녁을 고쳐줘.”
- Visual verification – GPT‑4o를 사용해 냉장고 사진을 분석하고 재고를 확인합니다.
MyFitnessPal GraphQL 스키마나 Selenium 안정성에 대한 질문이 있나요? 아래에 댓글을 남겨 주세요!