Session 4 – Extending to Building End-to-End AI Applications

Objective

In this session, we’ll combine everything we’ve learned to build a complete AI application. By the end, you’ll know how to integrate Generative AI with user interfaces, APIs, and backend systems to create a functional, interactive tool. ????


Part 1: Overview of an AI Application Architecture

Components of an AI Application

  1. Frontend: The user interface (e.g., a web page or mobile app).
  2. Backend: Handles logic, connects the AI model, and processes data.
  3. AI Model: Provides predictions or generates outputs based on user input.
  4. Database (Optional): Stores user preferences, logs, or historical data.

Example Project: Recipe Generator

Let’s build a simple AI-powered Recipe Generator where users input available ingredients, and the app generates recipe suggestions.


Part 2: Project Setup

Tools and Libraries

  1. Frontend: HTML, CSS, JavaScript (or Streamlit for simplicity).
  2. Backend: Python (using Flask or FastAPI).
  3. AI Model: Hugging Face transformers or OpenAI API.

Part 3: Hands-On Development

Step 1: Setting Up the Backend

We’ll use Flask to handle user requests and connect to the AI model.

Code: Backend for Recipe Generator

from flask import Flask, request, jsonify
from transformers import pipeline

# Initialize the Flask app
app = Flask(__name__)

# Load the pre-trained AI model
recipe_generator = pipeline("text-generation", model="gpt2")

@app.route('/generate', methods=['POST'])
def generate_recipe():
    # Get user input from the request
    data = request.json
    ingredients = data.get("ingredients", "")

    # Generate a recipe
    prompt = f"Create a recipe using these ingredients: {ingredients}"
    response = recipe_generator(prompt, max_length=100, num_return_sequences=1)

    # Send the generated recipe as a response
    return jsonify({"recipe": response[0]["generated_text"]})

if __name__ == '__main__':
    app.run(debug=True)

Step 2: Creating a Simple Frontend

For the frontend, let’s use basic HTML and JavaScript to take user input and display the generated recipe.

Code: HTML Frontend

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Recipe Generator</title>
</head>
<body>
    <h1>AI Recipe Generator</h1>
    <form id="recipe-form">
        <label for="ingredients">Enter your ingredients:</label><br>
        <textarea id="ingredients" rows="4" cols="50"></textarea><br><br>
        <button type="submit">Generate Recipe</button>
    </form>
    <h2>Generated Recipe:</h2>
    <p id="output"></p>

    <script>
        document.getElementById('recipe-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const ingredients = document.getElementById('ingredients').value;

            const response = await fetch('http://127.0.0.1:5000/generate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ingredients })
            });

            const result = await response.json();
            document.getElementById('output').innerText = result.recipe;
        });
    </script>
</body>
</html>

Step 3: Running the Application

  1. Start the Backend:

Run the Flask app in your terminal.

python app.py
  1. Open the Frontend:Save the HTML file and open it in your browser.
  2. Test the Application:
    • Input ingredients like eggs, tomatoes, cheese.
    • Click “Generate Recipe” and watch the magic! ✨

keyboard_arrow_down

Part 4: Enhancing the Application

Adding Features

  1. Save Recipes: Add a database to store generated recipes.
    • Use SQLite for simplicity or connect to a cloud database like Firebase.
  2. User Authentication: Allow users to log in and save their preferences.
  3. Improved Frontend: Use frameworks like React or Angular for a polished UI.
  4. Image Generation: Integrate DALLE to generate an image of the recipe.

Step 4: Adding DALLE for Visuals

Enhance the Backend:

@app.route('/generate_image', methods=['POST'])
def generate_image():
    # Use OpenAI API for image generation
    prompt = request.json.get("prompt", "A delicious pasta dish")
    response = openai.Image.create(prompt=prompt, n=1, size="1024x1024")
    image_url = response['data'][0]['url']
    return jsonify({"image_url": image_url})

Part 5: Deployment

Deploying the Application

Creating a live version of your AI application involves hosting the frontend, backend, and integrating them seamlessly. Let’s break it down:

1. Backend Deployment

  • Platform Options: Use HerokuAWS, or Google Cloud Platform to host your Flask app.
  • Steps for Heroku Deployment:

Install Heroku CLI:

 npm install -g heroku

Initialize Git in your project directory:

git init

Create a Procfile to define the app’s entry point:

 web: python app.py

Push the app to Heroku:

heroku create
 git add .
 git commit -m "Initial commit"
 git push heroku main

Open the app:

heroku open

2. Frontend Deployment

  • Use GitHub Pages or Netlify:
    • Upload your HTML, CSS, and JavaScript files to GitHub.
    • Use GitHub Pages to serve your static files:
      1. Go to your repository Settings.
      2. Under “Pages,” select the branch with your frontend files.
    • Alternatively, deploy using Netlify for enhanced features like custom domains.

3. Connecting Frontend and Backend

  • Update the frontend JavaScript to point to the deployed backend URL instead of localhost. Example:
 const response = await fetch('https://your-backend-url.com/generate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ingredients })
  });

4. Securing API Keys

  • Store sensitive keys in environment variables using tools like dotenv or platform-specific configurations.
    • Example for Flask:
import os
openai.api_key = os.getenv('OPENAI_API_KEY')

5. Testing the Deployment

  • Access the live app from any device and test the functionality. Share the link with your class for feedback.

Part 6: Wrap-Up & Reflection

Key Takeaways

  • End-to-End Workflow: Connected the frontend, backend, and AI model.
  • Hands-On Practice: Built a functional Recipe Generator.
  • Deployment Insights: Learned about hosting and securing an AI application.

Activity: Personalize Your App

  1. Modify the app to generate workout plans or motivational quotes.
  2. Share your project with the class and discuss your experience.

arrow_upwardarrow_downwardlinkcommenteditdeletemore_vert

Double-click (or enter) to edit