get-recipe-tool / tool.py
CallmeKaito's picture
Update tool.py
923663c verified
from smolagents import Tool
from typing import Optional
class SimpleTool(Tool):
name = "CulinAI -- your AI Recipe Assistant"
description = "Gets a recipe suggestion based on provided ingredients, dietary preference, and your laziness level (1=active chef, 10=super lazy). After finding a recipe, it retrieves detailed recipe information.\nFor dietary restriction, you can select from: none, vegetarian, vegan, gluten free, ketogenic, paleo, pescetarian, whole30, halal, or low fodmap."
inputs = {"ingredients":{"type":"string","description":"A comma-separated string of available ingredients."},"diet":{"type":"string","nullable":True,"description":"Dietary restrictions such as 'vegetarian', 'vegan', or 'gluten free'. Defaults to None."},"laziness":{"type":"integer","nullable":True,"description":"An integer from 1 (active) to 10 (super lazy); higher means recipes with quicker prep."}}
output_type = "string"
def forward(self, ingredients: str, diet: Optional[str] = None, laziness: Optional[int] = 5) -> str:
"""
Gets a recipe suggestion based on provided ingredients, dietary preference,
and your laziness level (1=active chef, 10=super lazy). After finding a recipe,
it retrieves detailed recipe information.
Args:
ingredients: A comma-separated string of available ingredients.
diet: Dietary restrictions such as 'vegetarian', 'vegan', or 'gluten free'. Defaults to None.
laziness: An integer from 1 (active) to 10 (super lazy); higher means recipes with quicker prep.
Returns:
A string with detailed information about the recommended recipe.
"""
import os
import requests
api_key = "0cbb3d6a82f5497e818d1f63dc736218"
if not api_key:
return "Spoonacular API key not set. Please set the SPOONACULAR_API_KEY environment variable."
# Step 1: Search for recipes using the ingredients
base_search_url = "https://api.spoonacular.com/recipes/findByIngredients"
params = {
"ingredients": ingredients,
"number": 1, # We want one suggestion
"ranking": 1,
"apiKey": api_key,
}
# Add diet if provided
if diet:
params["diet"] = diet
# Incorporate the laziness factor: filter by maxReadyTime if needed.
try:
laziness = int(laziness)
except ValueError:
return "Laziness must be an integer from 1 to 10."
if laziness >= 8:
params["maxReadyTime"] = 15 # 15 minutes for super lazy cooks
elif 5 <= laziness < 8:
params["maxReadyTime"] = 30 # 30 minutes for moderately lazy cooks
try:
search_response = requests.get(base_search_url, params=params)
search_response.raise_for_status()
search_data = search_response.json()
except Exception as e:
return f"Error during recipe search: {e}"
if not search_data:
return "No recipes found with these parameters. Try adjusting your ingredients, diet, or laziness level."
# Assume the first result is the best match
recipe = search_data[0]
recipe_id = recipe.get("id")
if not recipe_id:
return "Recipe ID not found in the search result."
# Step 2: Retrieve detailed recipe information using the recipe id
info_url = f"https://api.spoonacular.com/recipes/{recipe_id}/information"
info_params = {
"apiKey": api_key,
}
try:
info_response = requests.get(info_url, params=info_params)
info_response.raise_for_status()
info_data = info_response.json()
except Exception as e:
return f"Error retrieving detailed recipe information: {e}"
# Extract detailed information
title = info_data.get("title", "Untitled Recipe")
ready_time = info_data.get("readyInMinutes", "N/A")
servings = info_data.get("servings", "N/A")
instructions = info_data.get("instructions", "No instructions provided.")
# Extract ingredients list (names only)
ingredients_list = info_data.get("extendedIngredients", [])
ingredients_names = [ing.get("name") for ing in ingredients_list if ing.get("name")]
ingredients_str = ", ".join(ingredients_names) if ingredients_names else "N/A"
# Build the detailed summary message
detailed_info = (
f"Recipe suggestion: {title}\n"
f"Ready in: {ready_time} minutes | Servings: {servings}\n"
f"Ingredients: {ingredients_str}\n\n"
f"Instructions:\n{instructions}"
)
return detailed_info