Please enable JavaScript to use CodeHS

AI Engineer

Ground models in documents

LLMs hallucinate. Retrieval-Augmented Generation feeds relevant documents into the prompt so the model stays grounded in facts. This tutorial builds a minimal RAG pipeline.

AI ~15 min Programmer
Vocabulary

Key terms for this tutorial

Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.

model
A function with learnable parameters that maps inputs to outputs.
chunking
Splitting long documents into smaller pieces so they fit in context windows and can be retrieved accurately.
embedding
A learned vector that represents a token, word, or item in a continuous numerical space.
pipeline
A scikit-learn object that chains preprocessing steps and a model so the same transformations are applied during training and inference.
RAG
Retrieval-Augmented Generation. A pattern where a model answers questions by retrieving relevant documents and using them as context.

Embed

From text to vectors

An embedding model turns text into a dense vector. Similar texts have vectors with small cosine distance. You can compute embeddings with sentence-transformers or OpenAI's embedding API.

embed.py
import torch
import torch.nn.functional as F

def embed(text, vocab, d=8):
    vec = torch.zeros(d)
    for w in text.lower().split():
        vec[vocab.get(w, 0) % d] += 1
    return F.normalize(vec, dim=0)

vocab = {'the':0, 'cat':1, 'sat':2, 'mat':3, 'dog':4, 'ran':5}
q = embed('where is the cat', vocab)
docs = [
    embed('the cat sat on the mat', vocab),
    embed('the dog ran fast', vocab),
]
scores = [q @ d for d in docs]
print('similarities:', [round(s.item(), 3) for s in scores])
Output
similarities: [0.596, 0.298]

Line-by-line: embed.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn.functional as F — Import the torch library so we can use its built-in tools.
  3. def embed(text, vocab, d=8): — Define the embed function, which describes a step in the data or model pipeline.
  4. for w in text.lower().split(): — Loop over the data one batch at a time.
  5. scores = [q @ d for d in docs] — Loop over the data one batch at a time.
  6. print('similarities:', [round(s.item(), 3) for s in scores]) — Loop over the data one batch at a time.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Retrieval-Augmented Generation'. Explain the section 'From text to vectors' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Chunk

Chunking and retrieval

Documents are split into overlapping chunks. Each chunk is embedded and stored. At query time, the top-k most similar chunks are retrieved and concatenated into the prompt.

chunk.py
from collections import Counter

document = 'The cat sat. The cat ran. The dog barked.'
words = document.split()
chunk_size, overlap = 4, 1
chunks = []
for i in range(0, len(words), chunk_size - overlap):
    chunk = ' '.join(words[i:i + chunk_size])
    if chunk:
        chunks.append(chunk)
print('chunks:', chunks)
Output
chunks: ['The cat sat. The', 'sat. The cat ran.', 'cat ran. The dog', 'ran. The dog barked.']

Line-by-line: chunk.py

Read this slowly. Each line does one small, concrete thing.

  1. from collections import Counter — Import tools from the collections package.
  2. words = document.split() — Prepare a dataset by splitting or formatting raw examples.
  3. for i in range(0, len(words), chunk_size - overlap): — Loop over the data one batch at a time.
  4. print('chunks:', chunks) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Retrieval-Augmented Generation'. Explain the section 'Chunking and retrieval' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Check yourself

Check yourself

?

Why does RAG reduce hallucination?

How does retrieving documents help the model answer factually?

It places relevant source text directly in the context, so the model is conditioned on real information rather than relying solely on parametric memory.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Retrieval-Augmented Generation'. The practice question 'Why does RAG reduce hallucination?' asks: How does retrieving documents help the model answer factually? The answer is: It places relevant source text directly in the context, so the model is conditioned on real information rather than relying solely on parametric memory.. Explain the concept behind this in simple terms.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Retrieval-Augmented Generation'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Quick quiz

Three questions

1. What does RAG retrieve?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Retrieval-Augmented Generation'. The quiz asks: What does RAG retrieve? The correct answer is: Relevant document chunks to include in the prompt. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. Why chunk documents?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Retrieval-Augmented Generation'. The quiz asks: Why chunk documents? The correct answer is: To fit context windows and match specific parts of a document. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. What is a common similarity metric in RAG?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Retrieval-Augmented Generation'. The quiz asks: What is a common similarity metric in RAG? The correct answer is: Cosine similarity between embeddings. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Next: align models with reinforcement learning.

Part of the CodeHS tutorial library.