Introduction: AI-Powered Recipe Generation

Welcome to this lesson on generating new recipes with AI! So far, you have learned how to interact with large language models (LLMs), structure prompts, and manage LLM calls in your Flask application. Now, you will see how these skills come together to create a feature that generates unique cooking recipes based on a list of ingredients provided by the user.

Imagine you have a few ingredients in your fridge and want to know what you can cook. With AI-powered recipe generation, your app can suggest creative, step-by-step recipes instantly. This not only makes your app more helpful but also demonstrates the power of combining AI with web development.

In this lesson, you will learn how to connect your Flask backend to the AI, send ingredient lists, and return structured recipes to your users. By the end, you will understand the full flow of generating a recipe with AI and preparing it for use in your application.

Quick Recall: Prompts and LLM Manager

Before we dive in, let’s briefly recall two important concepts from previous lessons:

  • Prompt Templates:
    You learned how to use template files to create prompts for the AI. These templates can include placeholders (like {{ingredients}}) that are filled in with real values before being sent to the AI.

  • LLM Manager:
    The LLM Manager is a helper that handles all communication with the language model. It loads the right prompts, fills in variables, sends the request, and returns the AI’s response.

These tools are the foundation for generating recipes with AI. In this lesson, you will see how they are used together in a real Flask route.

How Recipe Generation Works in Flask

Let’s walk through how your Flask app generates a recipe using AI, step by step.

1. The API Route

Your app provides a special route for generating recipes:

@routes.route('/api/recipes/generate', methods=['POST'])
def generate_recipe():
    data = request.get_json()
    ingredients = data.get('ingredients', [])

    if not ingredients:
        return jsonify({'error': 'No ingredients provided'}), 400

    ingredient_str = ', '.join(ingredients)
    # ... (rest of the code)
  • This route listens for POST requests at /api/recipes/generate.
  • It expects a JSON body with an ingredients list.
  • If no ingredients are provided, it returns an error.

Example request:

{
  "ingredients": ["chicken", "rice", "broccoli"]
}
2. Preparing the Prompts

The route uses two prompt templates: a system prompt and a user prompt. These are loaded and filled in with the user’s ingredients.

response = generate_response(
    system_prompt_name='recipe_gen_system',
    user_prompt_name='recipe_gen_user',
    variables={'ingredients': ingredient_str}
)
  • generate_response loads the prompt templates and fills in the {{ingredients}} variable.
  • The system prompt sets the AI’s role and output format.
  • The user prompt asks the AI to create a recipe using the given ingredients.
3. Getting the AI’s Response

The AI returns a recipe as a formatted string, for example:

Name: Chicken and Broccoli Rice Bowl
Ingredients:
- chicken
- rice
- broccoli
Steps:
1. Cook the rice.
2. Sauté the chicken.
3. Add broccoli and mix everything together.

This response is then processed by your app.

Parsing and Structuring the AI’s Recipe

After receiving the AI’s response, your app needs to extract the recipe name, ingredients, and steps so they can be returned as structured data.

Let’s break down how this is done:

1. Splitting the Response

The response is split into lines for easier processing:

lines = response.strip().splitlines()
section = None
name = None
parsed_ingredients = []
steps = []
  • lines is a list of each line in the AI’s response.
  • section keeps track of which part of the recipe you are reading.
2. Extracting Each Section

The code loops through each line and checks which section it belongs to:

for line in lines:
    if line.lower().startswith("name:"):
        name = line.split(":", 1)[1].strip()
        section = None
    elif line.lower().startswith("ingredients:"):
        section = "ingredients"
    elif line.lower().startswith("steps:"):
        section = "steps"
    elif section == "ingredients" and line.strip().startswith("-"):
        parsed_ingredients.append(line.strip()[1:].strip())
    elif section == "steps" and line.strip()[:2].replace('.', '').isdigit():
        steps.append(line.strip())
  • If the line starts with Name:, it extracts the recipe name.
  • If the line starts with Ingredients:, it switches to the ingredients section.
  • If the line starts with Steps:, it switches to the steps section.
  • While in the ingredients section, it collects each ingredient (lines starting with -).
  • While in the steps section, it collects each step (lines starting with a number).
3. Returning the Structured Recipe

Finally, the route returns the structured recipe as JSON:

return jsonify({
    "name": name,
    "ingredients": parsed_ingredients,
    "steps": steps
}), 200

Example output:

{
  "name": "Chicken and Broccoli Rice Bowl",
  "ingredients": ["chicken", "rice", "broccoli"],
  "steps": [
    "1. Cook the rice.",
    "2. Sauté the chicken.",
    "3. Add broccoli and mix everything together."
  ]
}

This makes it easy for your frontend or other parts of your app to use the generated recipe.

Putting It All Together: Full Implementation

Here is the complete implementation of the recipe generation route in your Flask app, combining all the steps discussed above:

from flask import Blueprint, request, jsonify
from your_project.llm_manager import generate_response

routes = Blueprint('routes', __name__)

@routes.route('/api/recipes/generate', methods=['POST'])
def generate_recipe():
    data = request.get_json()
    ingredients = data.get('ingredients', [])

    if not ingredients:
        return jsonify({'error': 'No ingredients provided'}), 400

    ingredient_str = ', '.join(ingredients)

    # Generate the AI response using prompt templates
    response = generate_response(
        system_prompt_name='recipe_gen_system',
        user_prompt_name='recipe_gen_user',
        variables={'ingredients': ingredient_str}
    )

    # Parse the AI's response
    lines = response.strip().splitlines()
    section = None
    name = None
    parsed_ingredients = []
    steps = []

    for line in lines:
        if line.lower().startswith("name:"):
            name = line.split(":", 1)[1].strip()
            section = None
        elif line.lower().startswith("ingredients:"):
            section = "ingredients"
        elif line.lower().startswith("steps:"):
            section = "steps"
        elif section == "ingredients" and line.strip().startswith("-"):
            parsed_ingredients.append(line.strip()[1:].strip())
        elif section == "steps" and line.strip()[:2].replace('.', '').isdigit():
            steps.append(line.strip())

    return jsonify({
        "name": name,
        "ingredients": parsed_ingredients,
        "steps": steps
    }), 200

This code brings together all the concepts from the lesson: receiving user input, preparing prompts, calling the AI, parsing the response, and returning a structured recipe. You can now use this route in your Flask app to generate recipes based on any list of ingredients provided by your users.

Summary and Practice Preview

In this lesson, you learned how your Flask app generates new recipes using AI. You saw how the app:

  • Receives a list of ingredients from the user,
  • Prepares and sends prompts to the AI,
  • Parses the AI’s response to extract the recipe name, ingredients, and steps,
  • Returns the structured recipe as JSON.

You are now ready to practice building and testing this feature yourself. In the next exercises, you will get hands-on experience with the code, try generating recipes with different ingredients, and see how the AI responds. This skill is a key part of making your cooking helper app truly smart and interactive.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal