Introduction to Generative AI with Python

Welcome to the quirky world of Generative AI (GenAI) — where machines can write poems, generate code, compose music, and even roast your poorly written Python scripts! 😂
In this blog, we’ll dive into what GenAI is, how it works, and how you can build your first ever GenAI app in Python, with a humorous twist. Don’t worry — we’ll hold your hand through every step. Let’s gooo! 🧠🐍
🧠 What is Generative AI?
Generative AI is a type of artificial intelligence that can generate new content — text, images, music, code, jokes, tweets, and even excuses for not doing homework. It learns patterns from existing data and creates something new and original-ish.
“It’s like teaching Jethalal how to code — and suddenly he builds an AI that only responds to Babita ji’s voice commands.” 💻❤️
🛠️ Tech Stack
Tool | Purpose |
Python | Language of the AI wizards 🐍 |
OpenAI API | Brain behind the chatbot 🤯 |
Flask | Light web framework to serve your AI 🍰 |
HTML/CSS | Make it look somewhat pretty 🎨 |
pip | Your friendly neighborhood package installer 📦 |
💻 Software Requirements
Python 3.8 or higher 🐍
pip (comes with Python)
A browser (Chrome, Firefox, Brave... even Internet Explorer if you're feeling brave 🧨)
OpenAI account with API key 🔑 (https://platform.openai.com/)
🧠 Generative AI Key Concepts Explained Simply
🔤 1. Tokenization – “Breaking Language Into Lego Blocks”
What is it?
Tokenization splits text into small pieces (tokens) that a model can understand. These tokens could be:Words:
["Hello", "world"]
Subwords:
["Hel", "lo", "world"]
Even characters or bytes
Funny Example:
pythonCopy codesentence = "Jethalal loves Babita"
tokens = ["Jeth", "al", "al", " loves", " Bab", "ita"]
The model doesn’t see full words. It sees funky little pieces like " Bab"
and "ita"
, but it remembers what those mean.
📦 2. Vector Embedding – “Meaning Behind the Madness”
What is it?
Embeddings convert tokens into vectors (numbers) that represent meaning. Words with similar meanings get similar vectors.
Example:
"king"
→[0.23, 0.88, -0.51]
"queen"
→[0.20, 0.91, -0.48]
They're close in vector space – just like Jethalal is always close to… Babita ji 😅
Python Simulation:
pythonCopy codeimport numpy as np
word = "hello"
embedding = np.random.rand(3) # Just for demo
print(f"Embedding of '{word}':", embedding)
🔁 3. Self-Attention – “Who Should I Pay Attention To?”
What is it?
In a sentence, not all words are equally important. Self-attention lets the model decide which words to focus on when processing each word.
Example Sentence:
"Jethalal gave flowers to Babita."
When generating "Babita", the model pays special attention to:
"gave"
"flowers"
"Jethalal" 👀
Because that context is important.
Analogy:
Imagine you're in a classroom, and the teacher (Transformer) is asking:
"Hey, which students (words) should I listen to the most for answering this question?"
Each word attends to other words — hence self-attention.
⚙️ Internals: How Self-Attention Works
It calculates 3 vectors per word:
Query (Q)
Key (K)
Value (V)
And performs:
vbnetCopy codeAttention Score = Q · K.T
Softmax to get weights
Then: Output = weights × V
🧠 Don’t worry if this math feels scary — just remember:
“It figures out what’s important to focus on, based on context.”
🧪 Step-by-Step: Let's Make a "Dad Joke Generator" using GenAI
🔍 Step 1: Set up your environment
bashCopy codemkdir genai-dadjokes
cd genai-dadjokes
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install openai flask python-dotenv
🔐 Step 2: Get your OpenAI API Key
Go to platform.openai.com
Copy your API key
Create a
.env
file:
envCopy codeOPENAI_API_KEY=your-secret-api-key-here
🧠 Step 3: Write the Python backend
Create app.py
:
pythonCopy codeimport openai
from flask import Flask, request, jsonify
from dotenv import load_dotenv
import os
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
app = Flask(__name__)
@app.route("/joke", methods=["GET"])
def generate_joke():
prompt = "Tell me a dad joke about computers."
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": prompt}
],
temperature=0.8,
max_tokens=50,
)
joke = response['choices'][0]['message']['content']
return jsonify({"joke": joke.strip()})
if __name__ == "__main__":
app.run(debug=True)
🎨 Step 4: Create a funny frontend
Make templates/index.html
:
htmlCopy code<!DOCTYPE html>
<html>
<head>
<title>😂 AI Dad Joke Generator</title>
</head>
<body style="text-align: center; margin-top: 100px;">
<h1>👨🦳 Dad Jokes by AI</h1>
<button onclick="getJoke()">Get a Joke</button>
<p id="joke" style="font-size: 20px; margin-top: 20px;"></p>
<script>
async function getJoke() {
const res = await fetch('/joke');
const data = await res.json();
document.getElementById('joke').innerText = data.joke;
}
</script>
</body>
</html>
Update Flask to serve HTML:
pythonCopy codefrom flask import Flask, request, jsonify, render_template
# Replace your `generate_joke` function file with:
@app.route("/")
def home():
return render_template("index.html")
▶️ Step 5: Run the App
bashCopy codepython app.py
Go to http://localhost:5000
and click the button. Your AI will tell jokes like:
“Why did the computer get cold? Because it left its Windows open.” 💀
🤯 Bonus: Make It Roast You Instead
Want your AI to roast your code?
Change the prompt:
pythonCopy codeprompt = "Roast this Python code: print('Hello world')"
Get responses like:
“That code is so basic, even your calculator rolled its eyes.” 🔥
📘 Summary
You just:
🧠 Learned what GenAI is
💻 Set up a Python + Flask app
😂 Built a dad-joke generator using OpenAI’s GPT
🔥 Had a laugh while learning
🚀 What’s Next?
Add user authentication (for tracking who made the worst joke)
Try image generation with DALL·E
Save jokes in a database
Deploy on Render, Railway, or Vercel!
✨ Final Thoughts
Generative AI is not just powerful — it’s fun, engaging, and full of potential. Whether you want to build chatbots, creative apps, or even joke-telling robots, Python + OpenAI is your golden ticket 🎫
Now go forth and code… and maybe don’t let the AI roast you too hard. 🤖🔥
Subscribe to my newsletter
Read articles from Rameshwar Mane directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
