Module 1: Foundations of AI Engineering Building with APIs

Build with APIs, Not Chat Apps

There's a real difference between using ChatGPT, Gemini, Claude, or HuggingChat interactively and building against an API. When you build against an API, you manage request/response structure, errors and retries, multi-tenant state, and how tools are called and validated. The model becomes a component in your system, not a product you interact with.

This lesson bridges that gap. You'll take the prompt contracts you wrote in the previous lesson and implement them as API-backed services. By the end, you'll have a working service that calls a model, enforces output schemas, handles failures, and separates state between users.

What you'll learn

  • Make programmatic model API calls with structured message sequences
  • Enforce output shape with structured outputs / JSON schema
  • Handle basic model-call failures and understand where rate limits and retries fit
  • Manage conversation state across requests using session or conversation IDs
  • Make a basic tool call through the API
  • Compare the same operation across the supported provider variants: OpenAI, Gemini, Anthropic, Hugging Face, Ollama (Local), and Ollama (Cloud)

Concepts

Structured outputs: a feature of model APIs that constrains the model's response to follow a predictable format. There are two levels:

  • JSON mode (response_format={"type": "json_object"}): guarantees valid JSON but does not enforce a specific schema. You still rely on the prompt to guide the structure, and must validate the shape yourself.
  • Schema-constrained mode (response_format={"type": "json_schema", ...}): guarantees the response matches an exact JSON schema you define. The API rejects responses that do not conform. This is the stronger guarantee.

In this lesson we'll start with JSON mode (simpler, works with a wider range of models) and then see how schema-constrained mode tightens the contract. Both turn your prompt contracts into machine-checkable outputs.

Tool calling / function calling: the model's ability to request execution of a specific function with structured arguments, rather than just generating text. When the model encounters a task it cannot do alone (look up a user, read a file, search a database), it can emit a tool call with the function name and arguments. Your code executes the function and returns the result. The model then continues with that result in context.

Conversation state: in an API-backed system, you manage conversation history explicitly. Each request includes the full message sequence (system, user, assistant, tool messages). The API is stateless. If you do not send the history, the model does not remember it. This means you control what the model sees, which is powerful but requires deliberate state management.

Rate limiting: API providers enforce limits on how many requests you can make per minute or per day. When you exceed the limit, the API returns an error (usually HTTP 429). Your code must handle this gracefully: back off, wait, and retry. We'll cover rate limiting in more depth as a safety and cost topic in the Security Basics lesson.

Walkthrough

Project setup

Use Choosing a Provider if you need help mapping this lesson to OpenAI Platform, Gemini API, Anthropic's developer platform, Hugging Face, or Ollama Cloud. The concepts in this lesson are provider-agnostic even when individual code blocks use a specific SDK surface.

You are extending the FastAPI project you built in Python and FastAPI. If you still have your ai-eng-foundations/ directory with app.py and test_app.py, continue from there. If not, go back and complete that lesson first. This one builds directly on it.

Add the model SDKs to your existing project:

cd ai-eng-foundations
source .venv/bin/activate
pip install openai google-genai anthropic ollama huggingface_hub

The huggingface_hub package is included because some Hugging Face variants later in this lesson use InferenceClient directly. For the simplest Hugging Face path, you can also reuse the openai SDK with Hugging Face's router base URL and HF_TOKEN.

Set your API keys:

export OPENAI_API_KEY="sk-..."

You do not need every provider path configured to finish this lesson. Install the providers you actually plan to use, and use Choosing a Provider for the exact hosted-platform distinction:

  • OpenAI Platform means platform.openai.com, not chatgpt.com
  • Gemini API means https://aistudio.google.com/ plus https://ai.google.dev/, not gemini.google.com
  • Anthropic means https://platform.claude.com/ plus https://platform.claude.com/docs/, not claude.ai
  • Hugging Face means https://huggingface.co/settings/tokens for HF_TOKEN and https://huggingface.co/docs/inference-providers/index for the API, not huggingface.co/chat
  • GitHub Models means GitHub-hosted inference with GITHUB_TOKEN and publisher/model IDs, not GitHub Copilot SDK
  • Ollama Cloud means https://ollama.com/api, not local Ollama on localhost

If you choose Gemini for this lesson, the least-friction path is usually to use google-genai directly with GEMINI_API_KEY. If you choose Hugging Face, the least-friction path is usually to keep the openai SDK and point it at Hugging Face's OpenAI-compatible router with HF_TOKEN. If you choose GitHub Models, the least-friction path is to keep the openai SDK and point it at https://models.github.ai/inference with the GitHub headers and GITHUB_TOKEN. If you choose Ollama, the least-friction path is usually to keep the lesson concepts the same and swap only the client/call layer to Ollama's API or Python client.

By the end of this lesson, your project will have grown to:

ai-eng-foundations/
├── app.py              # FastAPI service — extended with model-backed endpoints
├── conversations.py    # In-memory conversation store (new)
├── tools.py            # Tool definitions and implementations (new)
├── cross_provider.py   # Cross-provider comparison script (new)
├── test_app.py         # Tests — extended
└── requirements.txt

Your /health, /echo, and /summarize-request endpoints from lesson 1 are still there. You are adding model-backed endpoints alongside them.

Hosted APIs today, same patterns everywhere. In this lesson you call hosted APIs plus one explicit local Ollama variant where that is the clearer path. Each code block offers tabs for the supported provider variants. Later, if you self-host an open-weight model using a serving engine like vLLM, Ollama, or llama.cpp, you point the same style of client at your own endpoint instead of a hosted platform. The code surface changes. The concepts do not.

You've already built a retry/backoff wrapper in Python and FastAPI. In this lesson, focus on model call structure, schemas, tool flow, and conversation state. Reuse the retry pattern from lesson 1 around your model calls; the dedicated rate-limit and backoff treatment comes in Security Basics.

Your first programmatic model call

Add a summarizer endpoint to your existing app.py. Your /health, /echo, and /summarize-request endpoints from lesson 1 stay. You are adding alongside them. The Pydantic models are the same regardless of provider:

# Add these imports to the top of app.py
import json
from fastapi import HTTPException

# --- New models (add below your existing models) ---

class SummarizeTextRequest(BaseModel):
    text: str

class SummarizeTextResponse(BaseModel):
    summary: str
    word_count: int
    key_topics: list[str]

Now add the client setup and endpoint. Pick your provider:

from openai import OpenAI

# Add this after your existing app = FastAPI() line
client = OpenAI()  # reads OPENAI_API_KEY from environment


@app.post("/summarize", response_model=SummarizeTextResponse)
def summarize(request: SummarizeTextRequest):
    """Summarize free-form text through the OpenAI-backed API endpoint.

    Args:
        request: Request model containing the source text to summarize.

    Returns:
        A validated summary payload with the summary, source word count, and key topics.
    """
    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {
                    "role": "system",
                    "content": (
                        "You are a summarizer. Given text, return a JSON object with: "
                        "summary (2-3 sentences), word_count (of the original text), "
                        "and key_topics (list of 2-4 topics). "
                        "Return ONLY valid JSON, no other text."
                    ),
                },
                {"role": "user", "content": request.text},
            ],
            temperature=0,
            response_format={"type": "json_object"},
        )
        result = json.loads(response.choices[0].message.content)
        return SummarizeTextResponse(**result)
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Model call failed: {e}")

Run and test:

uvicorn app:app --reload
curl -X POST http://localhost:8000/summarize \
  -H "Content-Type: application/json" \
  -d '{"text": "FastAPI is a modern Python web framework for building APIs. It uses type hints for validation and generates OpenAPI documentation automatically. It is built on top of Starlette and Pydantic."}'

Expected output (content will vary, structure should not):

{
  "summary": "FastAPI is a Python web framework that uses type hints for validation and auto-generates API documentation. It is built on Starlette and Pydantic.",
  "word_count": 30,
  "key_topics": ["FastAPI", "Python", "API", "Pydantic"]
}

If you get a response with all three fields, the model call is working. If you get a 502, check your API key and network connection.

Multi-turn conversations

Add conversation state management. Create conversations.py:

# conversations.py

# In-memory store — fine for learning, not for production
_conversations: dict[str, list[dict]] = {}

SYSTEM_PROMPT_TEXT = "You are a helpful assistant. Keep responses concise."


def get_history(conversation_id: str) -> list[dict]:
    """Return one conversation thread, creating it on first access.

    Args:
        conversation_id: Stable identifier for the conversation thread.

    Returns:
        The mutable list that stores prior user and assistant messages for the thread.
    """
    if conversation_id not in _conversations:
        _conversations[conversation_id] = []
    return _conversations[conversation_id]


def append_message(conversation_id: str, role: str, content: str):
    """Append one chat turn to the in-memory conversation store.

    Args:
        conversation_id: Stable identifier for the conversation thread.
        role: Message role to record, usually ``user`` or ``assistant``.
        content: Text content for the new message.

    Returns:
        None. The conversation store is updated in place.
    """
    history = get_history(conversation_id)
    history.append({"role": role, "content": content})

Add the conversation endpoint to app.py. The conversation store keeps only the user and assistant turns. Each provider example below applies the system prompt in the way its API expects.

Pick your provider:

# Add to app.py
from conversations import get_history, append_message, SYSTEM_PROMPT_TEXT


class ChatRequest(BaseModel):
    conversation_id: str
    message: str

class ChatResponse(BaseModel):
    conversation_id: str
    response: str
    message_count: int


@app.post("/chat", response_model=ChatResponse)
def chat(request: ChatRequest):
    """Continue one conversation through the OpenAI-backed chat endpoint.

    Args:
        request: Chat request containing the conversation ID and latest user message.

    Returns:
        A response with the assistant reply and the updated message count for the thread.
    """
    # Get history, add user message
    history = get_history(request.conversation_id)
    append_message(request.conversation_id, "user", request.message)
    messages = [{"role": "system", "content": SYSTEM_PROMPT_TEXT}, *history]

    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            temperature=0,
        )
        assistant_msg = response.choices[0].message.content
        append_message(request.conversation_id, "assistant", assistant_msg)

        return ChatResponse(
            conversation_id=request.conversation_id,
            response=assistant_msg,
            message_count=len(history),
        )
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Model call failed: {e}")

Test multi-turn behavior:

# First message
curl -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "test-1", "message": "My name is Kal-El."}'

# Second message — the model should remember the name
curl -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "test-1", "message": "What is my name?"}'

# Different conversation — the model should NOT know the name
curl -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "test-2", "message": "What is my name?"}'

The second call should respond with "Kal-El." The third call (different conversation ID) should not know the name. This confirms your service owns the conversation state, not the model.

Schema-constrained extraction

Add a structured extraction endpoint. This uses structured output constraints to force the model to return exactly the shape you specify. The Pydantic models are the same regardless of provider:

# Add to app.py

class BugReport(BaseModel):
    title: str
    steps_to_reproduce: list[str]
    expected_behavior: str
    actual_behavior: str
    severity: str  # "low", "medium", "high", "critical"

class ExtractRequest(BaseModel):
    text: str

Notice the difference from the OpenAI summarizer path above: it uses {"type": "json_object"} (JSON mode, which guarantees valid JSON, but the model decides the shape). This extraction endpoint uses schema-constrained mode, where the API guarantees the response matches your exact schema, including the severity enum. Some providers expose that through a different parameter name, but the concept is the same. Schema-constrained mode is the stronger contract. Use it when you know the exact output shape; use JSON mode when the shape is more flexible.

Pick your provider:

OpenAI's response_format with json_schema type provides the strictest schema-constrained output.

@app.post("/extract/bug-report", response_model=BugReport)
def extract_bug_report(request: ExtractRequest):
    """Extract a structured bug report with the OpenAI-backed endpoint.

    Args:
        request: Request model containing the raw bug description text.

    Returns:
        A validated ``BugReport`` parsed from the model response.
    """
    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {
                    "role": "system",
                    "content": (
                        "Extract a structured bug report from the user's text. "
                        "Return JSON with: title, steps_to_reproduce (list of strings), "
                        "expected_behavior, actual_behavior, severity (low/medium/high/critical). "
                        "If information is missing, use 'Not specified'."
                    ),
                },
                {"role": "user", "content": request.text},
            ],
            temperature=0,
            response_format={
                "type": "json_schema",
                "json_schema": {
                    "name": "bug_report",
                    "strict": True,
                    "schema": {
                        "type": "object",
                        "properties": {
                            "title": {"type": "string"},
                            "steps_to_reproduce": {
                                "type": "array",
                                "items": {"type": "string"},
                            },
                            "expected_behavior": {"type": "string"},
                            "actual_behavior": {"type": "string"},
                            "severity": {
                                "type": "string",
                                "enum": ["low", "medium", "high", "critical"],
                            },
                        },
                        "required": [
                            "title",
                            "steps_to_reproduce",
                            "expected_behavior",
                            "actual_behavior",
                            "severity",
                        ],
                        "additionalProperties": False,
                    },
                },
            },
        )
        result = json.loads(response.choices[0].message.content)
        return BugReport(**result)
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Model call failed: {e}")

Test it:

curl -X POST http://localhost:8000/extract/bug-report \
  -H "Content-Type: application/json" \
  -d '{"text": "When I click the submit button on the login page nothing happens. I expected it to log me in or show an error. This is blocking all QA testing."}'

Expected: a JSON object with all five fields populated, severity constrained to one of the four enum values. On OpenAI, Gemini, Anthropic, Hugging Face, and local Ollama, the structured-output setting is meant to guarantee the shape and the Pydantic model gives you a second validation layer. On the Ollama Cloud fallback above, you rely on JSON mode plus BugReport.model_validate_json(...) instead.

Your first tool call

Create tools.py with a tool the model can call:

# tools.py

# Fake user database
USERS = {
    "u-101": {"name": "Kal-El Chen", "email": "kal-el@example.com", "role": "engineer"},
    "u-102": {"name": "Sam Park", "email": "sam@example.com", "role": "designer"},
}


def lookup_user(user_id: str) -> dict:
    """Return a fake user profile for the requested ID.

    Args:
        user_id: Identifier to look up in the in-memory user table.

    Returns:
        The matching user record, or an error payload when the ID is not found.
    """
    if user_id in USERS:
        return USERS[user_id]
    return {"error": f"User {user_id} not found"}


# Tool definition for the model API
TOOL_DEFINITIONS = [
    {
        "type": "function",
        "function": {
            "name": "lookup_user",
            "description": "Look up a user by their ID and return their profile",
            "parameters": {
                "type": "object",
                "properties": {
                    "user_id": {
                        "type": "string",
                        "description": "The user ID, e.g. 'u-101'",
                    }
                },
                "required": ["user_id"],
            },
        },
    }
]

Add the tool-calling endpoint to app.py. The request/response models are the same regardless of provider:

# Add to app.py
import json
from tools import lookup_user, TOOL_DEFINITIONS


class ToolChatRequest(BaseModel):
    message: str

class ToolChatResponse(BaseModel):
    response: str
    tools_called: list[str]

Now add the endpoint. The tool-call flow differs more across providers than simple completions do. Each has its own request/response shape for tool definitions, tool-call messages, and tool results. Pick your provider:

@app.post("/chat-with-tools", response_model=ToolChatResponse)
def chat_with_tools(request: ToolChatRequest):
    """Answer one message, calling ``lookup_user`` when the model asks for it.

    Args:
        request: Tool-chat request containing the latest user message.

    Returns:
        The final assistant response plus the list of tools invoked during the turn.
    """
    messages = [
        {
            "role": "system",
            "content": "You are a helpful assistant. Use the lookup_user tool when the user asks about a person.",
        },
        {"role": "user", "content": request.message},
    ]

    try:
        # First call — model may request a tool
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            tools=TOOL_DEFINITIONS,
            temperature=0,
        )

        msg = response.choices[0].message
        tools_called = []

        # If the model requested a tool call, execute it
        if msg.tool_calls:
            # Add the assistant's tool-call message to history
            messages.append(msg)

            for tool_call in msg.tool_calls:
                if tool_call.function.name == "lookup_user":
                    args = json.loads(tool_call.function.arguments)
                    result = lookup_user(args["user_id"])
                    tools_called.append("lookup_user")

                    # Add the tool result to history
                    messages.append({
                        "role": "tool",
                        "tool_call_id": tool_call.id,
                        "content": json.dumps(result),
                    })

            # Second call — model uses the tool result to answer
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=messages,
                tools=TOOL_DEFINITIONS,
                temperature=0,
            )
            msg = response.choices[0].message

        return ToolChatResponse(
            response=msg.content,
            tools_called=tools_called,
        )
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Model call failed: {e}")

Test the tool call flow:

# This should trigger a tool call
curl -X POST http://localhost:8000/chat-with-tools \
  -H "Content-Type: application/json" \
  -d '{"message": "What is the email address for user u-101?"}'
# Expected: response mentions "kal-el@example.com", tools_called: ["lookup_user"]

# This should NOT trigger a tool call
curl -X POST http://localhost:8000/chat-with-tools \
  -H "Content-Type: application/json" \
  -d '{"message": "What is 2 + 2?"}'
# Expected: response answers "4", tools_called: []

The key observation: you sent the tool definition. The model decided to call it and provided the arguments. Your code executed the function. You sent the result back. The model used it to answer. This is the foundation for everything in Module 3.

Cross-provider exercise

Make the same bug report extraction call against Anthropic. Create a small standalone script:

# cross_provider.py
import os, json
from openai import OpenAI
from anthropic import Anthropic

bug_text = (
    "When I click the submit button on the login page nothing happens. "
    "I expected it to log me in or show an error. "
    "This is blocking all QA testing."
)

system_prompt = (
    "Extract a structured bug report from the user's text. "
    "Return JSON with: title, steps_to_reproduce (list of strings), "
    "expected_behavior, actual_behavior, severity (low/medium/high/critical). "
    "If information is missing, use 'Not specified'. Return ONLY valid JSON."
)

# --- OpenAI ---
openai_client = OpenAI()
openai_resp = openai_client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": bug_text},
    ],
    temperature=0,
    response_format={"type": "json_object"},
)
openai_result = json.loads(openai_resp.choices[0].message.content)
print("=== OpenAI ===")
print(json.dumps(openai_result, indent=2))

# --- Anthropic ---
anthropic_client = Anthropic()
anthropic_resp = anthropic_client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system=system_prompt,
    output_config={
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "title": {"type": "string"},
                    "steps_to_reproduce": {
                        "type": "array",
                        "items": {"type": "string"},
                    },
                    "expected_behavior": {"type": "string"},
                    "actual_behavior": {"type": "string"},
                    "severity": {
                        "type": "string",
                        "enum": ["low", "medium", "high", "critical"],
                    },
                },
                "required": [
                    "title",
                    "steps_to_reproduce",
                    "expected_behavior",
                    "actual_behavior",
                    "severity",
                ],
                "additionalProperties": False,
            },
        },
    },
    messages=[
        {"role": "user", "content": bug_text},
    ],
)
anthropic_result = json.loads(anthropic_resp.content[0].text)
print("\n=== Anthropic ===")
print(json.dumps(anthropic_result, indent=2))
python cross_provider.py

Compare the two outputs. Notice:

  • Message format: OpenAI uses messages with a system role; Anthropic uses a separate system parameter
  • Response structure: OpenAI nests content under choices[0].message.content; Anthropic uses content[0].text
  • Structured output: OpenAI uses response_format; Anthropic uses output_config
  • Output content: both should produce a valid bug report, but field values may differ

The concepts are the same; the API surfaces differ. You now know enough about both to avoid lock-in assumptions.

Optional extension:

  • Gemini: port the OpenAI extraction half to google-genai and compare response_format with Gemini's response_mime_type + response_schema
  • Hugging Face: rerun the OpenAI half of this script with the Hugging Face router base URL and HF_TOKEN
  • Ollama: rerun the extraction against Ollama's chat API/client using the same system prompt and compare the response shape and JSON reliability
  • If OpenAI or Anthropic is not your primary provider, invert the exercise: start from the provider you do have, then port one smaller call to any second provider you can access

Exercises

  1. Build the summarizer endpoint and confirm it returns structured JSON from a model call.
  2. Build the multi-turn conversation endpoint. Verify the model remembers context within a conversation and does not bleed state between conversations.
  3. Build the bug report extraction endpoint. Send it freeform text and confirm it returns all required fields.
  4. Build the tool-calling endpoint with lookup_user. Verify the model calls the tool when appropriate and skips it when not needed.
  5. Run cross_provider.py (or an equivalent script for the providers you actually have configured) and note at least three differences between two provider API surfaces.
  6. Port one smaller endpoint or extraction script to a third provider path. Note what changed in client setup, model naming, structured-output support, and response parsing.

Completion checkpoint

You can:

  • Call a model API programmatically and parse the response
  • Enforce a JSON schema on the model's output using structured outputs
  • Handle invalid model responses and basic call failures without crashing, and know where retry/backoff logic belongs
  • Maintain conversation state across multiple requests using a conversation ID
  • Execute a tool call flow: model requests tool -> your code runs it -> model continues with result
  • Show the same operation working against at least two supported providers, and explain what changes when you port it to other provider surfaces

What's next

Retrieval Basics. Model calls alone will not answer repo-specific questions, so the next lesson builds the simplest retrieval pipeline and lets you watch it fail in useful ways.

References

Start here

  • OpenAI API docs — the primary API reference for message structure, tool calling, and structured outputs
  • Gemini API quickstart — Gemini setup, auth, and first requests on the direct API

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.