Build Your Own AI Nutritionist: LLM, RAG, and Personalized Nutrition
In-depth discussion
Technical, yet accessible
0 0 679
This article guides readers through creating a personalized AI nutritionist using advanced AI techniques like LLMs, function calling, and RAG. It details the technology stack, environment setup, and implementation of specialized nutrition functions, culminating in a functional assistant capable of answering nutrition queries, calculating BMI, and providing personalized dietary advice.
main points
unique insights
practical applications
key topics
key insights
learning outcomes
• main points
1
Comprehensive guide on building an AI nutrition assistant
2
Integration of advanced AI techniques for personalized nutrition advice
3
Practical implementation with real-world applications and examples
• unique insights
1
Combines LLMs, function calling, and RAG for enhanced accuracy in nutrition guidance
2
Demonstrates how to create a searchable nutrition knowledge base using vector embeddings
• practical applications
The article provides a step-by-step approach to building a functional AI nutritionist, making nutrition science accessible and personalized for users.
• key topics
1
Large Language Models (LLMs)
2
Function Calling in AI
3
Retrieval-Augmented Generation (RAG)
• key insights
1
Practical application of AI in personal health management
2
Detailed implementation of nutrition functions for accurate calculations
3
Innovative use of AI techniques to enhance user interaction with nutrition data
• learning outcomes
1
Understand how to integrate LLMs with function calling for practical applications.
2
Learn to build a nutrition knowledge base using vector embeddings.
3
Gain insights into creating personalized AI assistants for health and nutrition.
“ Introduction: The Need for a Personal AI Nutritionist
In today's hectic environment, maintaining a balanced diet is increasingly difficult. Conflicting nutrition advice and fad diets often leave individuals confused. An AI Personal Nutritionist, available 24/7, can answer specific nutrition questions, calculate nutritional needs, and provide personalized recommendations. This is now possible with advances in artificial intelligence, particularly large language models (LLMs) and retrieval techniques. This article guides you through creating your own AI Personal Nutritionist Assistant, combining Google's Gemini LLM with specialized nutrition functions and a real nutrition data knowledge base. The assistant can answer questions about food nutrition, calculate BMI, estimate daily calorie needs, recommend foods based on criteria, and provide evidence-based nutrition advice.
“ Understanding the Technology Stack: LLMs, Function Calling, and RAG
Our AI Personal Nutritionist Assistant is powered by three key technologies: Large Language Models (LLMs) like Google's Gemini 1.5 Pro, Function Calling, and Retrieval-Augmented Generation (RAG). LLMs understand and generate human-like text, excelling at natural language queries about nutrition. Function Calling allows the LLM to use specialized calculations like BMI or calorie needs. RAG grounds the assistant's responses in factual nutrition data, retrieving relevant information from a nutrition database. These technologies work together to understand user queries, retrieve nutrition facts, and handle precise calculations.
“ Setting Up Your Development Environment
To set up the development environment, install the necessary libraries and configure API access. Use the following commands:
```bash
!pip install -U -q "google-genai==1.7.0"
!pip install chromadb
```
These commands install the Google Generative AI Python SDK and ChromaDB for the vector database. Next, set up access to the Google Gemini API:
```python
import google.generativeai as genai
import os
# Set up the API key
GOOGLE_API_KEY = "YOUR_API_KEY" # Replace with your actual API key
genai.configure(api_key=GOOGLE_API_KEY)
```
Replace `YOUR_API_KEY` with your actual Gemini API key from the Google AI Studio website.
“ Building the Nutrition Knowledge Base
Build the nutrition knowledge base by loading a comprehensive dataset of nutrition facts using pandas:
```python
import pandas as pd
import numpy as np
# Load nutrition data
nutrition_data = pd.read_csv('/kaggle/input/nutrition-facts-for-3636-foods/nutrition_facts.csv')
nutrition_data.head()
```
This dataset contains detailed nutrition information for over 3,600 foods. Convert this data into vector embeddings using ChromaDB:
```python
# Create embeddings for the nutrition data
from chromadb.utils import embedding_functions
import chromadb
# Initialize ChromaDB client
chroma_client = chromadb.Client()
# Create a collection for nutrition data
nutrition_collection = chroma_client.create_collection(
name="nutrition_facts",
embedding_function=embedding_functions.DefaultEmbeddingFunction()
)
# Prepare data for embedding
for i, row in nutrition_data.iterrows():
# Create a document with nutrition information
document = f"Food: {row['name']}, Calories: {row['calories']}, Protein: {row['protein_g']}g, Fat: {row['fat_g']}g, Carbs: {row['carbohydrate_g']}g"
# Add to collection with unique ID
nutrition_collection.add(
documents=[document],
ids=[f"food_{i}"]
)
```
This code creates a ChromaDB collection and populates it with nutrition data, allowing for semantic search.
“ Creating Specialized Nutrition Functions: BMI and Calorie Calculation
Implement two essential nutrition functions: BMI calculation and daily calorie needs estimation:
```python
def calculate_bmi(weight_kg, height_cm):
"""Calculate BMI given weight in kg and height in cm."""
height_m = height_cm / 100
bmi = weight_kg / (height_m * height_m)
# Determine BMI category
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal weight"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
return {
"bmi": round(bmi, 1),
"category": category
}
def calculate_calorie_needs(weight_kg, height_cm, age, gender, activity_level):
"""Calculate daily calorie needs based on Harris-Benedict equation."""
# Base metabolic rate (BMR)
if gender.lower() == "male":
bmr = 88.362 + (13.397 * weight_kg) + (4.799 * height_cm) - (5.677 * age)
else: # female
bmr = 447.593 + (9.247 * weight_kg) + (3.098 * height_cm) - (4.330 * age)
# Activity multipliers
activity_multipliers = {
"sedentary": 1.2, # Little or no exercise
"light": 1.375, # Light exercise 1-3 days/week
"moderate": 1.55, # Moderate exercise 3-5 days/week
"active": 1.725, # Hard exercise 6-7 days/week
"very_active": 1.9 # Very hard exercise & physical job or training twice a day
}
# Calculate total daily energy expenditure (TDEE)
multiplier = activity_multipliers.get(activity_level.lower(), 1.2)
tdee = bmr * multiplier
return {
"bmr": round(bmr),
"daily_calories": round(tdee),
"weight_loss": round(tdee - 500), # 500 calorie deficit
"weight_gain": round(tdee + 500) # 500 calorie surplus
}
```
The `calculate_bmi` function implements the Body Mass Index formula, and the `calculate_calorie_needs` function uses the Harris-Benedict equation.
“ Implementing Function Calling with Gemini
Define function schemas for Gemini to use these functions:
```python
nutrition_functions = [
{
"name": "calculate_bmi",
"description": "Calculate BMI (Body Mass Index) and determine weight category",
"parameters": {
"type": "object",
"properties": {
"weight_kg": {
"type": "number",
"description": "Weight in kilograms"
},
"height_cm": {
"type": "number",
"description": "Height in centimeters"
}
},
"required": ["weight_kg", "height_cm"]
}
},
{
"name": "calculate_calorie_needs",
"description": "Calculate daily calorie needs based on personal stats",
"parameters": {
"type": "object",
"properties": {
"weight_kg": {
"type": "number",
"description": "Weight in kilograms"
},
"height_cm": {
"type": "number",
"description": "Height in centimeters"
},
"age": {
"type": "integer",
"description": "Age in years"
},
"gender": {
"type": "string",
"description": "Gender (male or female)"
},
"activity_level": {
"type": "string",
"description": "Activity level (sedentary, light, moderate, active, very_active)"
}
},
"required": ["weight_kg", "height_cm", "age", "gender", "activity_level"]
}
}
]
```
These schemas define the name, description, and parameters for each function, allowing the LLM to determine when and how to use them.
“ Building the RAG System for Accurate Nutrition Data
The Retrieval-Augmented Generation (RAG) component ensures responses about nutrition facts are grounded in the database. Retrieve relevant entries from the nutrition database and provide them as context to the LLM:
```python
def nutrition_assistant(query):
"""Process a nutrition-related query using RAG and function calling."""
# Step 1: Retrieve relevant nutrition information using RAG
results = nutrition_collection.query(
query_texts=[query],
n_results=5
)
# Format the retrieved information
context = "\n".join(results["documents"][0])
```
This code uses ChromaDB's query function to find the top 5 most relevant entries for the user's query.
“ Putting It All Together: The Nutrition Assistant Function
Combine all components into the main assistant function:
```python
def nutrition_assistant(query):
"""Process a nutrition-related query using RAG and function calling."""
# Step 1: Retrieve relevant nutrition information using RAG
results = nutrition_collection.query(
query_texts=[query],
n_results=5
)
# Format the retrieved information
context = "\n".join(results["documents"][0])
# Step 2: Set up the model with function calling
model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
generation_config={"temperature": 0.2}
)
# Step 3: Create the prompt with context and query
prompt = f"""You are a helpful nutrition assistant. Use the following nutrition information to help answer the query.
NUTRITION INFORMATION:
{context}
USER QUERY: {query}
If the user is asking about BMI or calorie calculations, use the appropriate function.
For other nutrition questions, provide helpful advice based on the context and your knowledge.
"""
# Step 4: Generate response with potential function calls
response = model.generate_content(
prompt,
tools=nutrition_functions
)
# Step 5: Process function calls if present
if hasattr(response, 'candidates') and len(response.candidates) > 0:
candidate = response.candidates[0]
if hasattr(candidate, 'content') and hasattr(candidate.content, 'parts'):
for part in candidate.content.parts:
if hasattr(part, 'function_call'):
function_call = part.function_call
function_name = function_call.name
function_args = function_call.args
# Execute the appropriate function
if function_name == "calculate_bmi":
result = calculate_bmi(
function_args["weight_kg"],
function_args["height_cm"]
)
elif function_name == "calculate_calorie_needs":
result = calculate_calorie_needs(
function_args["weight_kg"],
function_args["height_cm"],
function_args["age"],
function_args["gender"],
function_args["activity_level"]
)
# Generate a new response with the function result
final_prompt = f"""You are a helpful nutrition assistant. A user asked: "{query}"
You called the function {function_name} which returned this result:
{result}
Please provide a helpful, conversational response that explains these results and gives appropriate nutrition advice.
Include specific food recommendations based on the nutrition information if relevant.
"""
final_response = model.generate_content(final_prompt)
return final_response.text
# If no function call was made, return the original response
return response.text
```
This function retrieves nutrition information, sets up the Gemini model, creates a prompt, generates a response, and processes function calls if needed.
“ Testing with Real-World Queries
Test the AI Personal Nutritionist with real-world queries:
```python
test_queries = [
"What's the nutritional value of an apple?",
"Can you calculate my BMI? I'm 70kg and 175cm tall.",
"How many calories should I eat? I'm a 30-year-old male, 80kg, 180cm, and moderately active.",
"What are some high-protein foods for building muscle?",
"Can you suggest a meal plan for weight loss?"
]
for query in test_queries:
print(f"\nQuery: {query}")
print("-" * 50)
response = nutrition_assistant(query)
print(response)
print("=" * 80)
```
These examples demonstrate the versatility of the AI Personal Nutritionist, handling factual queries, performing calculations, and providing personalized recommendations.
“ Future Enhancements and Conclusion
Potential enhancements include expanding the nutrition database, improving the accuracy of calorie estimations, adding support for more complex dietary requirements, and integrating with wearable devices. The AI Personal Nutritionist Assistant combines LLMs, function calling, and RAG to provide personalized nutrition guidance. This system can answer nutrition questions, calculate BMI and calorie needs, and provide personalized recommendations, showcasing the potential of AI in personal health.
We use cookies that are essential for our site to work. To improve our site, we would like to use additional cookies to help us understand how visitors use it, measure traffic to our site from social media platforms and to personalise your experience. Some of the cookies that we use are provided by third parties. To accept all cookies click ‘Accept’. To reject all optional cookies click ‘Reject’.
Comment(0)