Project - Custom Recipe Generator

I am unable to understand how to function the Custom Recipe Generator Project, it is not clearly explained in the text and the video. Please explain each point and function in detail.

Hi @shreyashkanodia

Here is a brief explanation of the Custom Recipe Generator Project:
This code creates a custom recipe generator using Flask, OpenAI, and HTML with JavaScript.

  1. Imports and API Key Configuration:
  • The code imports necessary modules: openai for AI interactions, os for environment variables, and Flask for web framework.
  • It sets the OpenAI API key using an environment variable.
  1. Recipe Generation Function:
  • generate_tutorial(components): This function interacts with the OpenAI API to generate a recipe based on the provided ingredients. It sends a prompt to the AI to create a recipe and returns the generated content.
  1. Flask Web Application:
  • The Flask app is instantiated with app = Flask(__name__).
  • Two routes are defined:
    • '/': Handles GET and POST requests. If a POST request is made, it retrieves the ingredients from the form and generates a recipe using generate_tutorial(). The result is rendered on a simple HTML page.
    • '/generate': Handles POST requests for generating recipes, calling generate_tutorial() with the provided ingredients and returning the output.
  1. HTML Template:
  • The HTML template is embedded within the Flask route and includes a form for users to input ingredients.
  • JavaScript functions handle the form submission (generateTutorial()) and copying the generated recipe to the clipboard (copyToClipboard()).
  • The form uses Bootstrap for styling and includes a text input for ingredients and a button to submit the form.
  • The recipe output is displayed within a card element, and a “Copy” button allows users to copy the recipe to their clipboard.
  1. Running the Application:
  • The Flask app runs on host and port 8080.

This setup allows users to input a list of ingredients and get a step-by-step recipe generated by OpenAI, which is displayed on a web page and can be easily copied to the clipboard.

If you still face any issue, please feel free to get back to us

Check this line by line explanation of the code…hope it helps
from boltiotai import openai # Import the OpenAI client from the boltiotai package
import os # Import the os module for interacting with the operating system
from flask import Flask, render_template_string, request # Import Flask and related functions for web development

openai.api_key = os.environ[‘OPENAI_API_KEY’] # Set the OpenAI API key from an environment variable

def generate_tutorial(components): # Define a function to generate a recipe tutorial
response = # Call the OpenAI API to create a chat completion
model=“gpt-3.5-turbo”, # Specify the model to use
messages=[{ # Provide the messages for the chat completion
“role”: “system”, # System message setting the assistant’s role
“content”: “You are a helpful assistant”
}, {
“role”: “user”, # User message with the prompt for generating the recipe
“content”: f"Suggest a recipe using the items listed as available. Make sure you have a nice name for this recipe listed at the start. Also, include a funny version of the name of the recipe on the following line. Then share the recipe in a step-by-step manner. In the end, write a fun fact about the recipe or any of the items used in the recipe. Here are the items available: {components}, Haldi, Chilly Powder, Tomato Ketchup, Water, Garam Masala, Oil"
return response[‘choices’][0][‘message’][‘content’] # Return the generated recipe content

app = Flask(name) # Create a new Flask application

@app.route(‘/’, methods=[‘GET’, ‘POST’]) # Define the route for the root URL, supporting GET and POST methods
def hello(): # Define the function to handle requests to the root URL
output = “” # Initialize an empty string for the output
if request.method == ‘POST’: # Check if the request method is POST
components = request.form[‘components’] # Get the components from the form data
output = generate_tutorial(components) # Generate the tutorial using the components

# Render the HTML template for the web page
return render_template_string('''
    <!DOCTYPE html >
    <html >
    <head >
        <title >Infinite Project Generator </title >
        <link href=""
        <script >
            async function generateTutorial() {  // Define an async function to generate the tutorial
                const components = document.querySelector('#components').value;  // Get the components from the input field
                const output = document.querySelector('#output');  // Get the output element
                output.textContent = 'Cooking a recipe for you...';  // Display a loading message
                const response = await fetch('/generate', {  // Send a POST request to the /generate route
                    method: 'POST',
                    body: new FormData(document.querySelector('#tutorial-form'))  // Send the form data
                const newOutput = await response.text();  // Get the response text
                output.textContent = newOutput;  // Display the generated tutorial
            function copyToClipboard() {  // Define a function to copy the output to the clipboard
                const output = document.querySelector('#output');  // Get the output element
                const textarea = document.createElement('textarea');  // Create a new textarea element
                textarea.value = output.textContent;  // Set its value to the output text
                document.body.appendChild(textarea);  // Append it to the body
      ;  // Select the text
                document.execCommand('copy');  // Copy the text to the clipboard
                document.body.removeChild(textarea);  // Remove the textarea element
                alert('Copied to clipboard');  // Show an alert
        </script >
    </head >
    <body >
        <div class="container">
            <h1 class="my-4">Custom Recipe Tutorial Generator </h1 >
            <form id="tutorial-form" onsubmit="event.preventDefault(); generateTutorial();" class="mb-3">
                <div class="mb-3">
                    <label for="components" class="form-label">Ingredients / Items:</label >
                    <input type="text" class="form-control" id="components" name="components" placeholder="Enter the list of Ingredients or items you have e.g. Bread, jam, potato etc." required >
                </div >
                <button type="submit" class="btn btn-primary">Share with me a tutorial </button >
            </form >
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <button class="btn btn-secondary btn-sm" onclick="copyToClipboard()">Copy </button >
                </div >
                <div class="card-body">
                    <pre id="output" class="mb-0" style="white-space: pre-wrap;">{{ output }}</pre >
                </div >
            </div >
        </div >
    </body >
    </html >
''', output=output)  # Pass the output variable to the template

@app.route(‘/generate’, methods=[‘POST’]) # Define the route for generating the recipe, supporting POST method
def generate(): # Define the function to handle POST requests to the /generate route
components = request.form[‘components’] # Get the components from the form data
return generate_tutorial(components) # Generate and return the tutorial using the components

if name == ‘main’: # Check if the script is being run directly‘’, port=8080) # Run the Flask application on host and port 8080

@shreyashkanodia You can understand this project by below explainantion in better way:-

Setting Up the Custom Recipe Generator

Step 1: Imports and API Key Configuration

First, you import necessary modules (openai, os, sys, Flask) and set up your OpenAI API key securely. If the API key is not found in the environment variables, an error message is displayed to guide the user on how to set it up.

from boltiotai import openai
import os
import sys
from flask import Flask, render_template_string, request

# Set up the OpenAI API key
    openai.api_key = os.environ['OPENAI_API_KEY']
except KeyError:
    You haven't set up your API key yet.

    If you don't have an API key yet, visit:

    1. Make an account or sign in
    2. Click "View API Keys" from the top right menu.
    3. Click "Create new secret key"

    Then, open the Secrets Tool and add OPENAI_API_KEY as a secret.

Step 2: Recipe Generation Function

Define a function generate_recipe(ingredients) that interacts with the OpenAI GPT-3.5 model to generate a recipe based on user-provided ingredients. It constructs a prompt for the AI to create a detailed recipe.

def generate_recipe(ingredients):
        response =
                    "role": "system",
                    "content": "You are a helpful recipe assistant"
                    "role": "user",
                    "content": f"Provide a recipe based on the following ingredients: {ingredients}. Make all the title Bold and do not use # * and give content in an organized and readable manner"
        return response['choices'][0]['message']['content']
    except Exception as e:
        return f"An error occurred: {str(e)}"

Step 3: Flask Application Setup

Initialize the Flask application (app = Flask(__name__)). Define two routes:

  • '/': Handles both GET and POST requests. On POST, it retrieves ingredients from a form submission, calls generate_recipe() with the ingredients, and renders the generated recipe on the HTML page.
  • '/generate': Specifically handles POST requests for generating recipes, invoking generate_recipe() and returning the generated content.
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    output = ""
    if request.method == 'POST':
        ingredients = request.form['ingredients']
        output = generate_recipe(ingredients)
    return render_template_string('''
    <!DOCTYPE html>
        <title>Custom Recipe Generator</title>
        <link href="" rel="stylesheet">
            /* Your CSS styles here */
        async function generateRecipe() {
            // JavaScript function to handle form submission and display output
        function copyToClipboard() {
            // JavaScript function to copy generated recipe to clipboard
        <div class="container">
            <!-- HTML content for form submission and displaying recipe output -->
    ''', output=output)

@app.route('/generate', methods=['POST'])
def generate():
    ingredients = request.form['ingredients']
    content = generate_recipe(ingredients)
    return content

if __name__ == '__main__':'', port=8080)

Step 4: HTML Template and JavaScript

Your HTML template (index.html) integrates Bootstrap for styling, includes a form for users to input ingredients, and displays the generated recipe output. JavaScript functions handle form submission (generateRecipe()) and copying the recipe to the clipboard (copyToClipboard()).

Step 5: Running the Application

To run the application, execute the Python script. Flask will serve the application on http://localhost:8080/ by default.

hii @shreyashkanodia

Sure, here’s a short explanation of setting up the custom recipe generator:

Setting Up the Custom Recipe Generator

Step 1: Imports and API Key Configuration

  • Import necessary modules (openai, os, sys, Flask).
  • Set up your OpenAI API key from environment variables. If the key is missing, an error message guides the user on how to set it up.

Step 2: Flask Application Setup

  • Initialize the Flask app.
  • Define the '/' route to handle GET and POST requests, retrieving ingredients from a form, generating a recipe, and rendering the recipe.
  • Define the '/generate' route to handle POST requests specifically for generating recipes.

Step 3: HTML Template and JavaScript

  • Use Bootstrap for styling.
  • Create a form for inputting ingredients and display the generated recipe.
  • Include JavaScript functions to handle form submission and copying the recipe to the clipboard.

Step 4: Running the Application

  • Run the Python script.
  • Flask serves the application on http://localhost:8080/ by default.