diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index 1070f70..2315e1f 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -1,21 +1,14 @@ 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 @@ -23,29 +16,26 @@ class UserCreateResponse(BaseModel): 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)): diff --git a/backend/app/models/database_models.py b/backend/app/models/database_models.py index 7023a1e..808ae1b 100644 --- a/backend/app/models/database_models.py +++ b/backend/app/models/database_models.py @@ -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( @@ -110,7 +115,7 @@ 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) @@ -118,7 +123,7 @@ class LLMRequest(Base): 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() diff --git a/backend/app/models/recipe.py b/backend/app/models/recipe.py index 0e065c9..b56bb51 100644 --- a/backend/app/models/recipe.py +++ b/backend/app/models/recipe.py @@ -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") diff --git a/backend/app/services/database_service.py b/backend/app/services/database_service.py index ddfb482..3ee1c8f 100644 --- a/backend/app/services/database_service.py +++ b/backend/app/services/database_service.py @@ -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) @@ -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""" @@ -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) @@ -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) diff --git a/backend/app/services/recipe_service.py b/backend/app/services/recipe_service.py index ff3d418..50ba85a 100644 --- a/backend/app/services/recipe_service.py +++ b/backend/app/services/recipe_service.py @@ -6,8 +6,8 @@ from sqlalchemy.orm import Session from langchain_core.language_models import BaseChatModel from langchain_google_genai import ChatGoogleGenerativeAI -from app.models.recipe import GeneratedRecipe, Recipe, ShoppingList -from app.services.database_service import DatabaseService +from app.models.recipe import Recipe, RecipeRequest, RecipeSuggestions +from app.services.database_service import RECIPE_SUGGESTIONS, DatabaseService from app.core.config import settings logger = logging.getLogger(__name__) @@ -16,7 +16,7 @@ class LLMConfigurationError(RuntimeError): """Raised when the LLM cannot be set up (e.g. missing API key).""" class RecipeGenerationError(RuntimeError): - """Raised when the LLM fails to produce a usable recipe.""" + """Raised when the LLM fails to produce usable recipes.""" def _elapsed_ms(started: float) -> int: return round((time.perf_counter() - started) * 1000) @@ -50,141 +50,94 @@ def llm(self) -> BaseChatModel: self._llm = get_llm() return self._llm - def _build_recipe_prompt( - self, - ingredients: List[str], - dietary_preferences: Optional[List[str]], - max_cooking_time: Optional[int], - allow_external_ingredients: bool - ) -> str: + def _build_prompt(self, request: RecipeRequest) -> str: """Helper function to build the prompt for the LLM.""" + count = request.count lines = [ - "You are a creative chef. Generate a single, delicious recipe based on " - f"the following ingredients: {', '.join(ingredients)}.", + f"You are a creative chef. Suggest {count} distinct recipe{'s' if count > 1 else ''} " + f"based on the following ingredients: {', '.join(request.ingredients)}.", ] + if count > 1: + lines.append("Each recipe must be a clearly different dish, not a variation of another.") - if allow_external_ingredients: + if request.allow_external_ingredients: lines.append( - "You can suggest a recipe that requires a few extra simple ingredients if it makes " - "the dish significantly better. Assume the user has basic pantry staples like salt, " - "pepper, and oil." + "A recipe may need a few extra simple ingredients if it makes the dish significantly " + "better. Assume the user has basic pantry staples like salt, pepper, and oil. List " + "the ingredients the user would need to buy in shopping_list, without quantities." ) else: lines.append( "You MUST ONLY use the ingredients provided. Do not suggest any extra ingredients " - "that are not on the list." + "that are not on the list. Leave shopping_list empty." ) constraints = [] - if dietary_preferences: - constraints.append(f"- Dietary preferences: the recipe must be suitable for {', '.join(dietary_preferences)}.") - if max_cooking_time: - constraints.append(f"- Maximum cooking time: the total cooking time must not exceed {max_cooking_time} minutes.") + if request.meal_type: + constraints.append(f"- Meal: every recipe must be a {request.meal_type.value}.") + if request.cuisine: + constraints.append(f"- Cuisine: every recipe must be {request.cuisine} cuisine.") + if request.difficulty: + constraints.append(f"- Difficulty: every recipe must be {request.difficulty.value}.") + if request.servings: + constraints.append(f"- Servings: every recipe must serve {request.servings}.") + if request.dietary_preferences: + constraints.append( + f"- Dietary preferences: every recipe must be suitable for {', '.join(request.dietary_preferences)}." + ) + if request.max_cooking_time: + constraints.append( + f"- Maximum cooking time: the total cooking time must not exceed {request.max_cooking_time} minutes." + ) if constraints: lines.append("Please adhere to these constraints:") lines.extend(constraints) return "\n".join(lines) - def _build_shopping_list_prompt( - self, - user_ingredients: List[str], - recipe_ingredients: List[str] - ) -> str: - """Helper function to build the shopping list prompt.""" - return "\n".join([ - f"A user has the following ingredients: {', '.join(user_ingredients)}.", - f"A recipe requires these ingredients: {', '.join(recipe_ingredients)}.", - "", - "Compare the two lists and generate a shopping list of ingredients the user needs to buy.", - "The shopping list should only include items from the recipe that the user does not have.", - "- If the user has 'chicken' and the recipe needs '1 lb boneless, skinless chicken breasts', " - "consider it available. General terms match specific ones.", - "- Assume basic pantry staples (salt, pepper, oil, water) are available.", - "- Do not include quantities in the final list.", - "- If the user has all the ingredients, return an empty list.", - ]) - - def _log_llm_request(self, operation: str, input: dict[str, Any], latency_ms: int, **fields) -> None: - if self.db_service: - self.db_service.log_llm_request( - operation=operation, model=settings.GEMINI_MODEL, input=input, latency_ms=latency_ms, **fields - ) - - async def _generate_shopping_list( - self, - user_ingredients: List[str], - recipe_ingredients: List[str] - ) -> List[str]: - """Generates a shopping list using the LLM.""" - if not recipe_ingredients: - return [] - - prompt = self._build_shopping_list_prompt(user_ingredients, recipe_ingredients) - log_input = {"user_ingredients": user_ingredients, "recipe_ingredients": recipe_ingredients} - started = time.perf_counter() - try: - result = await self.llm.with_structured_output(ShoppingList).ainvoke(prompt) - except Exception as e: - # The recipe is still useful without a shopping list, so don't fail the request - logger.exception("Failed to generate shopping list") - self._log_llm_request("shopping_list", log_input, _elapsed_ms(started), error=repr(e)) - return [] - self._log_llm_request("shopping_list", log_input, _elapsed_ms(started)) - return result.shopping_list - - async def get_recipe_recommendation( - self, - ingredients: List[str], - dietary_preferences: Optional[List[str]] = None, - max_cooking_time: Optional[int] = None, - allow_external_ingredients: bool = False, - user_id: Optional[uuid.UUID] = None - ) -> Recipe: + def _log_llm_request(self, input: dict[str, Any], latency_ms: int, **fields) -> Optional[int]: + if not self.db_service: + return None + request = self.db_service.log_llm_request( + operation=RECIPE_SUGGESTIONS, model=settings.GEMINI_MODEL, input=input, latency_ms=latency_ms, **fields + ) + return request.id + + async def get_recipe_suggestions( + self, request: RecipeRequest, user_id: Optional[uuid.UUID] = None + ) -> List[Recipe]: """ - Generate a recipe recommendation based on available ingredients using Google Gemini. + Generate several recipe suggestions in a single LLM call using Google Gemini. """ - prompt =self._build_recipe_prompt(ingredients, dietary_preferences, max_cooking_time, allow_external_ingredients) + prompt = self._build_prompt(request) logger.debug("Recipe prompt:\n%s", prompt) - log_input = { - "ingredients": ingredients, - "dietary_preferences": dietary_preferences or [], - "max_cooking_time": max_cooking_time, - "allow_external_ingredients": allow_external_ingredients, - } + log_input = request.model_dump(mode="json") llm = self.llm # Raises LLMConfigurationError before anything is timed or logged started = time.perf_counter() try: - generated = await llm.with_structured_output(GeneratedRecipe).ainvoke(prompt) - if generated is None: - raise RecipeGenerationError("The AI model returned an empty response.") + result = await llm.with_structured_output(RecipeSuggestions).ainvoke(prompt) + if result is None or not result.recipes: + raise RecipeGenerationError("The AI model returned no recipes.") except Exception as e: logger.exception("LLM recipe generation failed") - self._log_llm_request("recipe", log_input, _elapsed_ms(started), error=repr(e), user_id=user_id) + self._log_llm_request(log_input, _elapsed_ms(started), error=repr(e), user_id=user_id) if isinstance(e, RecipeGenerationError): raise - raise RecipeGenerationError("Failed to generate a valid recipe from the AI model.") from e - latency_ms = _elapsed_ms(started) - - recipe = Recipe(**generated.model_dump()) + raise RecipeGenerationError("Failed to generate valid recipes from the AI model.") from e - # Generate shopping list only if external ingredients are allowed - if allow_external_ingredients: - recipe.shopping_list = await self._generate_shopping_list( - user_ingredients=ingredients, - recipe_ingredients=recipe.ingredients - ) - else: - recipe.shopping_list = [] + # The model occasionally returns more than asked for + recipes = result.recipes[: request.count] + if not request.allow_external_ingredients: + for recipe in recipes: + recipe.shopping_list = [] + llm_request_id = self._log_llm_request(log_input, _elapsed_ms(started), user_id=user_id) if self.db_service: - db_recipe = self.db_service.create_recipe(recipe) - self._log_llm_request( - "recipe", log_input, latency_ms, recipe_id=db_recipe.id, user_id=user_id - ) + for recipe in recipes: + self.db_service.create_recipe(recipe, llm_request_id=llm_request_id) - return recipe + return recipes async def get_ingredient_suggestions(self, query: str) -> List[str]: """ diff --git a/backend/migrations/versions/2026_10_23_2131-6614d1f4ebee_link_recipes_to_llm_requests.py b/backend/migrations/versions/2026_10_23_2131-6614d1f4ebee_link_recipes_to_llm_requests.py new file mode 100644 index 0000000..0e4b3dd --- /dev/null +++ b/backend/migrations/versions/2026_10_23_2131-6614d1f4ebee_link_recipes_to_llm_requests.py @@ -0,0 +1,54 @@ +"""link recipes to llm requests + +Revision ID: 6614d1f4ebee +Revises: afc2e767b03b +Create Date: 2026-10-23 21:31:52.768360 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '6614d1f4ebee' +down_revision: Union[str, Sequence[str], None] = 'afc2e767b03b' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + op.add_column('recipes', sa.Column('description', sa.Text(), nullable=True)) + op.add_column('recipes', sa.Column('llm_request_id', sa.BigInteger(), nullable=True)) + op.create_index(op.f('ix_recipes_llm_request_id'), 'recipes', ['llm_request_id'], unique=False) + op.create_foreign_key(op.f('fk_recipes_llm_request_id_llm_requests'), 'recipes', 'llm_requests', ['llm_request_id'], ['id'], ondelete='SET NULL') + + # Keep existing data: move each request -> recipe link to the recipe side, and + # rename single-recipe requests so ingredient popularity still counts them + op.execute( + "UPDATE recipes SET llm_request_id = llm_requests.id " + "FROM llm_requests WHERE llm_requests.recipe_id = recipes.id" + ) + op.execute("UPDATE llm_requests SET operation = 'recipe_suggestions' WHERE operation = 'recipe'") + + op.drop_constraint(op.f('fk_llm_requests_recipe_id_recipes'), 'llm_requests', type_='foreignkey') + op.drop_column('llm_requests', 'recipe_id') + + +def downgrade() -> None: + """Downgrade schema.""" + op.add_column('llm_requests', sa.Column('recipe_id', sa.INTEGER(), autoincrement=False, nullable=True)) + op.create_foreign_key(op.f('fk_llm_requests_recipe_id_recipes'), 'llm_requests', 'recipes', ['recipe_id'], ['id'], ondelete='SET NULL') + # A request may now own several recipes; the old column can only point back to one of them + op.execute( + "UPDATE llm_requests SET recipe_id = " + "(SELECT min(id) FROM recipes WHERE recipes.llm_request_id = llm_requests.id)" + ) + op.execute("UPDATE llm_requests SET operation = 'recipe' WHERE operation = 'recipe_suggestions'") + + op.drop_constraint(op.f('fk_recipes_llm_request_id_llm_requests'), 'recipes', type_='foreignkey') + op.drop_index(op.f('ix_recipes_llm_request_id'), table_name='recipes') + op.drop_column('recipes', 'llm_request_id') + op.drop_column('recipes', 'description') diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 7cc918c..7a88ef2 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -22,7 +22,7 @@ from main import app from app.api.routes import get_recipe_service from app.core.database import Base, engine, get_db -from app.models.recipe import GeneratedRecipe, ShoppingList +from app.models.recipe import Recipe, RecipeSuggestions from app.services.recipe_service import RecipeService @@ -75,23 +75,31 @@ def with_structured_output(self, schema): return self.structured[schema] -SAMPLE_RECIPE = GeneratedRecipe( - title="Garlic Tomato Pasta", - ingredients=["200g pasta", "3 tomatoes", "2 cloves garlic", "fresh basil"], - instructions=["Boil pasta", "Make sauce", "Combine"], - cooking_time=20, - difficulty="Easy", - servings=2, - tags=["pasta", "vegetarian"], -) +def make_recipe(title: str, shopping_list: list[str] | None = None) -> Recipe: + return Recipe( + title=title, + description=f"A quick {title.lower()}.", + ingredients=["200g pasta", "3 tomatoes", "2 cloves garlic", "fresh basil"], + instructions=["Boil pasta", "Make sauce", "Combine"], + cooking_time=20, + difficulty="Easy", + servings=2, + tags=["pasta", "vegetarian"], + shopping_list=shopping_list or [], + ) + + +SAMPLE_SUGGESTIONS = RecipeSuggestions(recipes=[ + make_recipe("Garlic Tomato Pasta", ["fresh basil"]), + make_recipe("Pasta Puttanesca", ["olives", "capers"]), + make_recipe("Tomato Orzo"), +]) @pytest.fixture def fake_llm(): - return FakeLLM({ - GeneratedRecipe: SAMPLE_RECIPE, - ShoppingList: ShoppingList(shopping_list=["fresh basil"]), - }) + # A deep copy per test, because the service edits the recipes it gets back + return FakeLLM({RecipeSuggestions: SAMPLE_SUGGESTIONS.model_copy(deep=True)}) @pytest.fixture diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 3aa8a2b..dd3c655 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -1,140 +1,139 @@ -from app.models.recipe import GeneratedRecipe, ShoppingList +from app.core.database import SessionLocal +from app.models.database_models import LLMRequest, Recipe as RecipeRow +from app.models.recipe import RecipeSuggestions from app.services.recipe_service import RecipeService -from tests.conftest import FakeLLM, SAMPLE_RECIPE +from tests.conftest import FakeLLM, SAMPLE_SUGGESTIONS + +RECOMMEND = "/api/v1/recipes/recommend" + + +def prompt_of(fake_llm) -> str: + return fake_llm.structured[RecipeSuggestions].prompts[0] def test_health(client): assert client.get("/health").json()["status"] == "healthy" -def test_recommend_returns_recipe_without_shopping_list(client, fake_llm): - response = client.post("/api/v1/recipes/recommend", json={"ingredients": ["pasta", "Tomato", "garlic"]}) +def test_recommend_returns_requested_number_of_recipes(client): + response = client.post(RECOMMEND, json={"ingredients": ["pasta", "tomato"], "count": 2}) assert response.status_code == 200 - body = response.json() - assert body["title"] == "Garlic Tomato Pasta" - assert body["shopping_list"] == [] - # Shopping list is only generated when extra ingredients are allowed - assert fake_llm.structured[ShoppingList].prompts == [] - # Ingredients are normalised before reaching the prompt - assert "pasta, tomato, garlic" in fake_llm.structured[GeneratedRecipe].prompts[0] + titles = [r["title"] for r in response.json()["recipes"]] + assert titles == ["Garlic Tomato Pasta", "Pasta Puttanesca"] -def test_recommend_with_external_ingredients_builds_shopping_list(client): - response = client.post( - "/api/v1/recipes/recommend", - json={"ingredients": ["pasta", "tomato"], "allow_external_ingredients": True}, - ) +def test_recommend_defaults_to_three_recipes(client, fake_llm): + response = client.post(RECOMMEND, json={"ingredients": ["pasta"]}) - assert response.status_code == 200 - assert response.json()["shopping_list"] == ["fresh basil"] + assert len(response.json()["recipes"]) == 3 + assert "Suggest 3 distinct recipes" in prompt_of(fake_llm) + + +def test_ingredients_are_normalised_before_the_prompt(client, fake_llm): + client.post(RECOMMEND, json={"ingredients": ["pasta", "Tomato", " garlic "]}) + assert "pasta, tomato, garlic" in prompt_of(fake_llm) -def test_prompt_includes_constraints(client, fake_llm): - client.post( - "/api/v1/recipes/recommend", - json={"ingredients": ["rice"], "dietary_preferences": ["vegan"], "max_cooking_time": 30}, - ) - prompt = fake_llm.structured[GeneratedRecipe].prompts[0] +def test_prompt_includes_all_filters(client, fake_llm): + client.post(RECOMMEND, json={ + "ingredients": ["rice"], + "count": 1, + "meal_type": "dinner", + "cuisine": "Turkish", + "difficulty": "easy", + "servings": 4, + "dietary_preferences": ["vegan"], + "max_cooking_time": 30, + }) + + prompt = prompt_of(fake_llm) + assert "Suggest 1 distinct recipe " in prompt + assert "must be a dinner" in prompt + assert "must be Turkish cuisine" in prompt + assert "must be easy" in prompt + assert "must serve 4" in prompt assert "suitable for vegan" in prompt assert "must not exceed 30 minutes" in prompt - assert "\\n" not in prompt -def test_recommend_rejects_empty_ingredients(client): - assert client.post("/api/v1/recipes/recommend", json={"ingredients": []}).status_code == 422 - assert client.post("/api/v1/recipes/recommend", json={"ingredients": [" "]}).status_code == 422 +def test_shopping_lists_are_empty_without_extras(client): + response = client.post(RECOMMEND, json={"ingredients": ["pasta"]}) + assert all(r["shopping_list"] == [] for r in response.json()["recipes"]) -def test_llm_failure_returns_502(client, fake_llm): - fake_llm.structured[GeneratedRecipe].response = RuntimeError("boom") - response = client.post("/api/v1/recipes/recommend", json={"ingredients": ["egg"]}) +def test_shopping_lists_are_kept_with_extras(client): + response = client.post(RECOMMEND, json={"ingredients": ["pasta"], "allow_external_ingredients": True}) + + assert response.json()["recipes"][0]["shopping_list"] == ["fresh basil"] - assert response.status_code == 502 - assert "boom" not in response.json()["detail"] +def test_recommend_rejects_invalid_input(client): + assert client.post(RECOMMEND, json={"ingredients": []}).status_code == 422 + assert client.post(RECOMMEND, json={"ingredients": [" "]}).status_code == 422 + assert client.post(RECOMMEND, json={"ingredients": ["egg"], "count": 6}).status_code == 422 + assert client.post(RECOMMEND, json={"ingredients": ["egg"], "meal_type": "brunch"}).status_code == 422 -def test_llm_failure_does_not_count_ingredient_popularity(client, fake_llm): - fake_llm.structured[GeneratedRecipe].response = RuntimeError("boom") - client.post("/api/v1/recipes/recommend", json={"ingredients": ["kohlrabi"]}) +def test_llm_failure_returns_502(client, fake_llm): + fake_llm.structured[RecipeSuggestions].response = RuntimeError("boom") - assert client.get("/api/v1/ingredients/suggestions", params={"query": "kohlrabi"}).json()["suggestions"] == [] + response = client.post(RECOMMEND, json={"ingredients": ["egg"]}) + assert response.status_code == 502 + assert "boom" not in response.json()["detail"] -def test_shopping_list_failure_still_returns_recipe(client, fake_llm): - fake_llm.structured[ShoppingList].response = RuntimeError("boom") - response = client.post( - "/api/v1/recipes/recommend", - json={"ingredients": ["pasta"], "allow_external_ingredients": True}, - ) +def test_empty_llm_response_returns_502(client, fake_llm): + fake_llm.structured[RecipeSuggestions].response = RecipeSuggestions(recipes=[]) - assert response.status_code == 200 - assert response.json()["shopping_list"] == [] + assert client.post(RECOMMEND, json={"ingredients": ["egg"]}).status_code == 502 def test_missing_api_key_returns_503(): from fastapi.testclient import TestClient from main import app - response = TestClient(app).post("/api/v1/recipes/recommend", json={"ingredients": ["egg"]}) + response = TestClient(app).post(RECOMMEND, json={"ingredients": ["egg"]}) assert response.status_code == 503 assert "GOOGLE_API_KEY" in response.json()["detail"] -def test_ingredient_suggestions_use_popularity(client): - client.post("/api/v1/recipes/recommend", json={"ingredients": ["zucchini"]}) - - response = client.get("/api/v1/ingredients/suggestions", params={"query": "zucc"}) - - assert response.json()["suggestions"] == ["zucchini"] - - -def test_suggestions_fall_back_to_common_ingredients(): - import asyncio - service = RecipeService(llm=FakeLLM({GeneratedRecipe: SAMPLE_RECIPE})) - - assert asyncio.run(service.get_ingredient_suggestions("garl")) == ["garlic"] - - -def test_successful_recipe_is_saved_and_logged(client): - client.post("/api/v1/recipes/recommend", json={"ingredients": ["pasta", "tomato"]}) +def test_recipes_are_saved_and_linked_to_one_logged_request(client): + client.post(RECOMMEND, json={"ingredients": ["pasta", "tomato"], "count": 2}) - from app.core.database import SessionLocal - from app.models.database_models import LLMRequest, Recipe with SessionLocal() as db: - recipe = db.query(Recipe).one() request = db.query(LLMRequest).one() + recipes = db.query(RecipeRow).order_by(RecipeRow.id).all() - assert recipe.title == "Garlic Tomato Pasta" - assert recipe.steps == ["Boil pasta", "Make sauce", "Combine"] - assert request.operation == "recipe" - assert request.recipe_id == recipe.id - assert request.input["ingredients"] == ["pasta", "tomato"] + assert request.operation == "recipe_suggestions" assert request.error is None + assert request.input["ingredients"] == ["pasta", "tomato"] + assert request.input["count"] == 2 + assert [r.title for r in recipes] == ["Garlic Tomato Pasta", "Pasta Puttanesca"] + assert all(r.llm_request_id == request.id for r in recipes) + assert recipes[0].description == "A quick garlic tomato pasta." def test_failed_llm_call_is_logged_with_error(client, fake_llm): - fake_llm.structured[GeneratedRecipe].response = RuntimeError("boom") + fake_llm.structured[RecipeSuggestions].response = RuntimeError("boom") - client.post("/api/v1/recipes/recommend", json={"ingredients": ["egg"]}) + client.post(RECOMMEND, json={"ingredients": ["egg"]}) - from app.core.database import SessionLocal - from app.models.database_models import LLMRequest with SessionLocal() as db: request = db.query(LLMRequest).one() - - assert request.recipe_id is None + assert db.query(RecipeRow).count() == 0 assert "boom" in request.error -def test_popular_ingredients_count_successful_requests(client): - client.post("/api/v1/recipes/recommend", json={"ingredients": ["egg", "tomato"]}) - client.post("/api/v1/recipes/recommend", json={"ingredients": ["egg"]}) +def test_popular_ingredients_count_successful_requests(client, fake_llm): + client.post(RECOMMEND, json={"ingredients": ["egg", "tomato"]}) + client.post(RECOMMEND, json={"ingredients": ["egg"]}) + fake_llm.structured[RecipeSuggestions].response = RuntimeError("boom") + client.post(RECOMMEND, json={"ingredients": ["kohlrabi"]}) response = client.get("/api/v1/ingredients/popular") @@ -142,3 +141,18 @@ def test_popular_ingredients_count_successful_requests(client): {"name": "egg", "popularity": 2}, {"name": "tomato", "popularity": 1}, ] + + +def test_ingredient_suggestions_use_popularity(client): + client.post(RECOMMEND, json={"ingredients": ["zucchini"]}) + + response = client.get("/api/v1/ingredients/suggestions", params={"query": "zucc"}) + + assert response.json()["suggestions"] == ["zucchini"] + + +def test_suggestions_fall_back_to_common_ingredients(): + import asyncio + service = RecipeService(llm=FakeLLM({RecipeSuggestions: SAMPLE_SUGGESTIONS})) + + assert asyncio.run(service.get_ingredient_suggestions("garl")) == ["garlic"] diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index ba5f953..effad87 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,42 +1,46 @@ import { useState } from 'react'; -import FilterOptions from '@/components/FilterOptions'; -import IngredientInput from '@/components/IngredientInput'; -import RecipeDisplay from '@/components/RecipeDisplay'; -import ThemeToggle from '@/components/ThemeToggle'; -import { Button } from '@/components/ui/Button'; +import Header from '@/components/Header'; +import FormScreen from '@/screens/FormScreen'; +import RecipeScreen from '@/screens/RecipeScreen'; +import ResultsScreen from '@/screens/ResultsScreen'; import { ApiService } from '@/services/api'; -import type { FilterOptions as Filters, Recipe } from '@/types/recipe'; +import type { Recipe, RecipeFilters } from '@/types/recipe'; -const DEFAULT_FILTERS: Filters = { - dietary_preferences: [], +const DEFAULT_FILTERS: RecipeFilters = { + count: 3, + meal_type: null, + cuisine: null, + difficulty: null, max_cooking_time: null, + servings: null, + dietary_preferences: [], allow_external_ingredients: false, }; +// Which screen is shown; the recipe screen also knows which recipe +type View = { name: 'form' } | { name: 'results' } | { name: 'recipe'; index: number }; + export default function App() { const [ingredients, setIngredients] = useState([]); - const [filters, setFilters] = useState(DEFAULT_FILTERS); - const [recipe, setRecipe] = useState(null); + const [filters, setFilters] = useState(DEFAULT_FILTERS); + const [recipes, setRecipes] = useState([]); + const [view, setView] = useState({ name: 'form' }); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); - const handleGetRecipe = async () => { - if (ingredients.length === 0) { - setError('Please enter at least one ingredient'); - return; - } + const show = (next: View) => { + setView(next); + window.scrollTo({ top: 0 }); + }; + const handleSubmit = async () => { setLoading(true); setError(null); - try { - const recipeData = await ApiService.getRecipeRecommendation({ - ingredients, - dietary_preferences: filters.dietary_preferences.length > 0 ? filters.dietary_preferences : undefined, - max_cooking_time: filters.max_cooking_time ?? undefined, - allow_external_ingredients: filters.allow_external_ingredients, - }); - setRecipe(recipeData); + const result = await ApiService.getRecipeSuggestions({ ingredients, ...filters }); + setRecipes(result); + // A single recipe skips the results list + show(result.length === 1 ? { name: 'recipe', index: 0 } : { name: 'results' }); } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred'); } finally { @@ -44,51 +48,37 @@ export default function App() { } }; - const handleReset = () => { - setIngredients([]); - setFilters(DEFAULT_FILTERS); - setRecipe(null); - setError(null); - }; - return ( -
-
-
-
-

- Cookable -

-

Your ingredients in. A recipe out.

-
- -
- - - - - - - {error && ( -
- {error} -
+
+
+
+ {view.name === 'form' && ( + )} - - {recipe && ( - <> - - - + {view.name === 'results' && ( + show({ name: 'recipe', index })} + onBack={() => show({ name: 'form' })} + /> + )} + {view.name === 'recipe' && ( + show({ name: 'recipe', index })} + onBack={() => show(recipes.length > 1 ? { name: 'results' } : { name: 'form' })} + /> )}
diff --git a/frontend/src/components/FilterOptions.tsx b/frontend/src/components/FilterOptions.tsx index 09ad951..6bf3515 100644 --- a/frontend/src/components/FilterOptions.tsx +++ b/frontend/src/components/FilterOptions.tsx @@ -1,25 +1,17 @@ import { Card, StepHeading } from '@/components/ui/Card'; import { ToggleChip } from '@/components/ui/Chip'; -import { fieldClass } from '@/components/ui/field'; -import type { FilterOptions as Filters } from '@/types/recipe'; - -const DIETARY_OPTIONS = [ - { value: 'vegetarian', label: 'Vegetarian' }, - { value: 'vegan', label: 'Vegan' }, - { value: 'gluten-free', label: 'Gluten-free' }, - { value: 'dairy-free', label: 'Dairy-free' }, - { value: 'low-carb', label: 'Low-carb' }, -]; - -const COOKING_TIMES = [15, 30, 45, 60, 90]; +import { SelectField } from '@/components/ui/SelectField'; +import { Stepper } from '@/components/ui/Stepper'; +import { COOKING_TIMES, CUISINES, DIETARY_OPTIONS, DIFFICULTIES, MEAL_TYPES } from '@/constants/filters'; +import type { RecipeFilters } from '@/types/recipe'; interface FilterOptionsProps { - filters: Filters; - onFiltersChange: (filters: Filters) => void; + filters: RecipeFilters; + onFiltersChange: (filters: RecipeFilters) => void; } export default function FilterOptions({ filters, onFiltersChange }: FilterOptionsProps) { - const update = (changes: Partial) => onFiltersChange({ ...filters, ...changes }); + const update = (changes: Partial) => onFiltersChange({ ...filters, ...changes }); const togglePreference = (preference: string) => { const current = filters.dietary_preferences; @@ -32,46 +24,41 @@ export default function FilterOptions({ filters, onFiltersChange }: FilterOption return ( - + -
- {DIETARY_OPTIONS.map(({ value, label }) => ( - togglePreference(value)} - > - {label} - - ))} +
+ update({ meal_type })} /> + update({ cuisine })} /> + update({ difficulty })} /> + update({ max_cooking_time })} /> + update({ servings })} />
-
- - - +
+ Diet +
+ {DIETARY_OPTIONS.map(({ value, label }) => ( + togglePreference(value)} + > + {label} + + ))} +
+ + ); } diff --git a/frontend/src/components/Header.tsx b/frontend/src/components/Header.tsx new file mode 100644 index 0000000..9557a12 --- /dev/null +++ b/frontend/src/components/Header.tsx @@ -0,0 +1,15 @@ +import ThemeToggle from '@/components/ThemeToggle'; + +/** The same compact bar on every screen, pinned to the top of the page. */ +export default function Header() { + return ( +
+
+ + Cookable + + +
+
+ ); +} diff --git a/frontend/src/components/RecipeDisplay.tsx b/frontend/src/components/RecipeDisplay.tsx index 38f40ba..d8c2e2a 100644 --- a/frontend/src/components/RecipeDisplay.tsx +++ b/frontend/src/components/RecipeDisplay.tsx @@ -7,12 +7,13 @@ interface RecipeDisplayProps { } export default function RecipeDisplay({ recipe }: RecipeDisplayProps) { - const shoppingList = recipe.shopping_list ?? []; + const shoppingList = recipe.shopping_list; return (
-

{recipe.title}

+

{recipe.title}

+

{recipe.description}

{recipe.cooking_time} min {recipe.difficulty} diff --git a/frontend/src/components/ui/Segmented.tsx b/frontend/src/components/ui/Segmented.tsx new file mode 100644 index 0000000..bb6e341 --- /dev/null +++ b/frontend/src/components/ui/Segmented.tsx @@ -0,0 +1,30 @@ +interface SegmentedProps { + label: string; + value: number; + options: number[]; + onChange: (value: number) => void; +} + +/** A row of mutually exclusive number buttons, e.g. 1 to 5. */ +export function Segmented({ label, value, options, onChange }: SegmentedProps) { + return ( +
+ {options.map((option) => { + const selected = option === value; + return ( + + ); + })} +
+ ); +} diff --git a/frontend/src/components/ui/SelectField.tsx b/frontend/src/components/ui/SelectField.tsx new file mode 100644 index 0000000..81e8b01 --- /dev/null +++ b/frontend/src/components/ui/SelectField.tsx @@ -0,0 +1,30 @@ +import { fieldClass } from '@/components/ui/field'; + +interface SelectFieldProps { + label: string; + value: T | null; + options: { value: T; label: string }[]; + onChange: (value: T | null) => void; +} + +/** A labelled select whose first option, "Any", stands for null. */ +export function SelectField({ label, value, options, onChange }: SelectFieldProps) { + return ( + + ); +} diff --git a/frontend/src/components/ui/Stepper.tsx b/frontend/src/components/ui/Stepper.tsx new file mode 100644 index 0000000..66e4026 --- /dev/null +++ b/frontend/src/components/ui/Stepper.tsx @@ -0,0 +1,29 @@ +interface StepperProps { + label: string; + value: number | null; + min: number; + max: number; + onChange: (value: number | null) => void; +} + +/** A number picker with - and +; going below `min` means "any" (null). */ +export function Stepper({ label, value, min, max, onChange }: StepperProps) { + const decrease = () => onChange(value === null || value <= min ? null : value - 1); + const increase = () => onChange(value === null ? min : Math.min(value + 1, max)); + const buttonClass = 'h-full w-11 text-xl disabled:opacity-40'; + + return ( +
+ {label} +
+ + {value ?? 'Any'} + +
+
+ ); +} diff --git a/frontend/src/constants/filters.ts b/frontend/src/constants/filters.ts new file mode 100644 index 0000000..393f5d8 --- /dev/null +++ b/frontend/src/constants/filters.ts @@ -0,0 +1,32 @@ +import type { Difficulty, MealType } from '@/types/recipe'; + +// Choices offered in the preferences card + +export const MEAL_TYPES: { value: MealType; label: string }[] = [ + { value: 'breakfast', label: 'Breakfast' }, + { value: 'lunch', label: 'Lunch' }, + { value: 'dinner', label: 'Dinner' }, + { value: 'snack', label: 'Snack' }, + { value: 'dessert', label: 'Dessert' }, +]; + +export const CUISINES = ['Turkish', 'Italian', 'Mediterranean', 'Asian', 'Mexican', 'Indian'].map((c) => ({ + value: c, + label: c, +})); + +export const DIFFICULTIES: { value: Difficulty; label: string }[] = [ + { value: 'easy', label: 'Easy' }, + { value: 'medium', label: 'Medium' }, + { value: 'hard', label: 'Hard' }, +]; + +export const COOKING_TIMES = [15, 30, 45, 60, 90].map((m) => ({ value: m, label: `${m} min` })); + +export const DIETARY_OPTIONS = [ + { value: 'vegetarian', label: 'Vegetarian' }, + { value: 'vegan', label: 'Vegan' }, + { value: 'gluten-free', label: 'Gluten-free' }, + { value: 'dairy-free', label: 'Dairy-free' }, + { value: 'low-carb', label: 'Low-carb' }, +]; diff --git a/frontend/src/screens/FormScreen.tsx b/frontend/src/screens/FormScreen.tsx new file mode 100644 index 0000000..8e6f079 --- /dev/null +++ b/frontend/src/screens/FormScreen.tsx @@ -0,0 +1,58 @@ +import FilterOptions from '@/components/FilterOptions'; +import IngredientInput from '@/components/IngredientInput'; +import { Button } from '@/components/ui/Button'; +import { Segmented } from '@/components/ui/Segmented'; +import type { RecipeFilters } from '@/types/recipe'; + +interface FormScreenProps { + ingredients: string[]; + filters: RecipeFilters; + loading: boolean; + error: string | null; + onIngredientsChange: (ingredients: string[]) => void; + onFiltersChange: (filters: RecipeFilters) => void; + onSubmit: () => void; +} + +export default function FormScreen({ + ingredients, + filters, + loading, + error, + onIngredientsChange, + onFiltersChange, + onSubmit, +}: FormScreenProps) { + const { count } = filters; + + return ( + <> + + + +
+ How many recipes? + onFiltersChange({ ...filters, count: value })} + /> + +
+ + {error && ( +
+ {error} +
+ )} + + ); +} diff --git a/frontend/src/screens/RecipeScreen.tsx b/frontend/src/screens/RecipeScreen.tsx new file mode 100644 index 0000000..fe5b23a --- /dev/null +++ b/frontend/src/screens/RecipeScreen.tsx @@ -0,0 +1,43 @@ +import RecipeDisplay from '@/components/RecipeDisplay'; +import { Button } from '@/components/ui/Button'; +import type { Recipe } from '@/types/recipe'; + +interface RecipeScreenProps { + recipes: Recipe[]; + index: number; + onSelect: (index: number) => void; + onBack: () => void; +} + +export default function RecipeScreen({ recipes, index, onSelect, onBack }: RecipeScreenProps) { + const others = recipes.map((recipe, i) => ({ recipe, i })).filter(({ i }) => i !== index); + + return ( + <> + + + + + {others.length > 0 && ( +
+ Other suggestions +
+ {others.map(({ recipe, i }) => ( + + ))} +
+
+ )} + + ); +} diff --git a/frontend/src/screens/ResultsScreen.tsx b/frontend/src/screens/ResultsScreen.tsx new file mode 100644 index 0000000..5ea2aeb --- /dev/null +++ b/frontend/src/screens/ResultsScreen.tsx @@ -0,0 +1,72 @@ +import { DIETARY_OPTIONS } from '@/constants/filters'; +import { Button } from '@/components/ui/Button'; +import { Tag } from '@/components/ui/Chip'; +import type { Recipe, RecipeFilters } from '@/types/recipe'; + +const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); + +/** Short labels for the filters the user actually set. */ +function activeFilters(filters: RecipeFilters): string[] { + const labels = [ + filters.meal_type && capitalize(filters.meal_type), + filters.cuisine, + filters.difficulty && capitalize(filters.difficulty), + filters.max_cooking_time && `≤ ${filters.max_cooking_time} min`, + filters.servings && `Serves ${filters.servings}`, + ...filters.dietary_preferences.map((d) => DIETARY_OPTIONS.find((o) => o.value === d)?.label ?? d), + ]; + return labels.filter((label): label is string => Boolean(label)); +} + +interface ResultsScreenProps { + recipes: Recipe[]; + ingredients: string[]; + filters: RecipeFilters; + onSelect: (index: number) => void; + onBack: () => void; +} + +export default function ResultsScreen({ recipes, ingredients, filters, onSelect, onBack }: ResultsScreenProps) { + const title = recipes.length === 1 ? 'A recipe for you' : `${recipes.length} recipes for you`; + + return ( + <> +
+ +

{title}

+
+ {ingredients.join(' · ')} + {activeFilters(filters).map((label) => ( + {label} + ))} +
+
+ +
+ {recipes.map((recipe, i) => ( + + ))} +
+ + ); +} diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index a04cfec..6b8ec66 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -1,4 +1,4 @@ -import { Recipe, IngredientRequest } from '@/types/recipe'; +import type { Recipe, RecipeRequest, RecipeSuggestions } from '@/types/recipe'; const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000/api/v1'; @@ -14,7 +14,7 @@ async function errorMessage(response: Response): Promise { } export class ApiService { - static async getRecipeRecommendation(request: IngredientRequest): Promise { + static async getRecipeSuggestions(request: RecipeRequest): Promise { let response: Response; try { response = await fetch(`${API_BASE_URL}/recipes/recommend`, { @@ -32,7 +32,8 @@ export class ApiService { throw new Error(await errorMessage(response)); } - return response.json(); + const data: RecipeSuggestions = await response.json(); + return data.recipes; } static async getIngredientSuggestions(query: string): Promise { diff --git a/frontend/src/types/recipe.ts b/frontend/src/types/recipe.ts index 30f4c11..4b16fb8 100644 --- a/frontend/src/types/recipe.ts +++ b/frontend/src/types/recipe.ts @@ -1,23 +1,32 @@ export interface Recipe { title: string; + description: string; ingredients: string[]; instructions: string[]; cooking_time: number; difficulty: string; servings: number; tags: string[]; - shopping_list?: string[]; + shopping_list: string[]; } -export interface IngredientRequest { - ingredients: string[]; - dietary_preferences?: string[]; - max_cooking_time?: number; - allow_external_ingredients?: boolean; -} +export type MealType = 'breakfast' | 'lunch' | 'dinner' | 'snack' | 'dessert'; +export type Difficulty = 'easy' | 'medium' | 'hard'; -export interface FilterOptions { - dietary_preferences: string[]; +/** Everything the user can choose besides the ingredients; null means "any". */ +export interface RecipeFilters { + count: number; + meal_type: MealType | null; + cuisine: string | null; + difficulty: Difficulty | null; max_cooking_time: number | null; + servings: number | null; + dietary_preferences: string[]; allow_external_ingredients: boolean; } + +export type RecipeRequest = { ingredients: string[] } & RecipeFilters; + +export interface RecipeSuggestions { + recipes: Recipe[]; +}