Introduction to Agents & the Training Ladder

Agentic AI · L-Intro

What an agent is, how a language model produces text (probabilistically), the training ladder, and a modular agent architecture we will build on for the whole term.

Learning Objectives

After this lecture you can:

  1. Recap conditional probability, the chain rule of probability, and Markov chains.
  2. State the language-modelling objective (chain rule) and why it is autoregressive.
  3. Distinguish a chatbot from an agent.
  4. Explain the training ladder: base → aligned → tool-calling.
  5. Identify the core components of an agent: model, agent loop, tool calls, planning capabilities, and memory.
  6. Describe the agent's core and its boundary components, and name the trust boundary.

Part I — Probability Recap and Language Models

A language model is a probability distribution over token sequences, so we start with the probability we need.

📖 More in detailed review: http://christianherta.de/lehre/algorithmic-fundations-of-robotics-and-artifical-intelligence/math/probabilities.html

Outcome, Event & Sample Space

  • Outcome (elementary event): a single possible result of a random experiment.
    • Die roll: one face, e.g. $3$.
    • All outcomes form the sample space $\Omega=\{1,2,3,4,5,6\}$.
  • Event: any subset of $\Omega$ — one outcome or a collection.
    • e.g. "even" $=\{2,4,6\}$ or
    • "greater than 4" $=\{5,6\}$.
    • $P(\text{event})=\sum$ of its outcome probabilities.

Random Variables

A random variable is a function that assigns a numerical value to each outcome in the sample space. Random variables are usually denoted by capital letters, e.g. $X$ or $Y$.

Its set of possible values is written $\mathrm{Val}(X)$.

Die example: let $X=1$ if the face is odd $\{1,3,5\}$, else $X=0$ (even).

  • $P(X{=}1)=P(\{1,3,5\})=3/6=0.5$ and
  • $P(X{=}0)=0.5$.

Notation ("abuse of notation"): we identify a specific distribution by its argument:

  • $P(X)$ denotes the whole distribution of $X$ and
  • $P(Y)$ that of $Y$;

$P(X{=}x)$ is a single number.

Short notation: $P(x)$ for $P(X{=}x)$ if not ambiguous.

Discrete Probability Distributions

A discrete probability distribution defines the likelihood of all possible outcomes for a discrete random variable.

Formally it assigns a probability to every value with $$P(X{=}x)\ge 0 \qquad\text{and}\qquad \sum_{x\in \mathrm{Val}(X)} P(X{=}x)=1.$$

Joint Distribution

A joint distribution gives the probability of combinations of two (or more) random variables: $$ P(X=x, Y=y) \ge 0, \qquad \sum_{x}\sum_{y} P(X{=}x,\, Y{=}y) = 1. $$

Die example ($X$ odd/even, $Y=\mathbb{1}[\text{face}>3]$ — the indicator: $1$ if the face is greater than $3$, else $0$):

$P(X,Y)$ $Y{=}0\ (\le 3)$ $Y{=}1\ (>3)$
$X{=}1$ (odd) $2/6$ $1/6$
$X{=}0$ (even) $1/6$ $2/6$

It generalises to many variables: $P(X_1,\dots,X_n)$ — e.g. the probability of a whole sequence of outcomes (e.g. tokens).

Marginal & Independence

  • Marginal: recover one variable by summing the joint over the other
    • $P(X)=\sum_y P(X,Y{=}y)$.
  • Independence: $P(X,Y)=P(X)\,P(Y)$ — knowing one says nothing about the other.
    • Notation: $X \perp Y$

Conditional Probability

$$ P(X\mid Y) = \frac{P(X, Y)}{P(Y)}, \qquad P(Y)>0 $$

"Probability of $X$ given $Y$."

Conditional Independence

$X$ is independent of $Y$ given $Z$ if $$P(X,Y \mid Z)=P(X \mid Z)\,P(Y\mid Z)$$ or, equivalently, $$P(X \mid Y,Z)=P(X \mid Z).$$

Notation: $X \perp Y \mid Z$

Tokens & the Vocabulary

Token: the atomic unit of text a language model reads and produces

  • roughly a word or a word-piece (subword).
  • E.g. "tokenization" might split into "token" + "ization".
  • Note: Tokens are not always whole words.

Vocabulary $V$: the fixed, finite set of all tokens the model knows (typically ~50k–200k).

Every prompt and every reply is a sequence of tokens from $V$.

How text is split into tokens (tokenization) is covered in → L-Att.

Notation: $W_t$ (capital) is the token at position $t$ as a random variable over $V$; a concrete (generic) token is lowercase $w_t$. Write $W_{1:T} := (W_1, W_2, \dots, W_T)$ for the random variable of sequence of $T$ tokens.

A concrete text is a token sequence

$$w_{1:T} = w_1 w_2 w_3 \dots w_T$$ (each $w_t \in V$).

The Chain Rule of Probability

Notation: $W_{1:t-1}$ is the prefix (token sequence) before position $t$.

Any joint factorises into conditionals: $$ P(W_{1:T}) = P(W_1)\,P(W_2\mid W_1)\cdots P(W_T\mid W_{1:T-1}) = \prod_{t=1}^{T} P(W_t\mid W_{1:t-1})$$

The identity behind language modelling:

  • model only the next-token conditional,
  • multiply to score any sequence.

Markov Chains & the Markov Assumption

A sequence is a (first-order) Markov chain if the next state (here token) depends only on the current: $$ P(W_t\mid W_{1:t-1}) = P(W_t\mid W_{t-1}), $$ captured by a transition matrix $P_{ij}=P(W_t{=}j\mid W_{t-1}{=}i)$, where the indices $i,j$ label the vocabulary tokens ($W_t{=}j$ means "$W_t$ is the $j$-th token"; a generic token value is $w_t$).

As conditional independence. The Markov assumption says that given the present $W_{t-1}$, the next token $W_t$ is independent of the older past $W_{1:t-2}$ — i.e. $W_t \perp W_{1:t-2}\mid W_{t-1}$ (cf. Conditional Independence above). In the bigram model the total probability is: $$P(W_{1:T}) = P(W_1) \prod_{t=2}^T P(W_t \mid W_{t-1})$$

  • $n$-gram LMs assume a fixed window of the last $n-1$ tokens: $P(W_t\mid W_{1:t-1}) \approx P(W_t\mid W_{t-n+1:\,t-1})$ — cheap but forgetful (a bigram, $n{=}2$, is the first-order case above).
  • Modern LLMs drop the assumption: they condition on the full history $W_{1:t-1}$ (up to the context window). (This is why context length matters — the context window.)
In [1]:
# A first-order Markov (bigram) language model, estimated by counting.
from collections import Counter, defaultdict
import numpy as np

text = "the cat sat on the mat . the cat ate the fish . the dog sat on the log .".split()

# Count bigram transitions: P(next_token | prev_token)
counts = defaultdict(Counter)
for prev_token, next_token in zip(text[:-1], text[1:]):
    counts[prev_token][next_token] += 1


def get_conditional_dist(prev_token: str) -> dict[str, float]:
    token_counts = counts[prev_token]
    total_count = sum(token_counts.values())
    return {word: count / total_count for word, count in token_counts.items()}


print("P(next | 'the') =", get_conditional_dist("the"))
print("P(next | 'cat') =", get_conditional_dist("cat"))

# Sample a sequence using the Markov conditionals
rng = np.random.default_rng(seed=0)
current_token = "the"
generated_sequence = ["the"]

for _ in range(8):
    dist = get_conditional_dist(current_token)
    if not dist:
        break
    words, probabilities = list(dist.keys()), list(dist.values())
    current_token = rng.choice(words, p=probabilities)
    generated_sequence.append(current_token)

print("Sampled text:", " ".join(generated_sequence))
P(next | 'the') = {'cat': 0.3333333333333333, 'mat': 0.16666666666666666, 'fish': 0.16666666666666666, 'dog': 0.16666666666666666, 'log': 0.16666666666666666}
P(next | 'cat') = {'sat': 0.5, 'ate': 0.5}
Sampled text: the fish . the cat ate the fish .

The bigram model is Markov — it uses only the last word, so it quickly loses coherence. An LLM conditions on the whole prefix, which is why it stays on topic. Same chain rule, no Markov shortcut.

From Probability to Neural Language Models

So far the model is just an abstract distribution $P(W_t \mid W_{1:t-1})$. In modern LLMs this conditional is computed by a neural network — a Transformer — trained on huge text corpora. Its internals (tokenization, attention, positional encoding, the context window, and the KV-cache) are the subject of Inside the Model.

For now we only need the interface: prompt in → a probability distribution over the next token out.

Part II — From Language Models to Agents

Working definition of an AI Agent

An AI agent is an aligned LLM (large language model) placed in a loop where it can use tools to act and observe the results, keeps memory across steps, and works toward a goal — often proactively — instead of only replying once.

Compactly: Agent = aligned LLM + tools + memory (+ planning & proactivity), run in a loop.

Intelligence as Rationality (Russell & Norvig, 2021)

The standard AI-Book of Russell & Norvig (2021) defines intelligence as rationality—doing the right thing. What counts as the right thing is defined by the objective that we provide to the agent, e.g. to maximize an expected performance measure given percepts and prior knowledge.

Rational agent (Russell & Norvig, 2021, §1.1.4). A rational agent is one that acts so as to achieve the best outcome or, when there is uncertainty, the best expected outcome — i.e. it selects the action expected to maximise its performance measure, given its percepts and prior knowledge (R&N, §2.2).

Value Alignment Problem

"The problem of achieving agreement between our true preferences and the objective we put into the machine is called the value alignment problem: the values or objectives put into the machine must be aligned with those of the human." (Russell & Norvig, 2021, §1.1.5, p. 23)

The Training Ladder: Base → Aligned Chat Model → Aligned Tool-Calling Model

Training on large corpora results in a base model (aka foundation model):

  • it predicts the next token.
  • a document completer, not a helper.

Two further training stages turn the base model into a model which can be used for an agent:

  • Aligned chat model (for a chatbot): fine-tuned to follow instructions.
  • Aligned tool-calling model (for an agent): fine-tuned to request tools.

Note. The chain rule $P(W_{1:T})=\prod_t P(W_t\mid W_{1:t-1})$ is just the autoregressive factorization — it holds for every rung (base, aligned, tool-calling). Alignment doesn't change the maths; it reshapes the learned conditional $P(W_t\mid W_{1:t-1})$ itself, shifting probability mass toward helpful, instruction-following continuations.

Alignment: Base Model → Chatbot

A base model continues text; it doesn't "answer" — its (standard) training objective is next-token prediction, not "follow the user's instructions", so the two come apart (Ouyang et al., 2022, §1; the base model itself: Brown et al., 2020).

Example. Ask a base model "What is the distance from Earth to the Moon?" and a very typical continuation is more questions"What is the distance from Earth to the Sun? To Venus? …" — because on the web a question is often followed by more questions. Answering is just one possible completion, not a preferred one.

Alignment fine-tunes it to behave like a helpful chatbot:

  • SFT (supervised fine-tuning): train on many (instruction, good answer) pairs → the model learns to follow instructions.
  • Preference optimization (RLHF / RLAIF / DPO): score candidate answers by human preference and tune toward the preferred ones → helpful, honest, harmless (the HHH criteria; Askell et al., 2021 — adopted by InstructGPT, Ouyang et al., 2022). (RLHF = Reinforcement Learning from Human Feedback; RLAIF = Reinforcement Learning from AI Feedback; DPO = Direct Preference Optimization.)
  • + chat template (system / user / assistant roles).

Result: an aligned chat model = a chatbot — it converses and follows instructions, but it is reactive and talk-only.

The Pipeline Stages Behind the Rungs

The three rungs say what a model can do. The field's own vocabulary for when each capability is installed has meanwhile settled on three named stages (Tu et al., 2025):

  • Pre-training — next-token prediction on web-scale corpora. Produces the base model.
  • Mid-trainingthe same next-token objective on a curated blend (high-quality domain data, QA pairs, CoT traces, instruction and tool-use data) under a decaying learning rate. It amplifies targeted capabilities — mathematics, reasoning, coding, tool use, long context, multilinguality — while a reserved share of general data preserves what pre-training built.
  • Post-training — a different objective: SFT and RL on alignment data (instruction tuning, preference optimization, RL with verifiable rewards, tool-calling and structured-output SFT, safety).

Chatbot → Agent

Unlike single-turn chatbots that process one input and pause, an AI agent runs in a continuous loop:

  • Observes: Receives user messages, tool outputs, or sensor data.
  • Reasons: Evaluates current progress and plans the next move.
  • Acts: Triggers APIs, runs code, or calls tools.

It repeats this sequence until it completes the goal or requests human assistance.

Structural challenges

Transitioning from a simple chatbot to an autonomous agent exposes key challenges that a single LLM call cannot solve alone:

  • Persistence: Maintaining long-term context, history, and failure logs across turns and days.
  • Grounding: Connecting to real-world, up-to-date knowledge sources.
  • Action: Interfacing directly with tools, databases, and APIs.
  • Coordination: Enabling multi-agent collaboration, delegation, and reasoning for high-complexity tasks.
  • Safety: Applying robust guardrails, human oversight, and fail-safes during uncertain operations.

The Runtime — What Executes the Tools

The runtime is the program hosting the model — everything that is not the model itself. It is everything wrapped around the LLM — model plus runtime is the agent. Its jobs:

  • Advertise the available tools (names, arguments, schemas) to the model.
  • Parse the model's tool-call request and execute the actual function.
  • Feed the result back to the model and drive the loop.
  • Enforce policy — the model only requests; the runtime decides and executes.

This is the tool gateway + agent loop of the agent architecture (Agent Control and Its Boundaries in the lecture note). Because the model cannot act on its own, the runtime is also the security boundary.

Talking to a Model: Messages & the System Prompt

The model is called with a list of role-tagged messages, not a single string:

  • system-prompt: standing instructions / persona, sent first; sets how the model should behave (tone, rules, role). Treated as higher priority than user text — a behaviour learned during alignment (the chat template), not a hard guarantee (cf. prompt injection).
  • user: the human's input.
  • assistant: the model's replies (and, later, its tool-call requests).
  • for agents additionally tool (see below): results handed back from a tool.
[
    {"role": "system", "content": "You are a terse assistant; answer in one sentence."},
    {"role": "user",   "content": "What is a token?"},
    ...
]

The system prompt is your main knob for behaviour — you'll change it in the lab.

Crucial Insight: LLM Statelessness

The model does not remember previous turns. On every new turn, the runtime re-sends the entire array of history messages (system, user, assistant, tool). If you leave past messages out, the model forgets them instantly.

Tools

A tool is a function/capability the runtime exposes to the model — a way to act on or observe the world beyond generating text:

  • read/write a file, run code, query a database
  • search the web, call an API, send a message

To use tools reliably, the model gets a fine-tuning step: tool- / function-calling training, i.e. it learns when a tool is needed and how to request one:

  • To train an LLM to use tools, the model is exposed to special chat formats during its Instruction Tuning (SFT) and Reinforcement Learning (RLAIF) phases so it learns to recognize when to pause text generation and emit a structured tool request.

The model never runs the tool itself; it requests it.

Loops

A chatbot only talks. Turn it into an agent by adding a loop to tool-use to solve a task in several steps: call a tool, read the result, decide the next move, until the task is done — the agent loop. Over the coming lectures, you'll learn different decision strategies to power this loop.

Written with the deliberation factored out, the loop commits to nothing — it is the classical agent program (Russell & Norvig, 2021, §2.4): a persistent internal state, updated from percepts, with one action selected per cycle.

$$ \begin{array}{l} \textbf{Agent-Loop}(\textit{goal}) \\ \hline \textbf{Input: } \textit{goal} \text{; a runtime providing the tools; a step budget } B \\ \textbf{Output: } \text{the result} \\ \hline 1: \quad \textit{state} \gets \text{Init}(\textit{goal}) \\ 2: \quad \textbf{while } \neg\,\text{Done}(\textit{state}) \textbf{ and } \text{steps} < B \textbf{ do} \\ 3: \quad \qquad a \gets \text{Decide}(\textit{state}) \qquad \text{// the only line a strategy changes} \\ 4: \quad \qquad o \gets \text{Execute}(a) \qquad \text{// the runtime acts; the model never does} \\ 5: \quad \qquad \textit{state} \gets \text{Update}(\textit{state}, a, o) \\ 6: \quad \textbf{return } \text{Result}(\textit{state}) \\ \hline \end{array} $$

where:

  • $a$: Action
  • $o$: Observation
  • $state$: for an LLM-agent this is the context.

Three names carry everything a deliberation strategy decides:

  • what $state$ is,
  • how $Decide$ picks, and
  • what makes $\text{Done}$ true.

Line 4 is the security boundary — the model requests, the runtime executes. The step budget $B$ is there because line 3 may never choose to stop.

Planning: Reactive vs. Deliberate

To use external tools effectively, an LLM must decide how to sequence its actions. Systems generally fall into three planning paradigms:

  • Implicit Planning (ReAct - Reasoning and Acting)(Yao et al., 2023) The model emits an action, receives an observation, and chooses the next step. Simple, but vulnerable to local minima and compounding errors.
  • Explicit Plan Generation: The LLM breaks a complex goal into a structured DAG (Directed Acyclic Graph) (e.g. JSON) or plan file before executing.
  • Search-based Planning: Treats planning as a tree search over multiple potential execution paths. The model branches into multiple candidate actions at each step, evaluates intermediate progress via a self-critique/reward heuristic, and uses search algorithms like Breadth-First Search (BFS) to explore, backtrack, and select the optimal trajectory.

Structured Tool Calls (JSON)

The model requests a tool by emitting a structured tool call. Commonly a JSON object naming the tool and its arguments, matching a schema the runtime advertised (JSON is the native format; some systems use other encodings):

{ "name": "read_file", "arguments": { "path": "notes.md" } }

The runtime parses the JSON, runs the function, and feeds the result back to the model. Chaining request → execute → result is the agent loop.

Note: Some model provider (e.g. OpenAI) emit an escaped JSON string in arguments.

Memory

So far each request is independent. Memory lets an agent carry information across turns — and even across restarts:

  • Short-term: the running conversation (the context sent each turn).
  • Long-term: Facts and preferences are persisted to storage as text files. To find them later, they are indexed using embeddings (vectors). The system retrieves the correct text file via semantic similarity and feeds that text into the LLM as its long-term memory.

Because the model is stateless (Part I), memory must be managed by the runtime — stored, retrieved, and, when it grows too large, summarised (compaction). (Details: retrieval and compaction, later in the course.)

Proactivity

Some agents can act on their own, without a fresh prompt:

  • A heartbeat daemon wakes the agent on a timer (e.g. every few minutes).
  • On each tick it may check for new information and decide to act — remind you, fetch news, follow up on a task.

Sometimes agents without proactivity are called assistants.

Core Capabilities of an Agent

Four capabilities turn a static language model into an autonomous actor — each with a concrete algorithmic form:

Capability What it provides Mathematical / algorithmic form Course
Tools hands — interact with the outside world function schemas & an execution API → L-ReAct
Memory a past — context survives across turns / time vector spaces $\mathbb{R}^d$, KV-cache, JSONL logs → L-Embed, → L-Att, → L-RAG, → L-Memory
explicit Planning (optional) a future — decompose goals, search trajectories, replan plan schemas, DAGs, $A^*$ search, MDP policy → L-Decomp, → L-ToT, → L-MDP
Proactivity (optional) initiative — act unprompted on timers / events heartbeat daemons, background schedulers → L-Orch

Chatbot vs Agent — The Full Picture

Putting the pieces together:

Capability Chatbot Agent
Converse
Call tools (act)
Multi-step loop
Memory across turns limited
Plan / decompose (goals → sub-tasks) ✅ (often)
Act unprompted (proactivity) ✅ (often)

Agent = aligned LLM + tools + memory (+ planning & proactivity), run in a loop

Agent Capability Levels

Beyond the training ladder (how the model is made), agents differ in how much the system around the model does. A useful capability ladder (Gulli, 2025):

  • Level 0 — Core reasoning engine: a standalone, stateless LLM — no tools, memory, or live data. (Part I above; model internals come later in the course.)
  • Level 1 — Connected problem-solver: model + tools — gather & process external info over multiple steps (web search, RAG, specialised APIs for accuracy) via a ReAct / function-calling loop. (.)
  • Level 2 — Strategic problem-solver: multi-step planning plus context engineering — strategically selecting, packaging & managing the most relevant info per step to curate the model's limited attention (the context budget). Also self-reflection (Tree-of-Thoughts, Plan-and-Solve), proactive / continuous operation, and self-improvement (refining its own prompts/context).
  • Level 3 — Collaborative multi-agent systems: a team of specialists (division of labour, like an organisation) that delegate, negotiate, or run under a supervisor. (.)

Two different ladders. The training ladder (base → aligned → tool-calling) is about the model; these capability levels are about the system built around it.

Context Engineering — A First Look

An LLM only "knows" what is in its context for this call (it is stateless, see above). Context engineering is the discipline of deciding what to put there: selecting, packaging and trimming the most relevant information — the system prompt, retrieved documents, tool outputs, memory / interaction history, and implicit data (user identity, session & environment state) — so the model's limited attention is spent on what matters.

  • Too little context → the model lacks the facts it needs.
  • Too much → it drowns in noise, and every token costs latency and money.

Richness and budget (Gulli, 2025).

Output quality often depends more on the context you assemble than on the model itself — a strong model still underperforms with a poor informational environment. The finite window is why the agent system must also select, not only add.

Prompt engineering vs. context engineering.

  • Prompt engineering is the narrower sibling: crafting the wording and structure of a single instruction — role, examples (few-shot), output format, "think step by step" — to steer one call.
  • Context engineering is the broader discipline of choosing what information fills the whole context across steps (system prompts, CoT, tool descriptions).

Who does it? Context engineering is the job of the agent runtime and its developer — the system prompt, retrieval, memory and compaction are assembled automatically each call, around the user's message. The end-user just asks; the agent engineers the context.

Limits & Responsible Use ⚖️

Agents are powerful but not infallible — keep the limits in view from day one:

  • Hallucination. An LLM samples plausible tokens, not verified facts — so it can state wrong things fluently and confidently. * (mitigated by grounding / guardrails, measured by factuality evaluation.)
  • Non-determinism. Sampling makes outputs vary run-to-run; repeatability needs low temperature and care.
  • Where agents fail. Errors compound over multi-step tasks, tools can be misused, and autonomy raises the safety/ethics stakes.

Agent Control and Its Boundaries

One component holds the control and every dependency on something outside the agent is reached through a component of its own — a common, representative division, though simple agents discharge several of these duties in one place:

The agent (the runtime)requestanswercontexttext / tool-call requestrequested callobservationChannels chat UI · CLI ·messaging · APIAPI gateway the frontdoorauthentication · sessionrouting · rate limitingAgent Controlthe agent loop · sessionmemoryModel proxy/LLM Gatewayprovider routing · keys ·cost · cachingTool gateway the trustboundaryallowlist · approval · toolexecutionModel (LLM) hosted APIor local weightsTools and effects files ·shell · HTTP · otherservices
  • Agent Control. It holds the control flow: it calls the model, reads the answer, issues the call the model requested, and repeats. It keeps the session memory, and it reaches nothing outside itself directly. This component is named after the agent loop it runs, and the two names are used interchangeably in this course.
  • One boundary component per external dependency. Agent Control reaches the user through the API gateway, the model through the model proxy, and the world through the tool gateway. Each is exchangeable because the interface belongs to Agent Control: changing the model provider changes the proxy alone.
  • Only one of the three is a trust boundary. The tool gateway authorizes an action the model proposed, and executes it — the model never executes anything. The API gateway authenticates a caller and the model proxy routes a call; both are useful, and neither decides whether an effect on the world may happen.

*This division is not one product's design — it is the shape most agent runtimes converge on.

(The runtime = everything inside the box — Agent Control and its boundary components; *not the model.)*

Practice Framing: Model + Harness, Workflows vs. Agents

Two key insights from production systems reinforce why agency requires both training and software architecture:

  • Model + Harnessharness (also called Scaffold) is the practitioner's name for what we called the runtime (Agent Control and its boundary components).
    • The Model provides the core reasoning and tool-calling capacity (learned via the training ladder).
    • The Harness is the surrounding runtime — the modular architecture (gateways, tool APIs, memory, and permissions) that hosts the model.
    • It is the same agent formula, regrouped by who builds what: aligned LLM = the model; tools + memory + loop (+ proactivity) = the harness.
    • "The model is the driver; the harness is the vehicle." You cannot engineer real agency purely by wrapping base models in if/else conditions.
  • Workflows vs. Autonomous Agents
    • Workflows: Predefined code paths with LLM nodes for specific processing steps. Highly predictable and cheaper.
    • Agents: Dynamic loops where the model chooses its own execution path. Ideal for open-ended tasks where steps cannot be known in advance.

In Practice / This Week's Lab

All hands-on work is in the exercises notebook (lecture-01-Intro-exercises.ipynb):

  • Part A — theory & calculations: conditional probability, the chain rule and statistical independence; a bigram model estimated by counting; the training ladder and the pipeline stages; chatbot vs agent and the core and its boundaries; the agent loop and the planning paradigms.
  • Part B — lab: set up Ollama, call a local tool-calling model via the OpenAI client, see that the model is stateless — memory exists only if you resend the history, and the token bill grows quadratically when you do — and inspect a structured tool call.
  • Part C — reflection: an open question on critical thinking in language models.

Work through all of it in the lab session.

Summary

  • Part I: an LLM is an autoregressive distribution $P(W_{1:T})=\prod_t P(W_t\mid W_{1:t-1})$.
  • base → chatbot: alignment (SFT + RLHF/DPO) makes it follow instructions — reactive, talk-only.
  • chatbot → agent: tool-calling training lets it request tools via structured JSON calls; the runtime executes them.
  • Agent = aligned LLM + tools + memory (+ planning & proactivity), run in a loop
  • The agent's modules: chat model · Agent Control, i.e. the agent loop (the control + session memory) · API gateway · model proxy · tool gateway (the trust boundary).

References

Peer-reviewed papers

  • Brown, Tom B., et al. "Language Models are Few-Shot Learners." Advances in Neural Information Processing Systems. Vol. 33. 2020. arXiv:2005.14165. — the base model; the origin of the term in-context learning and the zero-/one-/few-shot spectrum.
  • Caballero, Ethan, et al. "Broken Neural Scaling Laws." International Conference on Learning Representations. Vol. 2023. 2023. arXiv:2210.14891. — a plain power law is strictly monotonic and has no inflection point; breaks, and the result that one cannot be extrapolated from below.
  • Hoffmann, Jordan, et al. "An empirical analysis of compute-optimal large language model training." Advances in Neural Information Processing Systems. Vol. 35. 2022. arXiv:2203.15556. — Chinchilla: parameters and training tokens should be scaled equally, and why the earlier estimate was biased by a fixed learning-rate schedule.
  • Ouyang, Long, et al. "Training language models to follow instructions with human feedback." Advances in Neural Information Processing Systems. Vol. 35. 2022. arXiv:2203.02155. — SFT + RLHF; why a base model does not follow instructions.
  • Yao, Shunyu, et al. "ReAct: Synergizing Reasoning and Acting in Language Models." International Conference on Learning Representations. Vol. 2023. 2023. arXiv:2210.03629. — the ReAct loop.
  • Yao, Shunyu, et al. "Tree of Thoughts: Deliberate Problem Solving with Large Language Models." Advances in Neural Information Processing Systems. Vol. 36. 2023. arXiv:2305.10601. — search-based planning.

Preprints & other non-peer-reviewed papers

  • Askell, Amanda, et al. "A General Language Assistant as a Laboratory for Alignment." arXiv preprint arXiv:2112.00861 (2021). — the HHH criteria (helpful, honest, harmless).
  • Kaplan, Jared, et al. "Scaling Laws for Neural Language Models." arXiv preprint arXiv:2001.08361 (2020). — the power-law dependence of pre-training loss on parameters, data and compute, each taken separately.
  • Tu, Chengying, et al. "A Survey on LLM Mid-training." arXiv preprint arXiv:2510.23081 (2025). — the three pipeline stages behind the rungs (pre-, mid-, post-training), and the definition that makes the boundary an objective rather than a dataset.

Textbooks & monographs

  • Gulli, Antonio. Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems. Springer Nature, 2025. — agent capability levels.
  • Russell, Stuart, and Peter Norvig. Artificial Intelligence: A Modern Approach. 4th ed., Pearson, 2021. — AI as rationality; the rational agent; the standard model (§1.1, §1.1.4, §2.2); the agent program — a persistent state updated from percepts, one action selected per cycle (§2.4).

Blogs, documentation & other web sources

  • Lieret, Kilian A., and Carlos E. Jimenez. mini-swe-agent: The Minimal AI Software Engineering Agent. GitHub repository, v2.4.6, 2026. — the security boundary relocated to the process: one subprocess for each action. https://github.com/SWE-agent/mini-swe-agent
  • Nakajima, Yohei. BabyAGI. GitHub repository, 2023 (archived 2024). — a planning agent with no tools and no session memory. https://github.com/yoheinakajima/babyagi_archive
  • Nakajima, Yohei. BabyAGI: An Experimental Framework for a Self-Building Autonomous Agent. GitHub repository, v0.1.2, 2024. — the registry above the agent rather than beneath it. https://github.com/yoheinakajima/babyagi
  • Nakajima, Yohei. BabyAGI 2o: The Simplest Self-Building Autonomous Agent. GitHub repository, 2024. — the fused agent loop, and the absent tool gateway. https://github.com/yoheinakajima/babyagi2o
  • Schluntz, Erik, and Barry Zhang. "Building Effective Agents." Anthropic Engineering, 2024. — workflows vs. agents; start simple.
  • shareAI-lab. Learn Claude Code — Harness Engineering for Real Agents. 2025. GitHub. — An Agent Product is Model and Harness.
  • Völkl, Gerhard. selmakit: A Minimal Multi-Channel Agent Framework Built on PydanticAI. GitHub repository, v0.1.23, 2026. — the lab's Selma as source: a gateway, approval gates, and a toolkit supplied by a library. https://github.com/gkvoelkl/python-selmakit