Understanding Modern AI From Basics to Advanced

An interactive journey through Artificial Intelligence, Large Language Models, AI Agents, Fine-Tuning, RAG, and more โ€” with visual diagrams, real examples, and hands-on demos.

0Topics
0+Visual Diagrams
0+Reference Links
Scroll to explore

Your Learning Path

Follow this roadmap from AI fundamentals to advanced techniques

๐Ÿค–

AI Fundamentals

What is AI? Types, history, and core concepts

Explore โ†’
๐Ÿ“

Large Language Models

How LLMs work, transformers, tokens, and training

Explore โ†’
โš–๏ธ

Open vs Closed Models

Comparing open-source and proprietary AI models

Explore โ†’
๐Ÿ•ต๏ธ

AI Agents

Autonomous systems that reason, plan, and act

Explore โ†’
๐Ÿ”ง

Fine-Tuning

Customizing models for specific tasks and domains

Explore โ†’
๐Ÿ“š

RAG

Retrieval-Augmented Generation for grounded AI

Explore โ†’
๐Ÿš€

Hands-On Labs

Interactive demos and playground experiments

Explore โ†’
Chapter 1

What is Artificial Intelligence?

The science of making machines think, learn, and act intelligently

Definition

Artificial Intelligence (AI) is a branch of computer science focused on building systems that can perform tasks typically requiring human intelligence โ€” such as understanding language, recognizing images, making decisions, and learning from experience.

๐Ÿ“… Brief History of AI

1950

Alan Turing's "Computing Machinery and Intelligence"

Turing proposes the Turing Test โ€” a benchmark for machine intelligence.

1956

Dartmouth Conference

The term "Artificial Intelligence" is coined. The field is officially born.

1966

ELIZA Chatbot

One of the first natural language processing programs created at MIT.

1997

Deep Blue beats Kasparov

IBM's chess computer defeats the world champion, showcasing computational AI power.

2012

Deep Learning Revolution

AlexNet wins ImageNet, igniting the deep learning era with neural networks.

2017

Transformer Architecture

Google's "Attention Is All You Need" paper revolutionizes NLP and AI.

2022

ChatGPT Launch

OpenAI releases ChatGPT, bringing LLMs to mainstream adoption worldwide.

2024-26

Agentic AI & Multimodal Models

AI agents, reasoning models, and multimodal systems become the frontier.

๐Ÿ—๏ธ Types of AI

Narrow AI (ANI)

Current State

Specialized in one task. Most AI today falls here.

  • ChatGPT / Claude (text generation)
  • DALL-E / Midjourney (image generation)
  • Siri / Alexa (voice assistants)
  • Self-driving car perception systems
  • Spam filters and recommendation engines

General AI (AGI)

Theoretical

Human-level intelligence across all domains.

  • Can learn any intellectual task a human can
  • Transfer knowledge between domains
  • Reason abstractly and creatively
  • Currently does not exist
  • Active area of research and debate

Super AI (ASI)

Hypothetical

Surpasses all human intelligence combined.

  • Exceeds human cognitive abilities in every way
  • Could solve currently unsolvable problems
  • Raises significant ethical and safety concerns
  • Purely theoretical / science fiction
  • Topic of AI safety research

๐Ÿงฉ AI, ML, DL โ€” How They Relate

Artificial Intelligence
Machine Learning
Deep Learning
Generative AI
AI โ€” Any technique enabling machines to mimic human behavior
ML โ€” Algorithms that learn from data without explicit programming
DL โ€” Neural networks with many layers (deep neural nets)
GenAI โ€” Models that generate new content (text, images, code)

๐Ÿ“Š Types of Machine Learning

How it Works

The model learns from labeled data โ€” input-output pairs where the correct answer is provided during training.

Real-World Examples

  • Email spam detection: trained on emails labeled "spam" or "not spam"
  • Medical diagnosis: X-rays labeled with diseases
  • Price prediction: housing data with known prices
Input Data
(Images, Text)
โ†’
Model
(Learns patterns)
โ†’
Prediction
(Labels, Values)
Known Labels โ†‘

How it Works

The model finds hidden patterns in data without any labels. It discovers structure on its own.

Real-World Examples

  • Customer segmentation: grouping similar customers for marketing
  • Anomaly detection: finding unusual transactions (fraud)
  • Topic modeling: discovering themes in documents
Raw Data
(No labels)
โ†’
Model
(Finds patterns)
โ†’
Clusters
(Groups, Patterns)

How it Works

An agent learns by interacting with an environment, receiving rewards or penalties for its actions.

Real-World Examples

  • Game playing: AlphaGo defeating Go world champion
  • Robotics: learning to walk and manipulate objects
  • RLHF: training ChatGPT to be helpful using human feedback
Agent
(Makes decisions)
โ†’ Action โ†’
Environment
(Game, Real world)
โ†’ Reward โ†’
Updated Policy
(Better strategy)

How it Works

The model creates its own labels from data โ€” e.g., predicting the next word in a sentence. This is how most LLMs are trained.

Real-World Examples

  • GPT models: predict next token in text sequences
  • BERT: fill in masked words in sentences
  • CLIP: learn image-text relationships from web data
Text Data
"The cat sat on the _"
โ†’
Model
(Predicts missing)
โ†’
Prediction
"mat" (97%)
Chapter 2

Large Language Models (LLMs)

The engines behind modern AI โ€” understanding how they work

What is an LLM?

A Large Language Model is a deep learning model trained on massive amounts of text data. It learns statistical patterns of language to predict, generate, and understand text. Think of it as a powerful autocomplete that has read most of the internet.

โš™๏ธ The Transformer Architecture

At the heart of every modern LLM is the Transformer, introduced in the 2017 paper "Attention Is All You Need" by Google.

Key Components

๐Ÿ“ฅ
Input Embedding

Converts words/tokens into numerical vectors the model can process

๐Ÿ“
Positional Encoding

Adds position information so the model knows word order

๐Ÿ‘๏ธ
Self-Attention

Allows each word to "look at" every other word to understand context

๐Ÿงฎ
Feed Forward Network

Processes attention output through neural network layers

๐Ÿ“ค
Output Layer

Produces probability distribution over vocabulary for next token

Input: "How does AI"
โ†“
Token Embedding + Position
โ†“
Multi-Head Self-Attention
โ†“
Feed Forward Network
ร— N layers (e.g., 96 in GPT-4)
โ†“
Output: "work" (probability: 0.82)

๐Ÿ‘๏ธ Self-Attention โ€” The Key Innovation

Self-attention lets each word attend to all others. Click on words to see attention patterns:

The cat sat on the mat because it was tired

๐Ÿ‘† Click any word to see what it "attends to" (which other words help determine its meaning)

๐Ÿ”ค Tokenization โ€” How LLMs Read Text

LLMs don't read words โ€” they read tokens. A token can be a word, part of a word, or a character.

Hello , how are you ?
Tokens: 6 Characters: 19 Ratio: 3.2 chars/token

๐Ÿ‹๏ธ How LLMs Are Trained

1

Pre-Training

Model is trained on massive text corpus (trillions of tokens from books, websites, code). It learns to predict the next word.

๐Ÿ“Š Data: 1-15 trillion tokens ๐Ÿ’ฐ Cost: $2M-$100M+ โฑ๏ธ Time: weeks-months on thousands of GPUs
2

Supervised Fine-Tuning (SFT)

Model is trained on high-quality demonstration data โ€” human-written examples of helpful, accurate responses.

๐Ÿ“Š Data: ~100K examples ๐ŸŽฏ Goal: Teach instruction-following
3

RLHF (Reinforcement Learning from Human Feedback)

Humans rank model outputs. A reward model is trained on these preferences, then used to improve the LLM via reinforcement learning.

๐Ÿ‘ฅ Human raters compare outputs ๐ŸŽฏ Goal: Align with human preferences

๐Ÿ“ LLM Size Comparison

Model sizes have grown exponentially. Parameters are the learned weights of the model.

๐Ÿ’ก Key LLM Concepts

Temperature

Click to learn more โ†’

Controls randomness. Low (0.0) = deterministic, factual. High (1.0+) = creative, diverse. Like adjusting how "adventurous" the model is.

Context Window

Click to learn more โ†’

Maximum input+output tokens. GPT-4 Turbo: 128K tokens. Claude 3: 200K tokens. Gemini 1.5: 1M+ tokens. Larger = more context the model can "remember."

Hallucination

Click to learn more โ†’

When LLMs generate plausible-sounding but incorrect information. They predict likely text, not truth. This is why RAG and grounding are important.

Prompt Engineering

Click to learn more โ†’

The art of crafting inputs to get better outputs. Techniques include: few-shot examples, chain-of-thought, role-playing, and structured prompts.

Inference

Click to learn more โ†’

Using a trained model to generate outputs. Training is expensive and rare. Inference happens every time you chat with an AI โ€” it's the production usage.

Multimodal

Click to learn more โ†’

Models that handle multiple data types: text + images + audio + video. GPT-4o, Gemini, and Claude 3 are multimodal โ€” they can "see" and "hear."

Chapter 3

Open Source vs Closed Models

Understanding the AI model landscape and choosing the right approach

โš–๏ธ The Great Divide

๐Ÿ”“ Open Source / Open Weight Models
Feature
๐Ÿ”’ Closed / Proprietary Models
Weights publicly available for download
Model Access
API access only, weights are secret
Free to use, modify, and deploy
Cost
Pay-per-token / subscription pricing
Full control โ€” run on your own hardware
Privacy
Data sent to third-party servers
Can fine-tune and customize freely
Customization
Limited fine-tuning through APIs
Competitive but often behind frontier
Performance
Often best-in-class capabilities
Community-driven, rapid innovation
Development
Large teams, significant R&D investment

๐Ÿ—บ๏ธ The AI Model Landscape (2024-2026)

๐Ÿ”“ Open Source / Open Weight

Llama 3.1/4
Meta 8B-405B params

Meta's flagship open model. Highly capable, commercially usable.

Mistral / Mixtral
Mistral AI 7B-8x22B params

European AI lab. Efficient MoE architecture. Strong performance per size.

DeepSeek V3/R1
DeepSeek 67B-671B params

Chinese lab. Strong reasoning. Competitive with frontier closed models.

Falcon / BLOOM
TII / BigScience 7B-180B params

Fully open models with training data transparency.

Phi-3/4
Microsoft 3.8B-14B params

Small but mighty. Designed for edge and mobile deployment.

Qwen 2.5
Alibaba 0.5B-72B params

Multilingual. Strong coding and math capabilities.

๐Ÿ”’ Closed / Proprietary

GPT-4o / o1 / o3
OpenAI Unknown (rumored 1.8T)

Market leader. Multimodal. o-series adds chain-of-thought reasoning.

Claude 3.5 / Opus 4
Anthropic Unknown

Constitutional AI. Excellent at coding, analysis, and long context tasks.

Gemini 2.0
Google DeepMind Unknown

Natively multimodal. 1M+ token context. Deep Google integration.

Grok
xAI Unknown

Elon Musk's AI. Real-time information. Integrated with X/Twitter.

๐Ÿ“Š Model Benchmark Comparison

Performance across common benchmarks (illustrative scores, higher is better):

๐Ÿค” Which Model Should You Choose?

What's your top priority?

You need data privacy. Can you run models on your own servers?

You want peak performance. What's your use case?

You want lowest cost. What scale are you working at?

You want full customization. What kind?

โœ… Recommendation: Self-hosted Open Models

Use Llama 3.1 70B or Mistral Large on your own GPU infrastructure. Full privacy, no data leaves your servers. Tools: vLLM, Ollama, or TGI for serving.

โœ… Recommendation: Private Cloud Deployment

Use Azure OpenAI Service or AWS Bedrock with data processing agreements. Or use Ollama locally for smaller models (Phi-3, Llama 8B).

โœ… Recommendation: Frontier Closed Models

Use GPT-4o / o3 or Claude Opus 4 for the best general reasoning. For math/science, Gemini 2.0 is strong. DeepSeek R1 (open) is a competitor.

โœ… Recommendation: Code-Optimized Models

Claude Opus 4 leads for coding. GPT-4o and DeepSeek Coder (open) are excellent. For fast completion: Codestral (Mistral) or Qwen Coder.

โœ… Recommendation: Multimodal Models

GPT-4o and Gemini 2.0 lead in vision+text. For open models: LLaVA or Llama 3.2 Vision.

โœ… Recommendation: Free & Local Models

Use Ollama to run models locally for free. Try Llama 3.1 8B, Phi-3, or Mistral 7B. For cloud: free tiers of ChatGPT, Claude, or Gemini.

โœ… Recommendation: Open Models + Cloud GPUs

Run Llama 3.1 70B or Mixtral 8x7B on cloud GPUs (Together AI, Fireworks, Replicate). Much cheaper than closed API pricing at scale.

โœ… Recommendation: Fine-tunable Open Models

Start with Llama 3.1 or Mistral. Use LoRA/QLoRA for efficient fine-tuning. Tools: Hugging Face, Axolotl, Unsloth. See the Fine-Tuning chapter below!

โœ… Recommendation: RAG Pipeline

Any model works with RAG! Use LangChain or LlamaIndex with a vector database (Pinecone, Chroma, Weaviate). See the RAG chapter below!

Chapter 4

AI Agents

Autonomous systems that perceive, reason, plan, and act

What is an AI Agent?

An AI Agent is an autonomous system that uses an LLM as its "brain" to perceive its environment, make decisions, use tools, and take actions to achieve goals โ€” often in multi-step workflows without constant human guidance.

๐Ÿ—๏ธ Agent Architecture

๐Ÿง  LLM Brain

Reasoning & Decision Making

๐Ÿ‘๏ธ
Perception

User input, environment observation, tool outputs

๐Ÿ—บ๏ธ
Planning

Break tasks into steps, create strategies

๐Ÿ’พ
Memory

Short-term (context) + Long-term (vector DB)

๐Ÿ”ง
Tools

APIs, code execution, web search, databases

โšก
Action

Execute decisions, interact with world

๐Ÿ”„ The Agent Loop โ€” Think โ†’ Act โ†’ Observe

๐Ÿค”

Think

Analyze input, reason about the task, and plan next action

โ†’
โšก

Act

Execute a tool call, write code, or generate a response

โ†’
๐Ÿ‘๏ธ

Observe

Review the result, check if the goal is achieved

โ†ฉ

User: "What's the weather in Tokyo and should I bring an umbrella?"

๐Ÿท๏ธ Types of AI Agents

๐Ÿ”จ Tool-Using Agents

Call external APIs and tools to complete tasks.

Example: ChatGPT with plugins โ€” searches the web, runs code, generates images.
Tools: Web Search, Code Interpreter, DALL-E, Browser

๐Ÿ—ฃ๏ธ Conversational Agents

Multi-turn dialogue with memory and personality.

Example: Customer service bots that remember conversation history and escalate complex issues.
Tools: Knowledge Base, CRM, Ticket System

๐Ÿ’ป Coding Agents

Write, debug, and refactor code autonomously.

Example: GitHub Copilot Agent, Devin, SWE-Agent โ€” can read entire codebases and make multi-file changes.
Tools: File System, Terminal, Git, LSP, Tests

๐Ÿ”ฌ Research Agents

Gather, analyze, and synthesize information.

Example: Deep Research by OpenAI / Gemini โ€” autonomously researches topics and writes reports.
Tools: Web Search, Document Reader, Citation Manager

๐Ÿ‘ฅ Multi-Agent Systems

Multiple specialized agents collaborating.

Example: CrewAI, AutoGen โ€” a "team" of agents where one plans, one researches, one writes, one reviews.
Tools: Inter-agent communication, Shared memory

๐Ÿ–ฅ๏ธ Computer-Use Agents

Control a computer like a human user.

Example: Anthropic's Computer Use, OpenAI Operator โ€” navigate GUIs, click buttons, fill forms.
Tools: Screenshot, Mouse, Keyboard, Browser

๐Ÿ› ๏ธ Popular Agent Frameworks

๐Ÿฆœ LangChain / LangGraph

Most popular framework. LangGraph adds stateful, graph-based agent workflows.

langchain.com โ†’

๐Ÿค– AutoGen (Microsoft)

Multi-agent conversation framework. Agents debate and collaborate.

autogen docs โ†’

๐Ÿ‘ฅ CrewAI

Role-based multi-agent orchestration. Define agent personas and tasks.

crewai.com โ†’

๐Ÿ Bee Agent (IBM)

Production-ready framework focused on reliability and observability.

GitHub โ†’
Chapter 5

Fine-Tuning

Customizing pre-trained models for your specific needs

What is Fine-Tuning?

Fine-tuning is the process of taking a pre-trained model and further training it on a smaller, specialized dataset to adapt it for specific tasks, domains, or behaviors. Think of it as teaching a well-educated generalist to become a domain expert.

๐Ÿค” When to Fine-Tune vs Other Approaches

1. Prompt Engineering

Cheapest & fastest. Craft better prompts with examples.

Effort: Low | Cost: Free

2. RAG (Retrieval-Augmented Generation)

Add external knowledge without changing the model.

Effort: Medium | Cost: Low

3. Fine-Tuning

Modify model weights for specialized behavior.

Effort: High | Cost: Medium-High

4. Training from Scratch

Build entire model. Only for major labs.

Effort: Extreme | Cost: $Millions

๐Ÿ”ง Fine-Tuning Approaches

Full Fine-Tuning

Updates all model parameters. Most powerful but most expensive.

Conceptual Overview
Pre-trained Model (all params)
    โ”‚
    โ–ผ  Train on your data
    โ”‚
Updated Model (all params modified)

โ€ข Requires: Full GPU memory (VRAM) for model + gradients + optimizer
โ€ข Llama 70B: ~140GB VRAM minimum (4x A100 80GB)
โ€ข Best for: Large datasets, significant behavior changes

LoRA (Low-Rank Adaptation)

Freezes original weights, trains small "adapter" matrices. 99%+ fewer trainable parameters.

How LoRA Works
Original Weight Matrix W (frozen) โ”€โ”€โ”€ W ร— input
                                        +
Low-Rank Matrices Aร—B (trainable) โ”€โ”€ (Aร—B) ร— input

โ€ข Original: 4096ร—4096 = 16.7M parameters
โ€ข LoRA (rank 8): 4096ร—8 + 8ร—4096 = 65K parameters
โ€ข 99.6% parameter reduction!
โ€ข Adapters are tiny (~10-100MB) and swappable
Python Example (Hugging Face PEFT)
from peft import LoraConfig, get_peft_model

lora_config = LoraConfig(
    r=8,                    # Rank of adapter
    lora_alpha=16,          # Scaling factor
    target_modules=["q_proj", "v_proj"],  # Which layers to adapt
    lora_dropout=0.05,
    task_type="CAUSAL_LM"
)

model = get_peft_model(base_model, lora_config)
model.print_trainable_parameters()
# Output: trainable params: 4,194,304 || all params: 6,738,415,616 || 0.06%

QLoRA (Quantized LoRA)

Combines LoRA with 4-bit quantization. Fine-tune a 70B model on a single GPU!

QLoRA Memory Savings
Model: Llama 2 70B

Full Fine-Tuning:     ~140 GB VRAM (4ร— A100)
LoRA (16-bit):         ~70 GB VRAM (2ร— A100)
QLoRA (4-bit + LoRA):  ~20 GB VRAM (1ร— A100 or RTX 4090!)

How: Model weights quantized to 4-bit (NF4)
     while LoRA adapters train in 16-bit precision

RLHF & DPO

Align models with human preferences using feedback or direct preference optimization.

RLHF Pipeline
Step 1: Collect human preference data
   โ†’ Pairs of (prompt, chosen_response, rejected_response)

Step 2 (RLHF): Train a reward model
   โ†’ Then use PPO to optimize the LLM against the reward model

Step 2 (DPO): Skip the reward model
   โ†’ Directly optimize the LLM on preference pairs
   โ†’ Simpler, more stable, increasingly preferred

Tools: trl library (Hugging Face), TRL's DPOTrainer

๐Ÿ“‹ Step-by-Step Fine-Tuning Process

1

Prepare Your Dataset

Format your data as instruction-response pairs. Typically need 100-10,000+ high-quality examples.

Dataset Format (JSON)
{
  "instruction": "Summarize this medical report",
  "input": "Patient presents with acute bronchitis...",
  "output": "The patient has acute bronchitis with symptoms..."
}
2

Choose Base Model & Approach

Pick a base model (e.g., Llama 3.1 8B) and PEFT method (LoRA/QLoRA). Consider model size vs. available hardware.

3

Configure Training

Set hyperparameters: learning rate (~2e-4), batch size, epochs (1-3), LoRA rank, target modules.

4

Train & Monitor

Run training, monitor loss curves. Should see decreasing, smooth loss. Watch for overfitting.

5

Evaluate & Deploy

Test on held-out data. Merge LoRA adapters into base model. Deploy using vLLM, TGI, or Ollama.

Chapter 6

Retrieval-Augmented Generation (RAG)

Grounding AI responses in your own data

What is RAG?

Retrieval-Augmented Generation (RAG) is a technique that enhances LLM responses by first retrieving relevant information from external knowledge bases, then including that context in the prompt. This grounds the AI's answers in factual, up-to-date data โ€” reducing hallucinations and enabling domain-specific knowledge without fine-tuning.

๐Ÿ”„ How RAG Works โ€” The Pipeline

๐Ÿ“ฅ Ingestion (Offline)
๐Ÿ“„ Documents
PDFs, web pages, DBs, APIs
โ†’
โœ‚๏ธ Chunking
Split into passages (512-1024 tokens)
โ†’
๐Ÿ”ข Embedding
Convert to vectors
โ†’
๐Ÿ—„๏ธ Vector DB
Store embeddings (Pinecone, Chroma)
๐Ÿ” Retrieval (Runtime)
โ“ User Query
"How does our refund policy work?"
โ†’
๐Ÿ”ข Embed Query
Same embedding model
โ†’
๐Ÿ”Ž Similarity Search
Find top-K relevant chunks
โ†’
๐Ÿ“‹ Retrieved Context
Top 3-10 relevant passages
โœจ Generation
๐Ÿ“‹ Context + Query
Combined into prompt
โ†’
๐Ÿง  LLM
Generates grounded answer
โ†’
โœ… Answer
With citations from source docs

๐Ÿ”ข Understanding Embeddings

Embeddings convert text into numerical vectors where similar meanings are close together in vector space.

๐Ÿ• dog ๐Ÿˆ cat ๐Ÿพ puppy ๐Ÿฆฎ retriever Animals
๐Ÿ’ป computer โŒจ๏ธ keyboard ๐Ÿ–ฅ๏ธ monitor ๐Ÿ–ฑ๏ธ mouse Technology
๐Ÿ• pizza ๐Ÿ” burger ๐ŸŒฎ taco ๐Ÿฃ sushi Food

In real embeddings, each text becomes a vector of 768-3072 numbers. Similar texts have vectors pointing in similar directions (high cosine similarity).

โš–๏ธ RAG vs Fine-Tuning โ€” When to Use Which

๐Ÿ“š RAG
Aspect
๐Ÿ”ง Fine-Tuning
Adding new knowledge / data
Best For
Changing model behavior / style
Switch data sources instantly
Flexibility
Need to retrain for new data
Low (vector DB + embeddings)
Cost
Medium-High (GPU training)
Minutes to hours
Setup Time
Hours to days
High โ€” sources are citable
Factual Accuracy
Can still hallucinate
Just update the knowledge base
Data Updates
Requires retraining
๐Ÿ’ก Pro Tip: In practice, RAG and fine-tuning are complementary! Fine-tune for tone/behavior, use RAG for knowledge. Many production systems use both.

๐Ÿš€ Advanced RAG Techniques

Hybrid Search

Combine vector (semantic) search with keyword (BM25) search for better retrieval.

Re-ranking

Use a cross-encoder model to re-rank retrieved chunks by relevance after initial retrieval.

Multi-Query RAG

Generate multiple query variations, retrieve for each, then combine results.

Agentic RAG

An AI agent that decides when and what to retrieve, can chain multiple searches.

Graph RAG

Build a knowledge graph from documents, traverse relationships for richer context.

Corrective RAG (CRAG)

Evaluate retrieved docs for relevance, fall back to web search if corpus is insufficient.

๐Ÿ’ป Simple RAG Example (Python + LangChain)

rag_example.py
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import Chroma
from langchain.chains import RetrievalQA

# 1. Load and chunk documents
loader = PyPDFLoader("company_handbook.pdf")
docs = loader.load()

splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,
    chunk_overlap=200
)
chunks = splitter.split_documents(docs)

# 2. Create embeddings and store in vector DB
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Chroma.from_documents(chunks, embeddings)

# 3. Create retrieval chain
llm = ChatOpenAI(model="gpt-4o", temperature=0)
qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=vectorstore.as_retriever(search_kwargs={"k": 5}),
    return_source_documents=True
)

# 4. Ask questions!
result = qa_chain.invoke({"query": "What is our PTO policy?"})
print(result["result"])
print("Sources:", [doc.metadata for doc in result["source_documents"]])
Chapter 7

Interactive Labs & Playground

Learn by doing โ€” hands-on experiments to solidify your understanding

๐ŸŒก๏ธ Lab 1: Temperature Experiment

See how temperature affects LLM output. Adjust the slider and generate text:

0.0 (Deterministic) 1.0 (Balanced) 2.0 (Very Creative)

โœ๏ธ Lab 2: Prompt Engineering Techniques

Compare different prompting strategies on the same task:

Zero-Shot

Classify this review as positive or negative:
"The battery life is amazing but the screen is too dim."
Response: "This review is mixed โ€” the reviewer likes the battery but dislikes the screen."
โญโญโญ โ€” Works but vague

Few-Shot (with examples)

Classify these reviews:
"Great camera!" โ†’ Positive
"Terrible build quality" โ†’ Negative  
"Good value for money" โ†’ Positive

Now classify: "The battery life is amazing but the screen is too dim."
Response: "Mixed (Positive for battery, Negative for screen)"
โญโญโญโญ โ€” More structured

Chain-of-Thought (CoT)

Classify this review. Think step by step:
1) Identify positive aspects
2) Identify negative aspects  
3) Weigh overall sentiment

Review: "The battery life is amazing but the screen is too dim."
Response: "1) Positive: battery life ('amazing')
2) Negative: screen brightness ('too dim')
3) Overall: Mixed-Positive (battery praise is stronger than screen criticism)"
โญโญโญโญโญ โ€” Detailed reasoning

๐Ÿง  Lab 3: Neural Network Visualizer

See how data flows through a neural network. Click neurons to activate them and watch signals propagate:

Click "Forward Pass" to see data flow through the network layers.

๐Ÿ“ Lab 4: Embedding Similarity Calculator

Type two sentences and see how similar they are in embedding space (simulated cosine similarity):

๐Ÿ’ฐ Lab 5: AI API Cost Estimator

Estimate monthly costs for different AI models based on your usage:

Input tokens/month: โ€”
Output tokens/month: โ€”
Estimated monthly cost: โ€”

๐Ÿงช Lab 6: Test Your Knowledge

1/6: What architecture powers most modern LLMs?

2/6: What does RAG stand for?

3/6: Which technique reduces fine-tuning parameters by 99%+?

4/6: Which is an open-source model?

5/6: In an agent loop, what comes after "Think"?

6/6: What reduces hallucinations by grounding AI in external data?

๐Ÿ“– AI Glossary