1.06 – Build Your First AI App | AI Course

šŸš€ 1.06 – Build Your First AI App

šŸ“‘ On this page

šŸŽÆ Project: AI Text Summarizer

šŸ“Œ What we're building

We'll build a web application that takes long text input and returns an AI-generated summary using OpenAI's GPT-4 API. This teaches: API calls, prompt engineering, web interface, and deployment.

šŸ’” Why this project?

šŸ› ļø Environment Setup

Step 1: Install prerequisites
# Install Python (3.9 or higher) from python.org

# Create a project folder
mkdir ai-summarizer
cd ai-summarizer

# Create a virtual environment (Windows)
python -m venv venv
venv\Scripts\activate

# Create a virtual environment (Mac/Linux)
python3 -m venv venv
source venv/bin/activate

# Install required packages
pip install openai python-dotenv flask
Step 2: Get your OpenAI API key
# 1. Sign up at platform.openai.com
# 2. Go to API keys → Create new key
# 3. Copy your key (starts with "sk-")
# 4. NEVER commit it to GitHub (add .env to .gitignore)
Step 3: Create environment variables
# Create a file named .env
OPENAI_API_KEY=sk-your-actual-api-key-here

šŸ’» CLI Version (Command Line)

Create `summarize_cli.py`
import os
from dotenv import load_dotenv
from openai import OpenAI

# Load environment variables
load_dotenv()

# Initialize the OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def summarize_text(text, max_length=150):
    """
    Summarize a given text using OpenAI's API.
    
    Args:
        text: The text to summarize
        max_length: Approximate length of summary in words
    
    Returns:
        The generated summary as a string
    """
    prompt = f"""
You are a helpful assistant that summarizes text.

Summarize the following text in {max_length} words or less.
Keep the key points and main ideas. Write in clear English.

TEXT TO SUMMARIZE:
{text}

SUMMARY:
"""
    
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": "You are a text summarization assistant."},
            {"role": "user", "content": prompt}
        ],
        temperature=0.5,
        max_tokens=500
    )
    
    return response.choices[0].message.content.strip()

def main():
    print("=" * 60)
    print("šŸ¤– AI Text Summarizer")
    print("=" * 60)
    
    print("\nEnter your text below. Press Ctrl+D (Mac/Linux) or Ctrl+Z (Windows) to finish.\n")
    
    # Read multi-line input
    lines = []
    try:
        while True:
            line = input()
            lines.append(line)
    except EOFError:
        pass
    
    text = "\n".join(lines)
    
    if not text.strip():
        print("No text provided. Goodbye!")
        return
    
    print("\nšŸ“ Original text length:", len(text), "characters")
    print("šŸ¤” Generating summary...\n")
    
    try:
        summary = summarize_text(text)
        print("=" * 60)
        print("šŸ“‹ SUMMARY:")
        print("=" * 60)
        print(summary)
        print("\n" + "=" * 60)
        print(f"šŸ“Š Summary length: {len(summary)} characters")
    except Exception as e:
        print(f"āŒ Error: {e}")
        print("Make sure your API key is set correctly.")

if __name__ == "__main__":
    main()
Run the CLI version:
python summarize_cli.py
# Then type or paste your text
# On Windows: Press Ctrl+Z then Enter to finish
# On Mac/Linux: Press Ctrl+D to finish

🌐 Web Version (Flask)

Create `app.py` (Flask Web Application)
import os
from dotenv import load_dotenv
from openai import OpenAI
from flask import Flask, render_template_string, request, jsonify

# Load environment variables
load_dotenv()

# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# Create Flask app
app = Flask(__name__)

# HTML template with simple form
HTML_TEMPLATE = '''



    
    
    AI Text Summarizer
    


    

šŸ¤– AI Text Summarizer

Paste any text and get an AI-generated summary using GPT-4

šŸ“„ Input Text

0 characters

šŸ“‹ Summary

Your summary will appear here...
šŸ’” Tip: For best results, paste at least 500-1000 characters. The AI will capture the key points.
šŸ“– Load example text
''' def summarize_text(text): """Summarize the given text using OpenAI API.""" prompt = f"""Please summarize the following text concisely. Capture the key points and main ideas. Keep the summary clear and well-structured. TEXT: {text} SUMMARY:""" response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a helpful assistant that summarizes text concisely and clearly."}, {"role": "user", "content": prompt} ], temperature=0.5, max_tokens=500 ) return response.choices[0].message.content.strip() @app.route('/') def home(): return render_template_string(HTML_TEMPLATE) @app.route('/summarize', methods=['POST']) def summarize(): try: data = request.get_json() text = data.get('text', '') if not text.strip(): return jsonify({'error': 'No text provided'}), 400 summary = summarize_text(text) return jsonify({'summary': summary}) except Exception as e: return jsonify({'error': str(e)}), 500 if __name__ == '__main__': print("=" * 60) print("šŸš€ AI Text Summarizer") print("=" * 60) print("\nStarting web server...") print("Open your browser and go to: http://localhost:5000") print("\nPress Ctrl+C to stop the server\n") app.run(debug=True, host='0.0.0.0', port=5000)
Run the web application:
python app.py
# Then open your browser to http://localhost:5000
šŸ’” Testing your app:

ā˜ļø Deployment Options

šŸ“Œ Deploy to the cloud (free options):
Deploy to Render (free) – Step by Step:
# 1. Create a requirements.txt file
flask==2.3.0
openai==1.0.0
python-dotenv==1.0.0

# 2. Create a Procfile (no extension)
web: gunicorn app:app

# 3. Create a .gitignore file
venv/
__pycache__/
.env
*.pyc

# 4. Push to GitHub
git init
git add .
git commit -m "First commit"
git remote add origin YOUR_GITHUB_URL
git push -u origin main

# 5. On Render: New Web Service → Connect GitHub → Set Environment Variable
# Add OPENAI_API_KEY with your key value

āœļø Exercises

Exercise 1.06.1 – Modify the prompt

Change the summarization prompt in the code. Try different styles:

Example prompts to try:
1) "Summarize the following text in exactly 3 bullet points. Each bullet point should be one sentence."
2) "Explain the following text like I'm 5 years old. Use simple words and short sentences."
3) "Summarize and extract 5 key technical terms with brief definitions."
Exercise 1.06.2 – Add a "Copy to Clipboard" button

Add a JavaScript button that copies the summary text to the user's clipboard.

Add after the summary paragraph:
<button onclick="copySummary()" style="margin-top:10px;">šŸ“‹ Copy Summary</button>
JavaScript to add:
function copySummary() { const summaryText = document.querySelector('#resultArea p')?.innerText; if (summaryText) { navigator.clipboard.writeText(summaryText); alert('Copied to clipboard!'); } }
Exercise 1.06.3 – Extend the app

Add a second feature to your app. Ideas:

Add translation endpoint:
def translate_text(text, target_language="Spanish"):
prompt = f"Translate the following text to {target_language}: {text}"
Then add a button and call this function. Same pattern as summarization!
šŸŽ‰ Congratulations – You've built an AI application!

You now know how to:

šŸ“˜ Level 1 Complete!

You've finished Level 1 of the AI course. You can now:

Next: Level 2 – Practitioner (coming soon)