Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 9 additions & 19 deletions backend/app/api/routes.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,41 @@
import uuid
from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel, Field
from typing import List, Optional
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.models.recipe import Recipe
from app.models.recipe import RecipeRequest, RecipeSuggestions
from app.services.recipe_service import RecipeService, LLMConfigurationError, RecipeGenerationError
from app.core.database import get_db
from app.services.database_service import DatabaseService

router = APIRouter()

class IngredientRequest(BaseModel):
ingredients: List[str] = Field(min_length=1, max_length=30)
dietary_preferences: Optional[List[str]] = None
max_cooking_time: Optional[int] = Field(default=None, gt=0, le=600)
allow_external_ingredients: bool = False

class UserCreateResponse(BaseModel):
user_id: uuid.UUID
message: str

def get_recipe_service(db: Session = Depends(get_db)) -> RecipeService:
return RecipeService(db)

@router.post("/recipes/recommend", response_model=Recipe)
async def recommend_recipe(
request: IngredientRequest,
@router.post("/recipes/recommend", response_model=RecipeSuggestions)
async def recommend_recipes(
request: RecipeRequest,
recipe_service: RecipeService = Depends(get_recipe_service)
):
"""
Get recipe recommendations based on available ingredients
Suggest one or more recipes based on available ingredients and filters
"""
ingredients = [i.strip().lower() for i in request.ingredients if i.strip()]
if not ingredients:
raise HTTPException(status_code=422, detail="Please provide at least one ingredient.")
request = request.model_copy(update={"ingredients": ingredients})

try:
return await recipe_service.get_recipe_recommendation(
ingredients=ingredients,
dietary_preferences=request.dietary_preferences,
max_cooking_time=request.max_cooking_time,
allow_external_ingredients=request.allow_external_ingredients
)
recipes = await recipe_service.get_recipe_suggestions(request)
except LLMConfigurationError as e:
raise HTTPException(status_code=503, detail=str(e))
except RecipeGenerationError as e:
raise HTTPException(status_code=502, detail=str(e))
return RecipeSuggestions(recipes=recipes)

@router.post("/users/create", response_model=UserCreateResponse)
async def create_user(db: Session = Depends(get_db)):
Expand Down
9 changes: 7 additions & 2 deletions backend/app/models/database_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,17 @@ class Recipe(Base):

id: Mapped[int] = id_column()
title: Mapped[str] = mapped_column(String(300))
description: Mapped[Optional[str]] = mapped_column(Text)
servings: Mapped[Optional[int]]
cooking_time_minutes: Mapped[Optional[int]]
difficulty: Mapped[Optional[str]] = mapped_column(String(20))
# Ordered list of instruction strings; always read together with the recipe
steps: Mapped[list[str]] = mapped_column(JSONB, default=list)
source: Mapped[str] = mapped_column(String(20))
# The LLM call that generated this recipe, if any
llm_request_id: Mapped[Optional[int]] = mapped_column(
BigInteger, ForeignKey("llm_requests.id", ondelete="SET NULL"), index=True
)
created_at: Mapped[datetime] = created_at_column()

ingredients: Mapped[list["RecipeIngredient"]] = relationship(
Expand Down Expand Up @@ -110,15 +115,15 @@ class LLMRequest(Base):

id: Mapped[int] = id_column(BigInteger)
user_id: Mapped[Optional[uuid.UUID]] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), index=True)
# What the call was for, e.g. "recipe" or "shopping_list"
# What the call was for, e.g. "recipe_suggestions"
operation: Mapped[str] = mapped_column(String(50))
model: Mapped[str] = mapped_column(String(100))
input: Mapped[dict[str, Any]] = mapped_column(JSONB)
latency_ms: Mapped[int]
input_tokens: Mapped[Optional[int]]
output_tokens: Mapped[Optional[int]]
error: Mapped[Optional[str]] = mapped_column(Text)
recipe_id: Mapped[Optional[int]] = mapped_column(ForeignKey("recipes.id", ondelete="SET NULL"))
created_at: Mapped[datetime] = created_at_column()

user: Mapped[Optional[User]] = relationship(back_populates="llm_requests")
recipes: Mapped[list[Recipe]] = relationship()
81 changes: 42 additions & 39 deletions backend/app/models/recipe.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,52 @@
from pydantic import BaseModel, ConfigDict, Field
from enum import Enum
from typing import List, Optional

class GeneratedRecipe(BaseModel):
"""Recipe fields produced by the LLM."""
from pydantic import BaseModel, Field


class MealType(str, Enum):
breakfast = "breakfast"
lunch = "lunch"
dinner = "dinner"
snack = "snack"
dessert = "dessert"


class Difficulty(str, Enum):
easy = "easy"
medium = "medium"
hard = "hard"


class RecipeRequest(BaseModel):
"""What the user asks for: their ingredients plus optional filters."""
ingredients: List[str] = Field(min_length=1, max_length=30)
count: int = Field(default=3, ge=1, le=5, description="How many recipes to suggest")
servings: Optional[int] = Field(default=None, ge=1, le=12)
meal_type: Optional[MealType] = None
cuisine: Optional[str] = Field(default=None, max_length=40)
difficulty: Optional[Difficulty] = None
dietary_preferences: List[str] = Field(default_factory=list, max_length=10)
max_cooking_time: Optional[int] = Field(default=None, gt=0, le=600)
allow_external_ingredients: bool = False


class Recipe(BaseModel):
"""One recipe as produced by the LLM and returned by the API."""
title: str = Field(description="The name of the recipe")
description: str = Field(description="One short sentence that makes the dish sound appealing")
ingredients: List[str] = Field(description="All ingredients required, including quantities")
instructions: List[str] = Field(description="Step-by-step preparation instructions")
cooking_time: int = Field(description="Total cooking time in minutes")
difficulty: str = Field(description="Difficulty level: Easy, Medium or Hard")
servings: int = Field(description="How many people the recipe serves")
tags: List[str] = Field(description='Relevant tags, e.g. "vegetarian", "quick", "dinner"')

class ShoppingList(BaseModel):
"""Ingredients the user still needs to buy."""
shopping_list: List[str] = Field(description="Recipe ingredients the user does not have, without quantities")

class Recipe(GeneratedRecipe):
shopping_list: Optional[List[str]] = None

model_config = ConfigDict(
json_schema_extra={
"example": {
"title": "Pasta with Tomato Sauce",
"ingredients": [
"200g pasta",
"2 tomatoes",
"1 onion",
"2 cloves garlic",
"2 tbsp olive oil",
"Salt and pepper to taste"
],
"instructions": [
"Bring a large pot of salted water to boil",
"Cook pasta according to package instructions",
"Meanwhile, heat olive oil in a pan",
"Sauté chopped onion and garlic until fragrant",
"Add chopped tomatoes and cook until softened",
"Season with salt and pepper",
"Toss cooked pasta with the sauce"
],
"cooking_time": 20,
"difficulty": "Easy",
"servings": 2,
"tags": ["pasta", "vegetarian", "quick"],
"shopping_list": []
}
}
shopping_list: List[str] = Field(
description="Ingredients of this recipe the user does not have, without quantities. "
"Empty if the user has everything."
)


class RecipeSuggestions(BaseModel):
"""Several distinct recipes for one request, generated in a single LLM call."""
recipes: List[Recipe] = Field(description="Distinct recipes, each a different dish")
14 changes: 10 additions & 4 deletions backend/app/services/database_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,28 @@
from app.models.recipe import Recipe as RecipeSchema


# llm_requests.operation of a recipe suggestion call
RECIPE_SUGGESTIONS = "recipe_suggestions"


class DatabaseService:
def __init__(self, db: Session):
self.db = db

# Recipe operations
def create_recipe(self, recipe_data: RecipeSchema, source: str = "generated") -> Recipe:
def create_recipe(
self, recipe_data: RecipeSchema, source: str = "generated", llm_request_id: Optional[int] = None
) -> Recipe:
"""Save a recipe with its ingredient lines and tags"""
db_recipe = Recipe(
title=recipe_data.title,
description=recipe_data.description,
servings=recipe_data.servings,
cooking_time_minutes=recipe_data.cooking_time,
difficulty=recipe_data.difficulty,
steps=recipe_data.instructions,
source=source,
llm_request_id=llm_request_id,
ingredients=[
RecipeIngredient(position=i, raw_text=line)
for i, line in enumerate(recipe_data.ingredients, 1)
Expand Down Expand Up @@ -51,7 +59,6 @@ def log_llm_request(
input: dict[str, Any],
latency_ms: int,
error: Optional[str] = None,
recipe_id: Optional[int] = None,
user_id: Optional[uuid.UUID] = None,
) -> LLMRequest:
"""Record one LLM call"""
Expand All @@ -61,7 +68,6 @@ def log_llm_request(
input=input,
latency_ms=latency_ms,
error=error,
recipe_id=recipe_id,
user_id=user_id,
)
self.db.add(request)
Expand All @@ -76,7 +82,7 @@ def get_popular_ingredients(self, limit: int = 10) -> List[tuple[str, int]]:
select(ingredient.c.value, count)
.select_from(LLMRequest)
.join(ingredient, true())
.where(LLMRequest.operation == "recipe", LLMRequest.error.is_(None))
.where(LLMRequest.operation == RECIPE_SUGGESTIONS, LLMRequest.error.is_(None))
.group_by(ingredient.c.value)
.order_by(count.desc(), ingredient.c.value)
.limit(limit)
Expand Down
Loading
Loading