Module 4: Code Retrieval Naive Vector Baseline

Flat Chunk/Vector Retrieval (Tier 1)

In the previous lesson, you categorized your benchmark questions by which retrieval method handles them. Some questions (the conceptual and vocabulary-mismatch ones) need semantic search. This lesson builds that semantic search as a naive baseline: chunk your files as plain text, embed the chunks, store them in a vector database, and retrieve the top-k results for each question.

This is an intentional failure lesson. We're building the simplest possible vector retrieval pipeline on purpose, running it against your benchmark, and carefully documenting what breaks. I've found this to be one of the most valuable exercises in my own journey, and why it's emphasized here. The specific ways naive retrieval fails will tell you exactly what to fix in the upcoming Tiers 2, 3, and 4.

What you'll learn

  • Build a complete chunk-embed-store-retrieve pipeline for a code repository
  • Use Qdrant as a local vector database to index and query code chunks
  • Run your benchmark questions through naive vector retrieval and grade the results
  • Identify five common failure classes in naive code retrieval
  • Compare vector retrieval against the structured retrieval from the previous lesson on the same benchmark

Concepts

Chunking: the process of splitting documents into smaller pieces for embedding and retrieval. In naive retrieval, you chunk by character count or line count with no regard for code structure. A chunk might split a function in half, merge unrelated code, or separate a docstring from the function it describes. These boundary violations are the primary source of failures in naive retrieval.

Embedding: converting text into a numerical vector that captures its meaning. An embedding model maps text to a point in a high-dimensional space where semantically similar texts are nearby. We'll use an embedding model to convert our code chunks into vectors for storage and search.

Vector database: a database optimized for storing vectors and finding the nearest neighbors to a query vector. It handles the math of similarity search so you can focus on what you store and how you query it.

Top-k retrieval: retrieving the k most similar chunks to a query. With naive retrieval, this is your only knob: retrieve more chunks (higher k) for better recall at the cost of more noise, or fewer chunks (lower k) for precision at the cost of missing relevant code.

Cosine similarity: a measure of how similar two vectors are, based on the angle between them. Values range from -1 (opposite) to 1 (identical direction). Most embedding models are trained so that cosine similarity correlates with semantic similarity.

Problem-to-Tool Map

Problem classSymptomCheapest thing to try firstTool or approach
Need semantic code retrievalGrep misses conceptual matches; metadata index doesn't cover natural-language questionsThe metadata index from the previous lessonChunk + embed + vector search (this lesson)
Retrieval returns irrelevant chunksTop-k results don't contain the code the model needs to answerIncrease kBetter chunking (Tier 2)
Symbol boundaries are splitA function definition is split across two chunks; retrieval returns half a functionLarger chunk sizeAST-aware chunking (Tier 2)
Code outranked by commentsDocstrings or comments rank higher than the actual implementationFilter by file typeMetadata-enriched embeddings (Tier 2)

Default: Qdrant

Why this is the default: Qdrant runs locally with no external dependencies, supports metadata filtering and hybrid search, and scales beyond toy corpora. It's a good fit for the progression we're building. We'll use its filtering capabilities in the AST-aware lesson and its hybrid features in the graph/hybrid lesson.

Portable concept underneath: a retrieval store that accepts vectors, stores them with metadata, and returns nearest neighbors filtered by arbitrary conditions. Any vector database provides this.

Closest alternatives and when to switch:

  • Chroma: use when you want the absolute simplest local setup and don't need filtering or hybrid features yet
  • pgvector: use when PostgreSQL is already your center of gravity and you don't want a separate database process
  • FAISS: use when you need raw speed for in-memory search and don't need persistence or metadata filtering

Walkthrough

Install dependencies

cd anchor-repo
pip install qdrant-client openai

Chunk your repository

Let's start with the simplest possible chunking: split every file into fixed-size text chunks with overlap. This is intentionally naive so we can see the failures it produces.

# retrieval/chunk_files.py
"""Naive text chunking for the anchor repository."""
import json
from pathlib import Path

REPO_ROOT = Path(".").resolve()
EXCLUDED_DIRS = {".venv", ".git", "__pycache__", "node_modules", ".tox", ".mypy_cache"}
CHUNK_SIZE = 800  # characters
CHUNK_OVERLAP = 200  # characters
OUTPUT_PATH = Path("retrieval/chunks.jsonl")

# File extensions to index
CODE_EXTENSIONS = {".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".rs", ".java", ".md", ".yaml", ".yml", ".toml", ".json"}


def is_excluded(path: Path) -> bool:
    """Check whether a path should be skipped during indexing.

    Args:
        path: Path relative to the repository root.

    Returns:
        bool: True when the path belongs to an excluded directory.
    """
    return any(part in EXCLUDED_DIRS for part in path.parts)


def chunk_text(text: str, chunk_size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
    """Split text into overlapping chunks by character count.

    Args:
        text: Full file contents to break into retrieval chunks.
        chunk_size: Maximum characters to place in each chunk.
        overlap: Number of characters to carry into the next chunk.

    Returns:
        list[str]: Overlapping text chunks in source order.
    """
    if len(text) <= chunk_size:
        return [text]
    chunks = []
    start = 0
    while start < len(text):
        end = start + chunk_size
        chunks.append(text[start:end])
        start = end - overlap
    return chunks


def build_chunks():
    """Walk the repository and emit naive retrieval chunks.

    Returns:
        list[dict]: Chunk records ready to be written to the JSONL index file.
    """
    all_chunks = []
    chunk_id = 0

    for path in sorted(REPO_ROOT.rglob("*")):
        if not path.is_file():
            continue
        if is_excluded(path.relative_to(REPO_ROOT)):
            continue
        if path.suffix not in CODE_EXTENSIONS:
            continue

        try:
            text = path.read_text(errors="replace")
        except Exception:
            continue

        if not text.strip():
            continue

        rel_path = str(path.relative_to(REPO_ROOT))
        chunks = chunk_text(text)

        for i, chunk in enumerate(chunks):
            all_chunks.append({
                "chunk_id": f"chunk-{chunk_id:05d}",
                "file_path": rel_path,
                "chunk_index": i,
                "total_chunks": len(chunks),
                "text": chunk,
                "char_count": len(chunk),
            })
            chunk_id += 1

    # Write chunks to JSONL
    with open(OUTPUT_PATH, "w") as f:
        for chunk in all_chunks:
            f.write(json.dumps(chunk) + "\n")

    print(f"Created {len(all_chunks)} chunks from {len(set(c['file_path'] for c in all_chunks))} files")
    print(f"Average chunk size: {sum(c['char_count'] for c in all_chunks) // len(all_chunks)} chars")
    print(f"Chunks saved to {OUTPUT_PATH}")
    return all_chunks


if __name__ == "__main__":
    build_chunks()
python retrieval/chunk_files.py

Expected output:

Created 142 chunks from 23 files
Average chunk size: 723 chars
Chunks saved to retrieval/chunks.jsonl

Take a moment to look at the chunks. Open retrieval/chunks.jsonl and scan a few entries. You'll notice chunks that split functions mid-body, merge a docstring from one function with the body of another, or contain a fragment of a class with no context about which class it belongs to. These are the boundary violations we'll fix with AST-aware chunking in the next lesson.

Embed and store in Qdrant

# retrieval/embed_and_store.py
"""Embed chunks and store them in a local Qdrant collection."""
import json
from pathlib import Path
from openai import OpenAI
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct

CHUNKS_PATH = Path("retrieval/chunks.jsonl")
COLLECTION_NAME = "anchor-repo-naive"
EMBEDDING_MODEL = "text-embedding-3-small"
EMBEDDING_DIM = 1536
BATCH_SIZE = 50

client = OpenAI()
qdrant = QdrantClient(path="retrieval/qdrant_data")


def load_chunks() -> list[dict]:
    """Load chunk records from the JSONL file.

    Returns:
        list[dict]: Chunk payloads ready for embedding and storage.
    """
    chunks = []
    with open(CHUNKS_PATH) as f:
        for line in f:
            if line.strip():
                chunks.append(json.loads(line))
    return chunks


def embed_texts(texts: list[str]) -> list[list[float]]:
    """Embed a batch of chunk texts with the configured provider model.

    Args:
        texts: Chunk texts to convert into embedding vectors.

    Returns:
        list[list[float]]: Embedding vectors aligned with the input order.
    """
    response = client.embeddings.create(model=EMBEDDING_MODEL, input=texts)
    return [item.embedding for item in response.data]


def create_collection():
    """Create or recreate the Qdrant collection used for naive retrieval.

    Returns:
        None
    """
    collections = [c.name for c in qdrant.get_collections().collections]
    if COLLECTION_NAME in collections:
        qdrant.delete_collection(COLLECTION_NAME)
        print(f"Deleted existing collection '{COLLECTION_NAME}'")
    qdrant.create_collection(
        collection_name=COLLECTION_NAME,
        vectors_config=VectorParams(size=EMBEDDING_DIM, distance=Distance.COSINE),
    )
    print(f"Created collection '{COLLECTION_NAME}'")


def embed_and_store():
    """Embed all indexed chunks and upsert them into Qdrant.

    Returns:
        None
    """
    chunks = load_chunks()
    create_collection()
    for batch_start in range(0, len(chunks), BATCH_SIZE):
        batch = chunks[batch_start:batch_start + BATCH_SIZE]
        texts = [c["text"] for c in batch]
        embeddings = embed_texts(texts)
        points = [
            PointStruct(
                id=batch_start + i, vector=embedding,
                payload={"chunk_id": chunk["chunk_id"], "file_path": chunk["file_path"],
                         "chunk_index": chunk["chunk_index"], "total_chunks": chunk["total_chunks"],
                         "text": chunk["text"]},
            )
            for i, (chunk, embedding) in enumerate(zip(batch, embeddings))
        ]
        qdrant.upsert(collection_name=COLLECTION_NAME, points=points)
        print(f"  Stored {batch_start + len(batch)}/{len(chunks)} chunks")
    print(f"\nDone. {len(chunks)} chunks embedded and stored in '{COLLECTION_NAME}'")


if __name__ == "__main__":
    embed_and_store()
python retrieval/embed_and_store.py

Expected output:

Deleted existing collection 'anchor-repo-naive'
Created collection 'anchor-repo-naive'
  Stored 50/142 chunks
  Stored 100/142 chunks
  Stored 142/142 chunks

Done. 142 chunks embedded and stored in 'anchor-repo-naive'

Retrieve and answer benchmark questions

Now we'll build a retrieval function and run it through the benchmark:

# retrieval/naive_retrieve.py
"""Naive vector retrieval: embed the query, find top-k chunks, return them."""
import sys
from openai import OpenAI
from qdrant_client import QdrantClient

COLLECTION_NAME = "anchor-repo-naive"
EMBEDDING_MODEL = "text-embedding-3-small"
TOP_K = 5

client = OpenAI()
qdrant = QdrantClient(path="retrieval/qdrant_data")

SYSTEM_PROMPT = (
    "You are a code assistant. Answer the question using ONLY the "
    "retrieved code context below. If the context doesn't contain "
    "enough information, say so."
)


def retrieve(query: str, top_k: int = TOP_K) -> list[dict]:
    """Retrieve the top matching chunks for a query.

    Args:
        query: Natural-language or code query to embed and search.
        top_k: Number of top-ranked chunks to return.

    Returns:
        list[dict]: Retrieved chunk metadata with scores and text previews.
    """
    response = client.embeddings.create(model=EMBEDDING_MODEL, input=[query])
    query_vector = response.data[0].embedding
    results = qdrant.query_points(
        collection_name=COLLECTION_NAME, query=query_vector, limit=top_k,
    )
    return [
        {"file_path": hit.payload["file_path"], "chunk_id": hit.payload["chunk_id"],
         "score": round(hit.score, 4), "text": hit.payload["text"]}
        for hit in results.points
    ]


def retrieve_and_answer(question: str, model: str = "gpt-4o-mini") -> dict:
    """Retrieve evidence and generate an answer from the naive vector baseline.

    Args:
        question: User question to answer from retrieved chunks.
        model: Generation model used for the answer step.

    Returns:
        dict: Final answer, supporting chunks, and retrieval-method metadata.
    """
    chunks = retrieve(question)
    context = "\n\n---\n\n".join(
        f"File: {c['file_path']} (score: {c['score']})\n{c['text']}" for c in chunks
    )
    response = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": f"{SYSTEM_PROMPT}\n\nRetrieved context:\n{context}"},
            {"role": "user", "content": question},
        ],
        temperature=0,
    )
    return {"answer": response.choices[0].message.content, "chunks_used": chunks,
            "retrieval_method": "naive_vector"}


if __name__ == "__main__":
    question = sys.argv[1] if len(sys.argv) > 1 else "What are the main modules in this repository?"
    print(f"Question: {question}\n")
    chunks = retrieve(question)
    print(f"Top {len(chunks)} chunks:")
    for c in chunks:
        print(f"  [{c['score']}] {c['file_path']}: {c['text'][:80]}...")
    print()
    result = retrieve_and_answer(question)
    print(f"Answer:\n{result['answer']}")
# Test with a single question
python retrieval/naive_retrieve.py "Where is the main entry point of the application?"

Run the benchmark and grade

# retrieval/run_naive_benchmark.py
"""Run benchmark questions through naive vector retrieval and grade."""
import json
import os
from datetime import datetime, timezone
from pathlib import Path
from retrieval.naive_retrieve import retrieve_and_answer

RUN_ID = "naive-vector-v1-" + datetime.now(timezone.utc).strftime("%Y-%m-%d-%H%M%S")
MODEL = "gpt-4o-mini"
PROVIDER = "openai"
BENCHMARK_FILE = Path("benchmark-questions.jsonl")
OUTPUT_FILE = Path(f"harness/runs/{RUN_ID}.jsonl")
REPO_SHA = os.popen("git rev-parse --short HEAD").read().strip()


def run_benchmark():
    """Run the benchmark set through the naive vector baseline.

    Returns:
        None
    """
    questions = []
    with open(BENCHMARK_FILE) as f:
        for line in f:
            if line.strip():
                questions.append(json.loads(line))

    print(f"Running {len(questions)} benchmark questions through naive vector retrieval")
    print(f"Run ID: {RUN_ID}\n")

    results = []
    for i, q in enumerate(questions):
        print(f"[{i+1}/{len(questions)}] {q['category']}: {q['question'][:60]}...")
        result = retrieve_and_answer(q["question"], model=MODEL)

        entry = {
            "run_id": RUN_ID,
            "question_id": q["id"],
            "question": q["question"],
            "category": q["category"],
            "answer": result["answer"],
            "model": MODEL,
            "provider": PROVIDER,
            "evidence_files": list(set(c["file_path"] for c in result["chunks_used"])),
            "chunk_scores": [c["score"] for c in result["chunks_used"]],
            "retrieval_method": "naive_vector",
            "grade": None,
            "failure_label": None,
            "grading_notes": "",
            "repo_sha": REPO_SHA,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "harness_version": "v0.2",
        }
        results.append(entry)

    os.makedirs("harness/runs", exist_ok=True)
    with open(OUTPUT_FILE, "w") as f:
        for entry in results:
            f.write(json.dumps(entry) + "\n")

    print(f"\nDone. {len(results)} results saved to {OUTPUT_FILE}")
    print("Next: grade these answers and compare against your Module 3 agent baseline.")


if __name__ == "__main__":
    run_benchmark()
python -m retrieval.run_naive_benchmark

After running, grade the results using the same grade_baseline.py from Module 2, then compare:

python harness/summarize_run.py harness/runs/naive-vector-v1-*-graded.jsonl

What you'll see break

When you grade the results, you'll notice five common failure classes. I've listed them here because I've seen every one of them in real-world code retrieval systems:

  1. Exact symbol misses: The question asks "where is validate_path defined?" and vector search returns chunks about validation in general, but not the specific function. Grep would have found this instantly.

  2. Broken semantic units: A function was split across two chunks. The retrieval returns the bottom half (with the return statement) but not the top half (with the function signature and docstring). The model can't answer "what does this function do?" from half a function.

  3. Irrelevant neighbors: Chunks from unrelated files rank highly because they happen to use similar vocabulary. A question about error handling returns chunks about logging because both mention "error."

  4. No relationship structure: "What calls process_request?" requires knowing the call graph. Vector search finds chunks that mention the function but doesn't know which files call it versus which files define it.

  5. Oversized evidence bundles: You retrieve 5 chunks of 800 characters each. That's 4,000 characters of context, and maybe 400 of them are relevant. The model has to work through noise to find the signal.

These five failures map directly to the retrieval substrates we'll add in the next three lessons:

Failure classWhat fixes itTier
Exact symbol missesCombine vector search with lexical searchTier 3 (hybrid)
Broken semantic unitsChunk by function/class boundaries, not character countTier 2 (AST-aware)
Irrelevant neighborsBetter chunk boundaries + rerankingTiers 2 and 3
No relationship structureImport and call graph edgesTier 3 (graph)
Oversized evidence bundlesContext compilation and token budgetingTier 4 (context compiler)

Exercises

  1. Build the full pipeline: chunk_files.pyembed_and_store.pynaive_retrieve.py. Verify you can retrieve chunks for a simple query.
  2. Run run_naive_benchmark.py against your full benchmark. Grade at least 15 answers.
  3. For each graded answer, assign a failure label from the five classes above (or add your own if you see a different pattern).
  4. Compare your naive vector results against your Module 3 agent results. Which categories improved? Which got worse? (Exact symbol lookups will often be worse with vector search than with grep. That's expected.)
  5. Open retrieval/chunks.jsonl and find three chunks where the character-boundary splitting produced obviously bad boundaries. Write down what the chunk should contain if you could split on code structure.

Completion checkpoint

You have:

  • A working Qdrant collection with embedded chunks from your anchor repo
  • A benchmark run graded and compared against your Module 3 agent baseline
  • Failure labels assigned to at least 15 graded answers
  • A clear picture of which failure classes dominate your results
  • Three specific examples of bad chunk boundaries that you'll fix with AST-aware chunking

Retrieval Lab Notes

Before moving on, write up your observations in retrieval/tier1-lab-notes.md. This is the same practice from Module 1's retrieval fundamentals, now applied to your anchor repo at scale. These notes will be your requirements document for Tiers 2-4.

For each failure class you observed, document one specific benchmark question, what the retrieval returned, what it should have returned, and which failure class it falls into. We'll reference these notes throughout the remaining tiers.

Reflection prompts

  • Which failure class appeared most often in your graded results? What does that tell you about the biggest gap in naive vector retrieval?
  • Were there questions where vector search outperformed your Module 3 grep-based agent? What made those questions different?
  • Were there questions where vector search was worse than grep? What do those questions have in common?
  • If you could fix only one failure class before moving to AST-aware retrieval, which would have the biggest impact on your benchmark scores?

What's next

AST and Symbol Retrieval. The baseline will show boundary and symbol failures; the next lesson fixes the representation, not just the ranking.

References

Start here

Build with this

Deep dive

Your Notes
GitHub Sync

Sync your lesson notes to a private GitHub Gist. If you have not entered a token yet, the sync button will open the GitHub token modal.

Glossary
API (Application Programming Interface)Foundational terms
A structured way for programs to communicate. In this context, usually an HTTP endpoint you call to interact with an LLM.
AST (Abstract Syntax Tree)Foundational terms
A tree representation of source code structure. Used by parsers like Tree-sitter to understand code as a hierarchy of functions, classes, and statements. You'll encounter this more deeply in the Code Retrieval module, but the concept appears briefly in retrieval fundamentals.
BM25 (Best Match 25)Foundational terms
A classical ranking function for keyword search. Scores documents by term frequency and inverse document frequency. Often competitive with or complementary to vector search.
ChunkingFoundational terms
Splitting a document into smaller pieces for indexing and retrieval. Chunk boundaries significantly affect retrieval quality. Split at the wrong place and your retrieval will return half a function or the end of one paragraph glued to the start of another.
Context engineeringFoundational terms
The discipline of selecting, packaging, and budgeting the information a model sees at inference time. Prompts, retrieved evidence, tool results, memory, and state are all parts of context. Context engineering is arguably the core skill of AI engineering. Bigger context windows are not a substitute for better context selection.
Context rotFoundational terms
Degradation of output quality caused by stale, noisy, or accumulated context. Symptoms include stale memory facts, conflicting retrieved evidence, bloated prompt history, and accumulated instructions that contradict each other. A form of technical debt in AI systems.
Context windowFoundational terms
The maximum number of tokens an LLM can process in a single request (input + output combined).
EmbeddingFoundational terms
A fixed-length numeric vector representing a piece of text. Used for similarity search: texts with similar meanings have nearby embeddings.
EndpointFoundational terms
A specific URL path that accepts requests and returns responses (e.g., POST /v1/chat/completions).
GGUFFoundational terms
A file format for quantized models used by llama.cpp and Ollama. When you see a model name like qwen2.5:7b-q4_K_M, the suffix indicates the quantization scheme. GGUF supports mixed quantization (different precision for different layers) and is the most common format for local inference.
HallucinationFoundational terms
When a model generates content that sounds confident but isn't supported by the evidence it was given, or fabricates details that don't exist. Not the same as "any wrong answer"; a model that misinterprets ambiguous instructions gave a bad answer but didn't hallucinate. Common causes: weak prompt, missing context, context rot, model limitation, or retrieval failure.
InferenceFoundational terms
Running a trained model to generate output from input. What happens when you call an API. Most AI engineering work is inference-time work: building systems around models, not training them. Use "inference," not "inferencing."
JSON (JavaScript Object Notation)Foundational terms
A lightweight text format for structured data. The lingua franca of API communication.
Lexical searchFoundational terms
Finding items by matching keywords or terms. Includes BM25, TF-IDF (Term Frequency–Inverse Document Frequency), and simple keyword matching. Returns exact term matches, not semantic similarity.
LLM (Large Language Model)Foundational terms
A neural network trained on large text corpora that generates text by predicting the next token. The core technology behind AI engineering; every tool, pattern, and pipeline in this curriculum runs on top of one.
MetadataFoundational terms
Structured information about a document or chunk (file path, language, author, date, symbol type). Used for filtering retrieval results.
Neural networkFoundational terms
A computing system loosely inspired by biological neurons, built from layers of mathematical functions that transform inputs into outputs. LLMs are a specific type of neural network (transformers) trained on text. You don't need to understand neural network internals to do AI engineering, but knowing the term helps when reading external resources.
Reasoning modelFoundational terms
A model optimized for complex multi-step planning, math, and logic (e.g., o3, o4-mini). Slower and more expensive but better on hard problems. Sometimes called "LRM" (large reasoning model), but "reasoning model" is the more consistent term across provider docs.
RerankingFoundational terms
A second-pass scoring step that re-orders retrieved results using a more expensive model. Improves precision after an initial broad retrieval.
SchemaFoundational terms
A formal description of the shape and types of a data structure. Used to validate inputs and outputs.
SLM (small language model)Foundational terms
A compact model (typically 1-7B parameters) that runs on consumer hardware with lower cost, latency, and better privacy (e.g., Phi, small Llama variants, Gemma). The right choice when privacy, offline operation, predictable cost, or low latency matter more than peak capability.
System promptFoundational terms
A special message that sets the model's behavior, role, and constraints for a conversation.
TemperatureFoundational terms
A parameter controlling output randomness. Lower values produce more deterministic output; higher values produce more varied output. Does not affect the model's intelligence.
TokenFoundational terms
The basic unit an LLM processes. Not a word. Tokens are sub-word fragments. "unhappiness" might be three tokens: "un", "happi", "ness". Token count determines cost and context window usage.
Top-kFoundational terms
The number of results returned from a retrieval query. "Top-5" means the five highest-scoring results.
Top-p (nucleus sampling)Foundational terms
An alternative to temperature for controlling output diversity. Selects from the smallest set of tokens whose cumulative probability exceeds p.
Vector searchFoundational terms
Finding items by proximity in embedding space (nearest neighbors). Returns "similar" results, not "exact match" results.
vLLM (virtual LLM)Foundational terms
An inference serving engine (not a model) that hosts open-weight models behind an OpenAI-compatible HTTP endpoint. Infrastructure layer, not model layer. Relevant when moving from hosted APIs to self-hosting.
WeightsFoundational terms
The learned parameters inside a model. Changed during training, fixed during inference.
Workhorse modelFoundational terms
A general-purpose LLM optimized for speed and broad capability (e.g., GPT-4o-mini, Claude Haiku, Gemini Flash). The default for most tasks. When someone says "LLM" without qualification, they usually mean this.
BaselineBenchmark and Harness terms
The first measured performance of your system on a benchmark. Everything else is compared against this. Without a baseline, you can't tell whether a change helped.
BenchmarkBenchmark and Harness terms
A fixed set of questions or tasks with known-good answers, used to measure system performance over time.
Run logBenchmark and Harness terms
A structured record (typically JSONL) of every system run: what input was given, what output was produced, what tools were called, how long it took, and what it cost. The raw data that evals, telemetry, and cost analysis are built from.
A2A (Agent-to-Agent protocol)Agent and Tool Building terms
An open protocol for peer-to-peer agent collaboration. Agents discover each other's capabilities and delegate or negotiate tasks as equals. Different from MCP (which connects agents to tools, not to other agents) and from handoffs (which transfer control within one system).
AgentAgent and Tool Building terms
A system where an LLM decides which tools to call, observes results, and iterates until a task is complete. Agent = model + tools + control loop.
Control loopAgent and Tool Building terms
The code that manages the agent's cycle: send prompt, check for tool calls, execute tools, append results, repeat or finish.
HandoffAgent and Tool Building terms
Passing control from one agent or specialist to another within an orchestrated system.
MCP (Model Context Protocol)Agent and Tool Building terms
An open protocol for exposing tools, resources, and prompts to AI applications in a standardized way. Connects agents to capabilities (tools and data), not to other agents.
Tool calling / function callingAgent and Tool Building terms
The model's ability to request execution of a specific function with structured arguments, rather than just generating text.
Context compilation / context packingCode Retrieval terms
The process of selecting and assembling the smallest useful set of evidence for a specific task. Not "dump everything retrieved into the prompt."
GroundingCode Retrieval terms
Tying model assertions to specific evidence. A grounded answer cites what it found; an ungrounded answer asserts without evidence.
Hybrid retrievalCode Retrieval terms
Combining multiple retrieval methods (e.g., vector search + keyword search + metadata filters) and merging or reranking the results.
Knowledge graphCode Retrieval terms
A data structure that stores entities and their relationships explicitly (e.g., "function A calls function B," "module X imports module Y"). Useful for traversal and dependency reasoning. One retrieval strategy among several, often overused when simpler metadata or adjacency tables would suffice.
RAG (Retrieval-Augmented Generation)Code Retrieval terms
A pattern where the model's response is grounded in retrieved external evidence rather than relying solely on its training data.
Symbol tableCode Retrieval terms
A mapping of code identifiers (functions, classes, variables) to their locations and metadata.
Tree-sitterCode Retrieval terms
An incremental parsing library that builds ASTs for source code. Used in this curriculum for code-aware chunking and symbol extraction.
Context packRAG and Grounded Answers terms
A structured bundle of evidence assembled for a specific task, with metadata about provenance, relevance, and token budget.
Evidence bundleRAG and Grounded Answers terms
A collection of retrieved items grouped for a specific sub-task, with enough metadata to evaluate whether the evidence is relevant and sufficient.
Retrieval routingRAG and Grounded Answers terms
Deciding which retrieval strategy or method to use for a given query. Different questions need different retrieval methods.
EvalObservability and Evals terms
A structured test that measures system quality. Not the same as training. Evals measure, they don't change the model.
Harness (AI harness / eval harness)Observability and Evals terms
The experiment and evaluation framework around your model or agent. It runs benchmark tasks, captures outputs, logs traces, grades results, and compares system versions. It turns ad hoc "try it and see" into repeatable, comparable experiments. Typically includes: input dataset, prompt and tool configuration, model/provider selection, execution loop, logging, grading, and artifact capture.
LLM-as-judgeObservability and Evals terms
Using a language model to evaluate or grade the output of another model or system. Useful for scaling evaluation beyond manual review, but requires rubric quality, judge consistency checks, and human spot-checking. Not a replacement for exact-match checks where they apply.
OpenTelemetry (OTel)Observability and Evals terms
An open standard for collecting and exporting telemetry data (traces, metrics, logs). Vendor-agnostic.
RAGASObservability and Evals terms
A specific eval framework for retrieval-augmented generation. Measures metrics like faithfulness, relevance, and context precision. One tool example, not a foundational concept. Learn the metrics first, then the tool.
SpanObservability and Evals terms
A single operation within a trace (e.g., one tool call, one retrieval query). Traces are made of spans.
TelemetryObservability and Evals terms
Structured data about system behavior: what happened, when, how long it took, what it cost. Includes traces, metrics, and events.
TraceObservability and Evals terms
A structured record of one complete run through the system, including all steps, tool calls, and decisions.
Long-term memoryOrchestration and Memory terms
Persistent facts that survive across conversations. Requires write policies to manage what gets stored, updated, or deleted.
OrchestrationOrchestration and Memory terms
Explicit control over how tasks are routed, delegated, and synthesized across multiple agents or specialists.
RouterOrchestration and Memory terms
A component that decides which specialist or workflow path to use for a given query.
SpecialistOrchestration and Memory terms
An agent or workflow tuned for a narrow task (e.g., "code search," "documentation lookup," "test generation"). Specialists are composed by an orchestrator.
Thread memoryOrchestration and Memory terms
Conversation state that persists within a single session or thread.
Workflow memoryOrchestration and Memory terms
Intermediate state that persists within a multi-step task but doesn't survive beyond the workflow's completion.
Catastrophic forgettingOptimization terms
When fine-tuning causes a model to lose capabilities it had before training. The model gets better at the fine-tuned task but worse at tasks it previously handled. PEFT methods like LoRA reduce this risk by freezing original weights.
DistillationOptimization terms
Training a smaller (student) model to reproduce the behavior of a larger (teacher) model on a specific task.
DPO (Direct Preference Optimization)Optimization terms
A method for preference-based model optimization that's simpler than RLHF, training the model directly on preference pairs without a separate reward model.
Fine-tuningOptimization terms
Updating a model's weights on task-specific data to change its behavior permanently. An umbrella term that includes SFT, instruction tuning, RLHF, DPO, and other techniques. See the fine-tuning landscape table in Lesson 8.3 for how these relate.
Full fine-tuningOptimization terms
Updating all of a model's parameters during training, as opposed to PEFT methods that update only a small subset. Requires significantly more GPU memory and compute. Produces the most thorough adaptation but carries higher risk of catastrophic forgetting.
Inference serverOptimization terms
Software (like vLLM or Ollama) that hosts a model and serves inference requests.
Instruction tuningOptimization terms
A specific application of SFT where the training data consists of instruction-response pairs. This is how base models become chat models: the technique is SFT, the data format is instructions. Not a separate technique from SFT.
LoRA (Low-Rank Adaptation)Optimization terms
A parameter-efficient fine-tuning method that trains small adapter matrices instead of updating all model weights. Dramatically reduces GPU memory and compute requirements.
Parameter countOptimization terms
The number of learned weights in a model, commonly expressed in billions (e.g., "7B" = 7 billion parameters). Determines memory requirements (roughly 2 bytes per parameter at FP16) and broadly correlates with capability, though training quality and architecture matter as much as size. See Model Selection and Serving for sizing guidance.
PEFT (Parameter-Efficient Fine-Tuning)Optimization terms
A family of methods (including LoRA) that fine-tune a small subset of parameters instead of the full model.
Preference optimizationOptimization terms
Training methods (RLHF, DPO) that use human or automated preference signals to improve model behavior. "This output is better than that output" rather than "this is the correct output."
QLoRA (Quantized LoRA)Optimization terms
LoRA applied to a quantized (compressed) base model. Further reduces memory requirements, enabling fine-tuning on consumer hardware.
QuantizationOptimization terms
Reducing the precision of model weights (e.g., FP16 → INT4) to shrink memory usage and increase inference speed at some quality cost. A 7B model at FP16 needs ~14 GB VRAM; quantized to 4-bit, it fits in ~4 GB. Common formats include GGUF (llama.cpp/Ollama), GPTQ and AWQ (vLLM/HuggingFace). See Model Selection and Serving for format details and tradeoffs.
OverfittingOptimization terms
When a model memorizes training examples instead of learning generalizable patterns. The model performs well on training data but poorly on new inputs. Detected by monitoring validation loss alongside training loss.
RLHF (Reinforcement Learning from Human Feedback)Optimization terms
A training method that uses human preference signals to improve model behavior through a reward model. More complex than DPO (requires training a separate reward model) but offers more control over the optimization objective.
SFT (Supervised Fine-Tuning)Optimization terms
Fine-tuning using input-output pairs where the desired output is known. The most common fine-tuning approach.
TRL (Transformer Reinforcement Learning)Optimization terms
A Hugging Face library for training language models with reinforcement learning, SFT, and other optimization methods.
Consumer chat appCross-cutting terms
The browser or desktop product meant for human conversation (ChatGPT, Claude, HuggingChat). Useful for experimentation, but not the same as API access.
Developer platformCross-cutting terms
The provider's API, billing, API-key, and developer-docs surface. This is what you need for this learning path.
Hosted APICross-cutting terms
The provider runs the model for you and you call it over HTTP.
Local inferenceCross-cutting terms
You run the model on your own machine.
ProviderCross-cutting terms
The company or service that hosts a model API you call from code.
Prompt cachingCross-cutting terms
Reusing computation from repeated prompt prefixes to reduce latency and cost on subsequent requests with the same prefix.
Rate limitingCross-cutting terms
Constraints on how many API requests you can make per unit of time. An operational concern that affects system design and cost.
Token budgetCross-cutting terms
The maximum number of tokens you allocate for a specific part of the context (e.g., "retrieval evidence gets at most 4K tokens"). A context engineering tool for preventing any single component from dominating the context window.