Career

Generative AI Tutorial for Beginners with Examples

A generative AI tutorial for beginners: how models generate text, temperature, prompts, safe API calls, JSON output, simple retrieval and testing, in Python.

rag_helper.py1def best_notes(question, notes):2 q = words(question)3 # find the closest note4reply = ask_model(prompt)5check(reply) # never trust blindly
  • AI
  • Python
  • Tutorial
  • Freshers

Quick answer: Generative AI models create new text, images or code by predicting the next piece, one step at a time, from patterns learned in training. To learn generative AI as a beginner, start with Python, then understand tokens and temperature, write clear prompts, call a model through one function, check its output, ground answers in your own data with retrieval, and test the app on a small set of questions.

This generative AI tutorial teaches the ideas by building them. It assumes no earlier AI knowledge, so it works as generative AI for beginners. You will write a tiny text generator, see what temperature does, write a prompt template, wrap a model call safely, check the reply, add simple retrieval and test the whole thing.

Every example runs in plain Python with no API key. Most of the work in a real app is the code around the model, and you can practise all of it on your laptop.

What is generative AI?

Generative AI is software that produces new content: text, images, audio or code. A large language model (LLM) is the kind that works with text.

An LLM reads your input as tokens, which are small pieces of words. It then predicts a likely next token, adds it to the text and repeats. It learned which tokens tend to follow which from a very large amount of training text.

This explains why a model writes fluent sentences, and also why it can state wrong facts confidently: it predicts likely text, not checked truth. This is called hallucination.

Term Meaning in one line
Token A small piece of text the model reads and writes
Prompt The input you send to the model
Context window The maximum number of tokens the model can handle in one request
Temperature A setting that controls how random the output is
Embedding A list of numbers that represents the meaning of a text
RAG Retrieval-augmented generation: find relevant text first, then ask the model to answer from it

Step 1: Set up Python

Install Python 3.10 or newer. Create a folder for this tutorial and a virtual environment inside it:

python -m venv venv

Activate it with venv\Scripts\activate on Windows or source venv/bin/activate on macOS and Linux. The examples use only the standard library. If functions, loops and dictionaries still feel hard, do our Python basics tutorial first.

Step 2: Build a tiny text generator

Real LLMs use neural networks with billions of numbers. You can still see the core idea, predict the next word and repeat, with a dictionary.

import random
from collections import defaultdict

text = (
    "the student opens the laptop . the student writes code . "
    "the trainer reviews the code . the student fixes the code ."
)

words = text.split()
next_words = defaultdict(list)
for current, following in zip(words, words[1:]):
    next_words[current].append(following)

print(next_words["the"])

random.seed(7)
word = "the"
output = [word]
for _ in range(6):
    word = random.choice(next_words[word])
    output.append(word)
print(" ".join(output))

Output (the second line may differ on your machine):

['student', 'laptop', 'student', 'trainer', 'code', 'student', 'code']
the student opens the student opens the

After "the", "student" appears three times out of seven, so it is the most likely next word. This generator looks at only one previous word, so it soon repeats itself. An LLM looks at thousands of previous tokens, but the principle is the same.

Step 3: See what temperature does

A model gives each possible next token a score. A function called softmax turns scores into probabilities. Temperature divides the scores before softmax.

import math

def softmax(scores, temperature=1.0):
    scaled = [s / temperature for s in scores]
    biggest = max(scaled)
    exps = [math.exp(s - biggest) for s in scaled]
    total = sum(exps)
    return [round(e / total, 2) for e in exps]

scores = [2.0, 1.0, 0.5]   # code, laptop, tea
print(softmax(scores, 0.5))
print(softmax(scores, 1.0))
print(softmax(scores, 2.0))

Output:

[0.84, 0.11, 0.04]
[0.63, 0.23, 0.14]
[0.48, 0.29, 0.23]

At a low temperature the top word ("code") wins almost every time, so output is steady. At a high temperature the other words get more chances, so output varies more. Subtracting biggest does not change the result; it only stops math.exp from overflowing on large scores.

Note: Some newer models and APIs fix the sampling settings or do not accept a temperature value at all. Check your provider's documentation. The idea is still worth knowing for interviews.

Step 4: Write a clear prompt

A good prompt states the task, gives the context, asks the question and says what shape the answer should take. Put it in a function so the wording is in one place.

def build_prompt(task, context, question, output_format):
    return (
        f"Task: {task}\n"
        f"Context:\n{context}\n"
        f"Question: {question}\n"
        f"Answer format: {output_format}\n"
        'If the context does not contain the answer, reply "I do not know".'
    )

prompt = build_prompt(
    task="Answer questions about the college library.",
    context="Books can be kept for 14 days. The fine is Rs 2 per day.",
    question="What is the fine for a late book?",
    output_format="One short sentence.",
)
print(prompt)

Output:

Task: Answer questions about the college library.
Context:
Books can be kept for 14 days. The fine is Rs 2 per day.
Question: What is the fine for a late book?
Answer format: One short sentence.
If the context does not contain the answer, reply "I do not know".

The last line gives the model a safe way out, which reduces made-up answers.

Step 5: Call the model through one function

Your app should not care which company made the model. Pass the model call in as a function. In tests you pass a fake; in production you pass a real one.

import os

def fake_model(prompt):
    return "The fine is Rs 2 per day."

def answer(question, ask_model):
    question = question.strip()
    if not question:
        return "Please type a question."
    if len(question) > 300:
        return "Please keep your question under 300 characters."
    return ask_model(question).strip()

print(answer("What is the fine?", fake_model))
print(answer("   ", fake_model))

api_key = os.environ.get("LLM_API_KEY")
print("Key found" if api_key else "Set LLM_API_KEY before calling a real model")

Output (when no key is set):

The fine is Rs 2 per day.
Please type a question.
Set LLM_API_KEY before calling a real model

The real ask_model is a few lines that use your provider's official Python SDK. Install the SDK, follow its quick-start for the current model names and method names, and read the key from an environment variable as shown. LLM_API_KEY is just the name used in this tutorial; each SDK documents the variable it reads by default.

Common mistake: Pasting an API key into your code and pushing it to GitHub. Bots scan public repositories for keys within minutes. Keep keys in environment variables or a .env file listed in .gitignore.

Step 6: Ask for JSON and check it

When code will use the reply, ask the model for JSON and then check it. Treat the reply like a form filled in by a stranger.

import json

ALLOWED = {"fees", "timings", "syllabus", "other"}

def parse_reply(reply):
    try:
        data = json.loads(reply)
    except json.JSONDecodeError:
        return {"topic": "other", "urgent": False}
    topic = str(data.get("topic", "other")).lower()
    if topic not in ALLOWED:
        topic = "other"
    urgent = data.get("urgent") is True
    return {"topic": topic, "urgent": urgent}

print(parse_reply('{"topic": "Fees", "urgent": true}'))
print(parse_reply('{"topic": "hostel", "urgent": "yes"}'))
print(parse_reply("Sure! The topic is fees."))

Output:

{'topic': 'fees', 'urgent': True}
{'topic': 'other', 'urgent': False}
{'topic': 'other', 'urgent': False}

The second reply uses an unknown topic and "yes" instead of true. The third is not JSON at all. Both fall back to a safe value instead of crashing. Many providers offer a structured output mode that enforces a schema; keep the check anyway.

Step 7: Ground answers with simple retrieval

An LLM does not know your college rules or your company's documents. RAG fixes this: find the most relevant notes first, then put them in the prompt as context. Here is the retrieval half, using word overlap.

import re

STOP = {"the", "is", "a", "an", "at", "on", "to", "of", "and", "does", "when", "who", "what"}

notes = {
    "library": "Books can be kept for 14 days. The fine is Rs 2 per day.",
    "canteen": "The canteen opens at 8 am and closes at 6 pm.",
    "lab": "The computer lab is open from 9 am to 5 pm on weekdays.",
}

def words(text):
    return set(re.findall(r"[a-z0-9]+", text.lower())) - STOP

def best_notes(question, notes, top_k=1):
    q = words(question)
    scored = []
    for name, text in notes.items():
        overlap = len(q & words(text))
        scored.append((overlap, name))
    scored.sort(reverse=True)
    return [name for score, name in scored[:top_k] if score > 0]

print(best_notes("Is the computer lab open on weekdays?", notes))
print(best_notes("What is the late fine?", notes))
print(best_notes("Who won the match?", notes))

Output:

['lab']
['library']
[]

The empty list for the cricket question lets your app say "I do not know" without calling the model. The STOP set removes common words that would make every note look relevant.

Now try best_notes("When does the canteen open?", notes). It returns ['lab'], because the question says "open" but the canteen note says "opens". Exact word matching misses meaning. Real systems use embeddings, which place "open" and "opens" close together, and store them in a vector database. The flow stays the same: retrieve, build the prompt with the notes, call the model, check the reply.

Step 8: Test with a small question set

You cannot judge an AI app by trying three questions by hand. Write the questions and what a good answer must contain, then run them after every change.

tests = [
    ("What is the late fine?", "Rs 2"),
    ("When does the canteen close?", "6 pm"),
    ("Who is the principal?", "I do not know"),
]

def fake_app(question):
    replies = {
        "What is the late fine?": "The fine is Rs 2 per day.",
        "When does the canteen close?": "It closes at 6 pm.",
        "Who is the principal?": "The principal is Dr. Rao.",
    }
    return replies[question]

passed = 0
for question, must_contain in tests:
    reply = fake_app(question)
    ok = must_contain.lower() in reply.lower()
    passed += ok
    print("PASS" if ok else "FAIL", "|", question)
print(f"{passed}/{len(tests)} passed")

Output:

PASS | What is the late fine?
PASS | When does the canteen close?
FAIL | Who is the principal?
2/3 passed

The third test caught a hallucination: the notes never named a principal. Grow this list to 20 or 30 questions, including empty input and questions your data cannot answer. Our generative AI best practices explain how to score retrieval and answers separately.

Generative AI examples you can relate to

Use What the model does What your code must add
College help desk Answers from rules and notices Retrieval, "I do not know" handling
Resume feedback Suggests clearer bullet points Privacy checks, no invented experience
Support ticket sorting Picks a category and urgency JSON checks, allowed values
Meeting notes Summarises a long transcript Length limits, human review
Code helper Explains or drafts code Running tests before trusting it

More cases from real companies are in generative AI real-time examples.

Practice tasks

  1. Run Step 3 with a temperature of 0.1 and 5.0. Explain the result in one line.
  2. In Step 6, also reject a reply whose JSON has extra keys.
  3. Add two more notes in Step 7 and two matching tests in Step 8.

Solutions to similar exercises are in our generative AI practice problems.

Where to go after this generative AI tutorial

Join Steps 4 to 8 into one small app and put it on GitHub with a README and your test results. Then pick a project from 12 generative AI project ideas and follow the GenAI stages of the AI engineer roadmap. Keep the generative AI cheat sheet open for revision.

If you want a structured, project-based path through machine learning, deep learning, LLMs, RAG and agents, see our Artificial Intelligence course guide.

Frequently asked questions

Do I need machine learning before I learn generative AI?

Not to start. You can build useful apps with Python, prompts and an API. You will understand the models much better if you later learn machine learning basics such as training, testing and overfitting, so plan to study them alongside.

Do I need a paid API key to follow this tutorial?

No. Every code example here runs offline in plain Python. A fake model function stands in for the real one. When you are ready, you replace that one function with a call to your chosen provider's official SDK and read the key from an environment variable.

Which programming language is best for generative AI?

Python is the most common choice because most AI libraries and examples use it. JavaScript is also used for web apps that call models. If you are a beginner, learn Python first.

What is the difference between generative AI and traditional AI?

Traditional machine learning usually predicts a label or a number, such as spam or not spam. Generative AI produces new content, such as a paragraph, a summary or a piece of code. Both learn from data.

How long does it take to learn generative AI basics?

With Python already in place and about two hours a day, most beginners can build a small, tested app in six to eight weeks. Without Python, add six to eight weeks at the start.


Not sure where your AI skills stand? Book a free demo class and build a small project with a trainer, or explore the Artificial Intelligence course.

Found this useful? Share it: LinkedIn Facebook WhatsApp

Written by

Siva Prasad Galaba

Staff Engineer & Founder, CodeBegun

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaching the next generation to code the way the industry actually works.

Back to all articles
Chat with us