Section 1: Generative AI Building Blocks
Understanding Large Language Models (LLMs) is the foundation for building reliable Agentic AI systems. Before designing agents that plan, use tools, and manage memory, you need to know how the underlying model reads text, tracks context, and generates responses—and why it sometimes gets facts wrong with complete confidence.
1.1 Tokens, Prompts, and Context Windows
LLMs do not read words the way humans do; they process text as numerical units within a fixed workspace.
- Tokenization: Breaking raw text into smaller chunks called tokens (whole words, subwords, or punctuation). A common word like
agentis usually 1 token, whileunbelievablemight split into 2–3 tokens. Roughly 100 tokens equals about 75 English words. - Prompting: The input text sent to an LLM to steer behavior. In agentic workflows, prompts combine system instructions, user requests, tool schemas, and retrieved reference data.
- Context Window: The maximum number of tokens an LLM can process in a single pass, covering both input prompt and generated output. Once exceeded, earlier tokens must be truncated or summarized, causing the model to "forget" them.
1.2 Next-Token Prediction and Hallucinations
An LLM generates text through next-token prediction. Given input tokens (e.g., ["The", "dog", "sat", "on"]),
the model converts them into numerical vectors and computes a probability distribution over its vocabulary—assigning higher probability
to "the" and lower scores to alternatives like "a" or "mat"—then appends the chosen token and repeats.
Because this optimizes for statistical plausibility rather than factual truth, models can hallucinate:
- No built-in fact-checker: The model predicts patterns learned during training rather than querying a live database of verified facts.
- Fluent pattern completion: When asked about an obscure event or private company policy, the model smoothly fabricates names, dates, or citations that match the expected format.
Worked Examples: Context Budgets & Hallucination Control
Example 1 — Managing a Context Window: Suppose an agent uses an LLM with an 8,000-token context window.
You want to pass a 1,000-token system prompt, a 6,500-token customer history log, and reserve 1,500 tokens for the reply.
Total: 1,000 + 6,500 + 1,500 = 9,000 tokens—exceeding the ceiling by 1,000 tokens. Sending this raw causes an API error
or silent truncation of system rules. Solution: Reserve fixed budgets (1,000 system + 1,500 output = 5,500 remaining)
and retrieve or summarize only the most relevant 5,000 tokens of history.
Example 2 — Preventing Fluent Fabrication: Asked "What is the SLA for our internal Billing v3 API?", an ungrounded LLM may invent "99.95% uptime." Grounding the prompt with retrieved Billing v3 docs and instructing the model to abstain when evidence is missing directly counteracts pattern completion.
1.3 Function / Tool Calling
Tool calling bridges a text-predicting LLM with real software systems. A critical architectural rule: the LLM never executes tools itself. The model emits a structured JSON proposal naming a function and its arguments; your application code validates the proposal, enforces permissions, executes the function, and returns the result to the model.
# 1. Tool schema provided to the model
TOOL_SCHEMA = {
"name": "search_runbooks",
"description": "Search internal engineering runbooks by keyword and service.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"service": {"type": "string", "enum": ["payments", "auth", "search"]}
},
"required": ["query"]
}
}
# 2. Model returns a structured proposal (NOT executed by the model):
# {"tool": "search_runbooks", "arguments": {"query": "rotate API key", "service": "payments"}}
# 3. Application code validates arguments, enforces permissions, and executes:
def execute_tool_safely(call, user_context):
if call["tool"] != "search_runbooks":
raise PermissionError("Tool not in allowlist")
return runbook_db.search(**call["arguments"], acl=user_context.roles) 1.4 Structured Outputs: Schemas, Validation, and Retries
Modern LLM APIs support constrained decoding against JSON Schemas (via Pydantic or Zod). Production code should always pair this with:
- Schema validation: Parse JSON into a typed object and verify types, enums, and value bounds.
- Semantic validation: Check business rules the schema cannot express (e.g., confirming a cited document ID exists in the retrieved set).
- Bounded retries & fallback: Feed the exact validation error back to the model for at most 1–2 repair attempts before failing gracefully.
1.5 The Modern AI Stack & "Vibe Coding"
Production AI applications separate concerns across five layers so you can swap models, update tools, or tighten policies without rewriting everything.
- Model Providers & Models: Supply raw inference (hosted APIs or self-hosted weights), not business logic or permissions.
- Application & Orchestration Layer: Owns prompt assembly, conversation state, routing, retries, timeouts, and policy enforcement.
- Context, Skills & Tools Layer: Provides domain knowledge (RAG indexes) and reusable capabilities (APIs, databases, MCP servers).
- "Vibe Coding" — Promise and Limits: Building software by prompting AI coding assistants in natural language and iterating on outputs. Great for rapid prototypes and UI scaffolding, but generated code still requires human architectural review, automated tests, dependency audits, and security checks before shipping.
1.6 Practical Operational Constraints
- Latency Budgets: Streaming tokens improves perceived speed (Time to First Token), but multi-step loops multiply wall-clock latency. Enforce per-call and total timeouts.
- Token & Model Costs: Costs scale with input + output tokens. Use prompt caching and route simple classification tasks to smaller, cheaper models.
- Reliability & Rate Limits: Implement exponential backoff with jitter for 429/5xx errors, circuit breakers, fallback models, and human-review queues for high-stakes actions.