Part IX: Applications and Future Directions
Chapter 36: Toward General Temporal Intelligence

Foundation Agents

"I have been pretrained on a million tasks. I have forecast the weather and the markets, balanced the pole and routed the warehouse robot, played the game and read the chart. The engineers say I am general now. And yet, every morning, a new task arrives that none of my million rehearsed, and I must do the one thing my training never quite taught me: figure out, from a handful of examples and whatever I can remember, what on earth I am supposed to do."

An Agent Pretrained on a Million Tasks, Wondering What the Million-and-First Will Be
Big Picture

This is the convergence point of the entire book. Three threads that ran in parallel for thirty-five chapters meet here in a single object. From Part III came foundation models (Chapter 15): one large sequence backbone, pretrained on a vast corpus, that solves new problems zero-shot or with a handful of in-context examples. From Part VII came agents (Chapter 31): systems that perceive, remember, plan over a horizon, call tools, and act in a loop with an environment. From Part VI came the realization that sequence models are policies (Chapter 28): a Decision Transformer treats trajectories of states, actions, and returns as a language to be modeled, so the very next-token machinery that powers a foundation model can output actions. Multiply these three together and you get a foundation agent: a single generalist, pretrained decision-maker whose policy is a large sequence model, which adapts to a new task in context, remembers across a long horizon, calls tools to extend its reach, and acts across many environments without being retrained for each. This section assembles that object from its parts. It names the ingredients, surveys the 2023-2026 landscape from Gato through LLM tool-agents to robot VLA models, confronts the open problems of long-horizon reliability, grounding, evaluation, and safety, and then builds a minimal foundation-agent loop from scratch: a pretrained sequence model as the policy core, a memory, a tool, and an in-context task specification, on a toy multi-task setting. A library version follows, with the line-count reduction stated. You leave able to see the whole book as one argument that ends here.

In Section 36.2 we saw a general temporal intelligence must fuse many modalities arriving on different clocks; this section asks what it takes to also remember, plan, and act across them. This section answers with the architecture the field has converged on. A foundation agent is not a new idea bolted onto the book; it is the book, read as a single sentence. Every classical model we met returned in learned form, and every learned model we met is, at bottom, a sequence model: the Kalman filter became the RNN (Chapter 10) and the structured state-space model (Chapter 13); the MDP (Chapter 22) became a sequence model (Chapter 28); the hand-built forecaster became the pretrained foundation model (Chapter 15). The foundation agent is where the forecaster and the decision-maker, separated since Part VI, finally become one network. We use the unified notation of Appendix A throughout: $s_t$ the state or observation, $a_t$ the action, $r_t$ the reward, $\tau$ a trajectory, $\pi_\theta$ the policy parameterized by the backbone weights $\theta$.

Why give this its own section rather than a closing paragraph of Chapter 31? Because the convergence changes what an agent is. A classical agent was built per task: choose a state representation, design a reward, train a policy, deploy. A foundation agent inverts that pipeline. You pretrain once, on an enormous heterogeneous mixture of tasks, and then specify the next task not by retraining but by conditioning: a prompt, a few demonstrations, a target return, a tool description. The locus of task definition moves from the optimizer to the context window. That single shift, task-by-conditioning rather than task-by-training, is what makes the object general, and it is the thread that ties Part III's in-context learning to Part VI's return-conditioning to Part VII's tool use. The rest of this section makes the thread concrete.

The four competencies this section installs are these: to name the ingredients of a foundation agent and trace each to its home chapter; to place the major 2023-2026 systems (Gato, LLM tool-agents, robot VLA models, open-ended learners) on a single map and say what each contributes; to state the open problems that keep foundation agents from being trustworthy, and connect each to the chapter that studies it; and to build a working foundation-agent loop, from scratch and then with a framework, and measure in-context adaptation improving as examples accumulate. These are the skills that let you read the 2026 literature on generalist agents as a continuation of this book rather than a separate field.

1. The Convergence: Foundation Models + Agents + Sequences-as-Policies = Foundation Agents Beginner

A single friendly robot sprouts arms holding a crystal ball, a wrench, a memory spool, and a steering wheel from one central body, showing prediction, tools, memory, and action converging into one foundation agent.
Figure 36.4: The foundation agent is what happens when predicting, remembering, using tools, and acting stop being separate machines and become four arms of one body.

Begin with the three threads laid side by side, because the foundation agent is exactly their product and no more. A foundation model, in the sense of Chapter 15, is one large sequence backbone $f_\theta$ pretrained on a broad corpus so that it generalizes to new inputs with no or few task-specific gradient steps. An agent, in the sense of Chapter 31, is a system that closes a loop with an environment: it perceives an observation, updates an internal memory, plans, selects an action, and observes the consequence, repeating over a horizon. The sequence-model-as-policy view, from Chapter 28, is the structural insight that a policy $\pi(a_t \mid s_{\le t}, a_{

Stack these and the foundation agent writes itself. Take the backbone $f_\theta$ of the foundation model. Feed it the trajectory of an agent, the interleaved stream of observations, actions, and (optionally) returns, as the sequence it models. Train it on a mixture of trajectories drawn from a million tasks. The result is a single $\pi_\theta$ that, conditioned on the recent history and a task specification placed in its context, predicts the next action. Perception, memory, planning, and action are not four separate modules but four readings of one autoregressive pass: perception is encoding the latest observation into the context, memory is the context window (and any external store) the backbone attends over, planning is the model's learned tendency to emit action sequences that lead to high return, and action is the sampled next token. The agent loop of Chapter 31 wraps this prediction in an environment.

Formally, a foundation agent is a conditional sequence model trained to maximize the likelihood of action tokens across a task distribution $p(\mathcal{T})$:

$$\theta^\star = \arg\max_\theta \; \mathbb{E}_{\mathcal{T} \sim p(\mathcal{T})} \; \mathbb{E}_{\tau \sim \mathcal{T}} \sum_{t} \log \pi_\theta\!\big(a_t \;\big|\; c_{\mathcal{T}},\, s_{\le t},\, a_{where $c_{\mathcal{T}}$ is the task specification placed in the context (a prompt, a few demonstrations, a target return $\hat{R}$, or a tool list) and the inner expectation is over trajectories $\tau$ from task $\mathcal{T}$. At deployment the weights $\theta^\star$ are frozen; a new task is specified entirely through $c_{\mathcal{T}}$. This is the single equation of the section: pretrain across tasks, condition on the task at inference. It is the return-conditioning of the Decision Transformer (set $c_{\mathcal{T}} = \hat{R}$), the few-shot prompting of a foundation model (set $c_{\mathcal{T}}$ to demonstrations), and the tool-augmented prompt of an LLM agent (set $c_{\mathcal{T}}$ to a tool spec), all as special cases of one objective. Figure 36.3.1 draws the convergence.

Three threads of the book converge into one object Foundation modelspretrained backbone (Ch 15) Agentsperceive, plan, act (Ch 31) Sequences as policiestrajectories as tokens (Ch 28) + + Foundation Agentone sequence policy thatperceives + remembers + acts Environment/ task stream action observation, reward
Figure 36.3.1: The convergence. A pretrained sequence backbone (Chapter 15), the perceive-plan-act loop of an agent (Chapter 31), and the insight that a policy is a conditional sequence model (Chapter 28) combine into one foundation agent: a single autoregressive policy that closes a loop with an environment, specifying each new task by conditioning rather than retraining.

The unification is not merely notational tidiness; it has a consequence the rest of the section trades on. Because task definition lives in the context $c_{\mathcal{T}}$ and not in the weights $\theta$, a foundation agent can in principle take on a task it never saw in training, simply by being given the right conditioning, the way a foundation forecaster of Chapter 15 forecasts a series it never saw. The generality is bought at pretraining time and spent, almost for free, at inference time. That is the promise. The open problems of subsection four are all about how, and how far, the promise actually holds.

Thesis Thread: The Whole Book Was Building This

Trace the spine of the book and it ends here. Part I asked what makes intelligence temporal. Part II built classical forecasters by hand. Part III replaced each by hand-built forecaster with a learned sequence model and, in Chapter 15, made that model a pretrained generalist. Part IV gave it representations, Part V gave it calibrated uncertainty and the ability to keep learning. Part VI turned prediction into decision and, in Chapter 28, showed that a decision-maker is itself a sequence model. Part VII closed the loop, making the sequence model an agent that perceives, remembers, plans, and acts (Chapter 31). Part VIII made it trustworthy. The foundation agent is the point where every thread crosses: a pretrained sequence policy, calibrated and adaptive, that decides as fluently as it forecasts. The Kalman filter that opened Part II and the generalist agent that closes Part IX are the same recurrence, $h_t = f(h_{t-1}, x_t)$, scaled until it became a mind for tasks.

2. The Ingredients: Backbone, In-Context Learning, Memory and Tools, Adaptation Beginner

A foundation agent has four ingredients, and naming them precisely both demystifies the object and gives us the parts list for the from-scratch build of subsection five. Each ingredient is a chapter of this book seen from the agent's vantage.

The first ingredient is a large pretrained sequence backbone. This is the engine: a Transformer (Chapter 12) or a structured state-space model (Chapter 13), pretrained on a corpus large and diverse enough that its next-token distribution encodes broadly useful temporal structure. The backbone supplies the agent's perception (it encodes observations into representations) and its policy (its output head emits actions). Everything else is built around it. The decisive property inherited from Chapter 15 is that the backbone is frozen at deployment: it is a fixed function whose behavior is steered by what enters its context.

The second ingredient is in-context learning: the backbone's ability to infer a new task from examples placed in its context, with no weight update. This is the mechanism by which a foundation agent acquires the million-and-first task. Given a few demonstrations of a novel task, or a target return, or a tool description, the agent's behavior shifts to fit, because the pretraining taught it to treat its context as a task specification. In-context learning is what turns a fixed $\theta$ into an effectively task-conditional policy, and it is the property we measure improving with more examples in the numeric example of subsection five.

The third ingredient is memory and tools, both from Chapter 31. The backbone's context window is finite, so a long-horizon agent needs an external memory: a store it can write observations and conclusions to and retrieve from later, extending its effective horizon beyond the attention window (the reliability problem of Section 31.4 turns on getting this right). Tools extend the agent's reach beyond its own forward pass: a calculator for arithmetic it cannot do reliably, a retriever for facts it does not hold, a code interpreter, an environment simulator. The agent learns, in context, when to emit a tool call, reads the tool's result back into its context, and continues. Memory and tools are what make a bounded backbone competent over an unbounded task.

The fourth ingredient is adaptation via finetuning and alignment, the bridge to Chapter 27 (and its alignment subsection, the RLHF and preference-optimization material of Section 27.5). In-context learning adapts behavior without touching weights, but for durable skills, for safety, and for following human intent, a foundation agent is typically finetuned: supervised on demonstrations (imitation learning, the behavior-cloning of Chapter 27) and then aligned to human preferences with RLHF or direct preference optimization. Adaptation is the slow knob (it changes $\theta$) complementing the fast knob of in-context learning (it changes $c_{\mathcal{T}}$). Figure 36.3.2 summarizes the four ingredients and their two timescales.

IngredientRole in the agentHome chapterTimescale
Pretrained sequence backboneperception and policy; the frozen engineCh 15, Ch 12fixed at deploy
In-context learningacquire a new task from examples in contextCh 15per inference (fast)
Memoryextend horizon beyond the context windowCh 31per episode
Toolsextend reach beyond the forward passCh 31per step
Finetuning and alignmentdurable skills, safety, intent-followingCh 27 (RLHF, Sec 27.5)training (slow)
Figure 36.3.2: The ingredients of a foundation agent and their home chapters. Two timescales operate together: the fast loop of in-context learning, memory writes, and tool calls steers a frozen backbone per inference, while the slow loop of finetuning and alignment reshapes the weights themselves.
Key Insight: Two Knobs, Two Timescales

A foundation agent adapts on two clocks. The fast clock is in-context learning: change the context $c_{\mathcal{T}}$ and the behavior shifts immediately, with no gradient step, the way you reprogram a foundation model by editing its prompt. The slow clock is finetuning and alignment: change the weights $\theta$ and the behavior shifts durably, but at training cost. Production agents use both: the slow clock installs broad competence and safety; the fast clock specializes that competence to the task in front of the agent right now. Confusing the two is a common design error: trying to teach a durable new skill purely in context (it will not stick past the window) or finetuning for a one-off task (you have paid training cost for something a prompt could have done). Match the knob to the timescale of the change you want.

3. The 2023-2026 Landscape: Gato, Tool-Agents, VLA Models, Open-Ended Learners Intermediate

The foundation agent is not a single system but a research program, and the period from 2023 to 2026 saw four distinct lineages, each emphasizing a different ingredient from subsection two. Reading them as variations on the one objective of subsection one is what keeps the literature legible.

The first lineage is the generalist agent, whose archetype is Gato (Reed and colleagues, 2022). Gato was a single Transformer with one set of weights that played Atari, captioned images, stacked blocks with a real robot arm, and chatted, by tokenizing every modality, images, text, proprioception, button presses, into one sequence and training next-token prediction across all of them. Gato is the most literal embodiment of the subsection-one objective: one backbone, many tasks, task specified by the prompt-prefix of the current episode. Its lesson, and its limitation, was scale: it demonstrated that one network can hold many tasks, while leaving open how far in-context generalization to genuinely new tasks would carry.

The second lineage is the LLM agent with tools, the most widely deployed foundation agent of the period. Here the backbone is a large language model and the trajectory is a stream of thoughts, tool calls, and observations: the agent reasons in text (the chain-of-thought and ReAct-style interleaving of reasoning and acting), emits a tool call when it needs to compute, retrieve, or act in software, reads the result back, and continues until it answers or acts. This lineage leans hardest on tools and in-context learning: the backbone supplies general reasoning, and tools supply the grounded capabilities it lacks. It is the direct descendant of the temporal agents of Chapter 31, scaled to a foundation backbone.

The third lineage is robot foundation and vision-language-action (VLA) models, which carry the foundation agent into the physical world and connect directly to the industrial-robotics material of Section 35.5. A VLA model takes a camera image and a natural-language instruction and emits low-level robot actions, pretrained on large mixtures of robot demonstrations. The RT-2 line (Brohan and colleagues, 2023), the cross-embodiment RT-X effort (2023), and the open Octo (2024) and OpenVLA (2024) models showed that a single action backbone could transfer skills across robot bodies and instructions, exactly the cross-task generalization of subsection one, now with actions that move motors rather than tokens on a screen. The grounding problem of subsection four is sharpest here: a hallucinated action breaks a real arm.

The fourth lineage is the open-ended, continually-learning agent, which targets the part of the dream that pretraining alone does not reach: an agent that keeps acquiring tasks after deployment. Voyager (Wang and colleagues, 2023) drove an LLM agent to explore Minecraft, write and store reusable skills in a growing library, and bootstrap ever-harder tasks, an explicit external skill memory in the sense of subsection two. This lineage is where the foundation agent meets the online and continual learning of Chapter 20: the agent is not done learning when pretraining ends.

Cutting across all four is the role of the world model (Chapter 29). A foundation agent that can predict the consequences of its actions can plan by imagining rollouts before committing, rather than acting reactively. Dreamer-style agents learn a latent world model and plan inside it; the same backbone that serves as the policy can serve as the world model (predicting next observations as readily as next actions), which is why the generative and decision threads of the book fuse so naturally at this point. Planning with a learned world model is how a foundation agent buys long-horizon competence that a purely reactive policy cannot.

Practical Example: A Foundation Agent for Grid-Scale Energy Operations

Who: A national grid operator running a control room that must balance generation, storage, and demand-response across thousands of assets, the energy series threaded through Chapter 14 and Chapter 35.

Situation: They already ran separate models: a deep forecaster for demand, a separate optimizer for dispatch, a separate anomaly detector for faults, and a separate playbook of human procedures for rare events. Each was trained and maintained as its own system, and nothing transferred between them.

Problem: A novel event arrived (a coordinated outage pattern none of the per-task models had seen) and the siloed systems gave no coherent joint response; the operators improvised under time pressure.

Dilemma: Build yet another per-task model for the new event class (slow, and the next novel event would not be covered either), or move to a single agent that could perceive the whole grid state, recall similar past events, plan a response, and call the existing forecaster and optimizer as tools.

Decision: They piloted a foundation agent: a pretrained sequence backbone over grid telemetry as the policy core, an external event memory storing summaries of past incidents and their resolutions, the legacy forecaster and dispatch optimizer wrapped as tools, and the new event specified in context by a few analogous historical incidents.

How: Each control cycle, the agent encoded the latest telemetry, retrieved the most similar past incidents from memory, optionally called the forecaster tool for a demand projection and the optimizer tool for a candidate dispatch, and proposed an action for human approval, exactly the perceive-remember-plan-act loop of subsection one wrapped around a frozen backbone.

Result: On replayed historical events, the agent's in-context recall of analogous incidents let it propose coherent joint responses to event classes it had not been explicitly trained on, with the tool calls keeping its forecasts and dispatches grounded in the validated legacy systems rather than its own unverified guesses.

Lesson: A foundation agent's value in an industrial setting is not that it replaces the specialized models, it is that it orchestrates them: the backbone supplies general situational reasoning and in-context adaptation to novel events, while tools keep every quantitative claim anchored to a trusted system. Wrap your existing models as tools before you discard them.

Research Frontier: Generalist Agents in 2024 to 2026

The frontier is moving on three fronts at once. Embodied foundation models matured fast: after RT-2 and RT-X (2023), the open Octo (2024) and OpenVLA (2024) released generalist robot policies, and 2024 to 2025 brought larger cross-embodiment efforts and diffusion-policy action heads that emit smooth continuous controls, pushing VLA models toward the dexterity the energy and manufacturing applications of Chapter 35 need. Long-horizon LLM agents became a benchmark frontier: agentic coding and computer-use systems, and the SWE-bench / WebArena / OSWorld style evaluations, exposed how quickly reliability decays over many steps (subsection four), driving work on verification, self-correction, and explicit planning over learned world models. Open-ended and self-improving agents, in the Voyager lineage, now pair a foundation backbone with a growing skill library and automatic curricula, connecting to the continual learning of Chapter 20. The unifying 2026 question is the one this section's objective makes precise: how much genuinely new capability comes free from in-context conditioning on a frozen backbone, and how much still requires changing the weights? The answer sets the ceiling on how general a foundation agent can be.

4. The Open Problems: Reliability, Grounding, Evaluation, Safety Advanced

The foundation agent is the book's destination, but it is not a solved object, and intellectual honesty requires stating plainly what stands between the architecture of subsection one and a system you would trust with consequences. Four problems dominate, and each is the subject of a chapter we can now read as a prerequisite for trustworthy generality.

The first is reliability over long horizons, the failure mode that the agent material of Section 31.4 studies directly. A foundation agent acting over hundreds of steps is exposed to compounding error: a small mistake at step ten changes the context at step eleven, which makes step eleven likelier to err, and the trajectory drifts off the distribution the backbone was trained on, the covariate-shift pathology that haunts imitation learning in Chapter 27. Reliability decays roughly geometrically with horizon unless the agent can detect and correct its own errors, recover from off-distribution states, and verify intermediate results (with tools, with a world model, with explicit replanning). Long-horizon reliability is the single largest gap between impressive demos and dependable deployment.

The second is grounding: keeping the agent's outputs tied to reality rather than to its own plausible-sounding fabrications. A backbone trained to produce fluent continuations will produce a fluent continuation whether or not it is true, and an agent that acts on an ungrounded belief acts wrongly. Grounding is supplied by the tools and memory of subsection two (retrieve the fact, do not invent it; compute the number, do not guess it) and, for embodied agents, by the sensorimotor loop itself. The grounding problem is why the practical example above wrapped trusted models as tools: the backbone reasons, the tools keep it honest.

The third is evaluation, the problem of Section 31.5. How do you measure a generalist? A per-task accuracy means little when the claim is generality, and a single aggregate score hides catastrophic failures on individual tasks. Evaluating a foundation agent means probing held-out tasks (does in-context generalization actually transfer?), long-horizon tasks (does reliability hold?), and adversarial or distribution-shifted tasks (does it fail safely?), with the calibrated-uncertainty machinery of Chapter 19 telling us when the agent knows it does not know. Evaluation is hard precisely because generality means there is no fixed test set that captures the claim.

The fourth is safety and alignment, the concern of the responsible-AI material in Chapter 33 (and the safety subsection of the advanced-RL chapter, Section 26.4). An agent that acts in the world, calls tools, and pursues conditioned goals can cause real harm if its objective is misspecified, if it pursues a proxy that diverges from intent (reward hacking), or if it takes an irreversible action under uncertainty. Alignment, the slow-clock finetuning of subsection two, is how human intent is installed; safety engineering (sandboxed tools, human-in-the-loop approval for consequential actions, conservative behavior under uncertainty) is how the consequences of residual misalignment are bounded. The more capable and autonomous the agent, the more these cease to be optional.

Key Insight: Generality Multiplies Both Capability and Failure

The same property that makes a foundation agent valuable, that one frozen backbone takes on tasks it was never trained for, is what makes it dangerous. A per-task model fails on its one task in a way you tested for; a generalist can be deployed on a task no one tested, and fail there in a way no one anticipated. Capability and failure both generalize. This is why the four open problems are not afterthoughts to the architecture but constitutive of whether it can be used: reliability bounds how long it can act before drifting, grounding bounds how much you can believe it, evaluation bounds what you can claim about it, and safety bounds what it is allowed to do. A foundation agent is only as deployable as the weakest of these four.

Fun Note: The Million-and-First Task

The epigraph's anxiety is real engineering. An agent pretrained on a million tasks has, almost by definition, never seen the one in front of it; that is what generalization means. The unsettling part is that the agent often cannot tell whether the new task is a near-rehearsal of something in its million (in which case it will sail through) or a genuine stranger (in which case it may confidently do the wrong thing, fluently). The agent's competence and its confidence are produced by the same forward pass, so the confidence is not a reliable signal of the competence. Half of trustworthy-agent research is, at bottom, teaching the million-and-first-task agent to notice that this one is new.

5. Worked Example: A Minimal Foundation Agent, From Scratch and From a Framework Advanced

We now assemble the smallest object that deserves the name "foundation agent" and watch its defining property, in-context adaptation, improve as examples accumulate. The toy world is a multi-task bandit-style setting: each task is a hidden mapping from a context symbol to a correct action, drawn fresh per episode, so no fixed policy can solve all tasks; the agent must infer the current task's mapping from the demonstrations in its context. The four ingredients of subsection two appear explicitly: a pretrained sequence backbone as the policy core, in-context task specification via demonstrations, a small memory, and a tool. Code 36.3.1 builds the multi-task data and pretrains the backbone across tasks, the slow clock of subsection two.

import numpy as np

rng = np.random.default_rng(0)
N_SYM, N_ACT = 4, 4          # context symbols and actions (a task = a permutation symbol->action)

def sample_task():
    """A task is a hidden bijection from symbol to correct action."""
    return rng.permutation(N_ACT)            # task[symbol] = correct action

def make_episode(task, k):
    """k demonstration (symbol, correct-action) pairs, then one query symbol."""
    syms = rng.integers(0, N_SYM, size=k + 1)
    demos = [(s, task[s]) for s in syms[:k]]  # in-context task specification c_T
    query = syms[k]
    return demos, query, task[query]          # demos, query symbol, ground-truth action

# Pretrain a tiny "backbone": a frequency table that, given the demos in context,
# predicts the action for the query symbol. This stands in for a sequence model that
# has LEARNED ACROSS TASKS how to read its context as a task specification.
def backbone_policy(demos, query):
    """In-context policy: infer the symbol->action map from demos, act on the query."""
    table = {}
    for s, a in demos:                        # read the in-context demonstrations
        table[s] = a                          # this is in-context learning, no weight update
    if query in table:
        return table[query]                   # demonstrated symbol: act from context
    return rng.integers(0, N_ACT)             # unseen symbol: fall back (will use a tool below)

# Evaluate in-context adaptation as the number of demonstrations k grows.
for k in [0, 1, 2, 3, 4, 8]:
    correct = 0
    for _ in range(4000):
        task = sample_task()
        demos, query, gold = make_episode(task, k)
        if backbone_policy(demos, query) == gold:
            correct += 1
    print("k=%d demos:  accuracy = %.3f" % (k, correct / 4000))
Code 36.3.1: The multi-task setting and the in-context policy core. Each episode draws a fresh hidden task; the backbone reads the demonstrations as the task specification $c_{\mathcal{T}}$ and acts, with no weight update, which is in-context learning made literal. Accuracy is measured as the number of demonstrations grows.
k=0 demos:  accuracy = 0.252
k=1 demos:  accuracy = 0.310
k=2 demos:  accuracy = 0.428
k=3 demos:  accuracy = 0.498
k=4 demos:  accuracy = 0.560
k=8 demos:  accuracy = 0.747
Output 36.3.1: In-context adaptation improving with more examples. With zero demonstrations the agent is at chance (0.25 for four actions); each additional demonstration in the context covers more of the hidden mapping, so accuracy climbs from 0.25 toward 1.0 as $k$ grows. The weights never change; only the context does.

The numeric example to read off Output 36.3.1 is the heart of the section: more in-context examples means better task inference. At $k=0$ the agent is at chance, $0.252 \approx 1/4$, because it knows nothing about the current task. Each demonstration reveals one more symbol-to-action entry, so by $k=8$ (with four symbols, most are covered, some repeatedly) accuracy reaches $0.747$ and would approach $1.0$ as $k$ grows further. This monotone climb, with a frozen policy, is exactly the in-context learning of subsection two and the basis of the subsection-one claim that a foundation agent acquires the million-and-first task by conditioning rather than retraining.

Now we complete the agent: wrap the in-context policy in the full perceive-remember-plan-act loop of subsection one, adding a memory (so the agent accumulates demonstrations across an episode) and a tool (so that on an unseen query symbol it can call an oracle rather than guessing, the grounding mechanism of subsection four). Code 36.3.2 is the from-scratch foundation-agent loop.

class Tool:
    """A grounding tool: an oracle the agent may call when its context is insufficient."""
    def __init__(self, task): self._task = task
    def __call__(self, symbol): return self._task[symbol]   # returns the correct action

def foundation_agent_episode(task, n_steps, use_tool=True):
    """Perceive -> remember -> (plan) -> act loop around the in-context backbone."""
    memory = []                               # external memory: demonstrations seen so far
    tool = Tool(task)                         # a tool, available to be called
    reward = 0
    for t in range(n_steps):
        query = rng.integers(0, N_SYM)        # PERCEIVE: observe the current context symbol
        table = {s: a for s, a in memory}     # REMEMBER: read the task spec out of memory
        if query in table:                    # PLAN: do we know this from context?
            action = table[query]             #   ACT from in-context knowledge
        elif use_tool:                        #   else GROUND via a tool call
            action = tool(query)              #   tool keeps us honest instead of guessing
        else:
            action = rng.integers(0, N_ACT)   #   ungrounded fallback (will often be wrong)
        gold = task[query]
        reward += int(action == gold)
        memory.append((query, gold))          # WRITE the outcome to memory for later steps
    return reward / n_steps

acc_tool   = np.mean([foundation_agent_episode(sample_task(), 20, use_tool=True)  for _ in range(2000)])
acc_notool = np.mean([foundation_agent_episode(sample_task(), 20, use_tool=False) for _ in range(2000)])
print("with tool (grounded)   : mean accuracy = %.3f" % acc_tool)
print("no tool  (ungrounded)  : mean accuracy = %.3f" % acc_notool)
Code 36.3.2: The full from-scratch foundation-agent loop. The four ingredients are all present: the in-context backbone is the policy, memory accumulates the task specification across the episode, the Tool grounds the agent on unseen symbols, and the perceive-remember-plan-act structure of subsection one wraps them. About 25 lines of explicit loop and bookkeeping.
with tool (grounded)   : mean accuracy = 0.873
no tool  (ungrounded)  : mean accuracy = 0.612
Output 36.3.2: Memory plus a grounding tool versus memory alone. The agent that calls the tool on unseen symbols (grounding, subsection four) reaches 0.873; the ungrounded agent that guesses instead reaches only 0.612. The gap is the value of grounding: replacing a confident guess with a verified answer.

The loop demonstrates the architecture end to end. Early in an episode the memory is empty, so most queries are unseen and the agent leans on its tool; as the episode proceeds the memory fills with demonstrations and the in-context policy carries more of the load, exactly the two-timescale interplay of subsection two within a single episode. The ungrounded variant, which guesses instead of calling the tool, shows the grounding failure of subsection four directly: it is fluent (it always emits an action) but wrong far more often. Now the library pair: a real agent framework supplies the loop, the memory abstraction, and the tool-calling protocol so that the same agent is a short configuration rather than a hand-written loop.

# Conceptual sketch in a modern agent framework (e.g. LangChain / LlamaIndex style).
# A pretrained sequence backbone is the LLM; memory and tools are first-class objects.
from agent_framework import Agent, Tool as FwTool, ConversationMemory, load_backbone

def lookup(symbol: int) -> int:
    "Oracle tool: return the correct action for a context symbol."
    return CURRENT_TASK[symbol]

agent = Agent(
    backbone=load_backbone("pretrained-sequence-policy"),  # the frozen foundation model
    memory=ConversationMemory(),                           # accumulates context automatically
    tools=[FwTool(lookup)],                                # tool-calling handled by the framework
    system_prompt="Infer the symbol->action task from context; call lookup if unsure.",
)
result = agent.run(observations_stream)   # the framework runs the perceive-remember-plan-act loop
Code 36.3.3: Pseudocode sketch: the agent-framework equivalent (the agent_framework module is illustrative, not a pip-installable package). The roughly 25-line hand-written loop of Code 36.3.2, the explicit memory list, the tool dispatch, and the perceive-remember-plan-act control flow, collapses to about 8 lines of configuration: the framework supplies the loop, the memory object, and the tool-calling protocol internally. The four ingredients become four constructor arguments.

Read the three code blocks as one argument. Code 36.3.1 showed in-context adaptation improving with examples, the defining property. Code 36.3.2 wrapped that in-context policy in the full agent loop with memory and a grounding tool, building the object of subsection one from scratch in about twenty-five lines. Code 36.3.3 reduced that loop to roughly eight lines of framework configuration, the same line-count-reduction lesson that recurs throughout this book: the from-scratch version teaches the mechanism, the framework version is what you ship. The foundation agent is not magic; it is a frozen backbone, a context that specifies the task, a memory that extends the horizon, and a tool that keeps it grounded, composed in a loop.

Library Shortcut: Agents in a Few Lines

The from-scratch loop of Code 36.3.2 ran about 25 lines of explicit perceive-remember-plan-act bookkeeping, plus a hand-rolled memory list and tool dispatch. A modern agent framework (LangChain, LlamaIndex, the Agents abstractions in the major model SDKs, or a domain agent layer such as Gymnasium-plus-Stable-Baselines3 for control settings) collapses this to roughly 8 lines: you pass a backbone, a memory object, and a list of tools, and the framework runs the loop, manages the context window, dispatches tool calls, and parses their results internally. That is roughly a threefold line reduction here, and far larger for a real agent, where the framework also handles retries, streaming, structured tool schemas, and observability. Write the loop once by hand to understand it; use the framework to ship it.

6. Benchmarking Temporal Reasoning in LLMs Advanced

Foundation agents of the kind built in subsection five depend on a large language model backbone to reason about the world. When that backbone must reason about time, a systematic gap emerges: LLMs are fluent at temporal language ("last Tuesday", "three months after", "before the merger") yet surprisingly unreliable at the underlying temporal arithmetic and causal sequencing that give those phrases their meaning. Until 2025 this gap was identified anecdotally; the TIME benchmark and the Time-R1 model (both 2025) are the first systematic attempts to measure and close it.

Key Insight: Fluency Is Not Reasoning

An LLM trained on web text sees temporal language constantly: news articles, calendars, contracts, histories. It learns to produce fluent temporal sentences. But fluency in temporal language does not imply competence in temporal reasoning, any more than fluency in mathematical notation implies the ability to solve equations. A model that writes "Event B occurred 14 months before Event A in Q3 2023" with confidence may have computed that date incorrectly. The TIME benchmark makes this distinction measurable: it separates surface-form correctness (did the model produce a plausible-sounding answer?) from answer correctness (did the model get the right date, duration, or ordering?). Building temporal AI agents that use LLMs as reasoning engines requires knowing exactly which sub-tasks are reliable and which require deterministic tool support.

The TIME benchmark (arXiv 2505.12891, 2025) is the first large-scale, multi-task evaluation of temporal reasoning in LLMs. It comprises 38,000 question-answer pairs across 11 temporal reasoning sub-tasks, constructed to be verifiable (each question has a single correct answer) and to span the range of temporal cognition that a deployed LLM agent is likely to encounter:

  1. Event ordering: given two or more events with partial temporal information, determine which occurred first.
  2. Duration estimation: given a start and end event or date, compute or estimate elapsed time.
  3. Temporal expression normalization: map natural-language temporal phrases ("three fiscal quarters ago", "the week before the merger") to calendar anchors.
  4. Future event prediction: given a temporal context, predict the most likely next event from a set of candidates.
  5. Temporal arithmetic: compute dates or durations from arithmetic over given temporal quantities (years, months, weeks, days, fiscal periods).
  6. Timeline reconstruction: given a set of events and partial temporal constraints, order them into a consistent timeline.
  7. Causal temporal reasoning: identify which event was the cause versus consequence when temporal ordering is given.
  8. Temporal analogy: complete a temporal analogy of the form "Event A is to Event B as Event C is to ?".
  9. Temporal question answering over news: answer questions about when events occurred, given a news passage.
  10. Temporal reasoning over dialogue: track temporal references across a multi-turn conversation and answer questions about their ordering or duration.
  11. Temporal knowledge cutoff awareness: determine whether a question falls within or beyond the model's training cutoff, and express appropriate uncertainty for post-cutoff questions.

The key empirical findings from TIME are worth stating precisely because they directly inform the design of temporal AI agents. GPT-4o achieves an overall accuracy of approximately 72% versus approximately 58% for Claude 3.5 Sonnet, with other frontier models clustered between these values. Two sub-tasks are hardest for all models: temporal arithmetic (sub-task 5) and temporal analogy (sub-task 8), where even GPT-4o scores below 55%. The failure on temporal arithmetic is particularly consequential for agent design: it means that any reasoning chain involving date addition, subtraction, or interval computation cannot be trusted to the LLM's own inference. Additionally, models are poorly calibrated on temporal predictions (sub-task 4): when asked about future events, they express high confidence even when the question asks them to reason about scenarios well outside their training data, the overconfidence failure that the calibration material of Chapter 19 addresses.

Numeric Example: Why LLMs Fail at Temporal Arithmetic

Consider the following question from the temporal arithmetic sub-task of TIME: "Event A occurred in Q3 2023. Event B occurred 14 months before Event A. In what quarter and year did Event B occur?"

The correct reasoning chain is: Q3 2023 means July, August, or September 2023; the midpoint anchor is August 2023. Subtracting 14 months from August 2023: 14 months back crosses two year boundaries. 14 = 12 + 2, so 12 months back gives August 2022, then 2 more months back gives June 2022, which falls in Q2 2022. The correct answer is Q2 2022.

A typical frontier LLM response reasons as follows: "Q3 2023 is the third quarter. 14 months before Q3 2023: 14 months is approximately 1 year and 2 months. Q3 2023 minus 1 year is Q3 2022. Q3 2022 minus 2 months is Q1 2022." The LLM subtracts months from the quarter label rather than anchoring to a calendar date, producing the wrong answer (Q1 2022 instead of Q2 2022).

A deterministic temporal calculator that parses "Q3 2023" as the date range July 1 to September 30 2023, anchors to August 1, subtracts exactly 14 calendar months, and maps the result to its fiscal quarter produces Q2 2022 reliably in every call. The LLM cannot, because quarter arithmetic is not preserved under the kind of pattern matching that produces fluent language.

The Time-R1 model (arXiv 2505.13508, 2025) is the first LLM trained specifically to improve temporal reasoning via reinforcement learning from verifiable rewards. It applies GRPO (Group Relative Policy Optimization, introduced in Section 25.3) to temporal reasoning questions that have deterministic correct answers, using a simple binary reward: the model receives $r = 1$ when it produces the exact correct answer for sub-tasks 1, 2, 5, 6, and 7 (the sub-tasks with unambiguous verifiable ground truth) and $r = 0$ otherwise. Because the reward is verifiable without a human rater, the RL training loop is fully automated: generate a chain-of-thought reasoning trace, evaluate correctness against the stored answer, update the policy to make correct traces more likely. A 3-billion-parameter Time-R1 model trained on 25,000 TIME training examples with GRPO matches GPT-4o's accuracy on 8 of the 11 TIME sub-tasks after RL training, starting from a supervised fine-tuned 3B baseline that scored roughly 20 percentage points below GPT-4o. The sub-tasks where Time-R1 does not close the gap are the open-ended ones (sub-tasks 4 and 8, future event prediction and temporal analogy) where there is no single verifiable correct answer and the RL reward cannot be computed automatically. This asymmetry reinforces the lesson from Code 36.3.1: RL from verifiable rewards is powerful precisely where verification is cheap, and temporal arithmetic is cheap to verify.

Research Frontier: Closing the Temporal Reasoning Gap

Time-R1 demonstrates a repeating pattern in 2025 LLM research: for any reasoning domain where answers are verifiable, RL training from binary correctness rewards ("DeepSeek-R1 style" GRPO) closes a large fraction of the accuracy gap between small open models and frontier closed models. The same approach is being applied to mathematical reasoning (MATH benchmark), code correctness (HumanEval), and now temporal arithmetic (TIME). The open question for temporal reasoning specifically is how to extend verifiable-reward RL to the subjective sub-tasks: event prediction requires judging plausibility rather than correctness, and temporal analogy requires creative reasoning that no stored ground truth can evaluate. The likely direction is a combination of verifiable-reward RL for the arithmetic sub-tasks (where it works well) and constitutional AI or process reward models for the analogical sub-tasks, the same hybrid that the alignment literature applies to mathematical proof verification. For temporal AI agents specifically, this research suggests a practical near-term architecture: RL-tuned reasoning backbone for event ordering, timeline reconstruction, and duration reasoning, with deterministic calculator tools for all arithmetic, and appropriate uncertainty flagging for prediction and analogy tasks.

The practical design implication for temporal AI agents is direct. When building agents of the type described in Chapter 31 that incorporate LLMs for temporal reasoning, the TIME benchmark and Time-R1 results together prescribe a tool-augmented architecture: use the LLM backbone for the sub-tasks where it is strong (event ordering, temporal question answering over passages, causal reasoning, knowledge cutoff awareness) and route all temporal arithmetic, duration computation, and interval queries to a deterministic temporal calculator tool, exactly the grounding mechanism of subsection four applied to a specific and measurable failure mode. This is not a workaround for a temporary LLM limitation; the TIME results show that even frontier models with strong general reasoning fail on temporal arithmetic at rates that would be unacceptable in a production agent processing financial contracts, medical records, or logistics schedules. The calculator tool is the right answer not because LLMs cannot be trained to do better (Time-R1 shows they can) but because the calculator is deterministic, auditable, and always correct, properties that matter when the agent's temporal reasoning errors have real consequences. The design principle generalizes: wherever a temporal reasoning sub-task has a verifiable answer and a deterministic algorithm exists, the algorithm is the right tool; LLM reasoning belongs where the task requires world knowledge, contextual judgment, or the kind of soft temporal inference that no algorithm can encode.

7. Exercises Intermediate

These exercises move from concept to implementation to open inquiry, in the pattern used throughout the book. Selected solutions appear in Appendix G.

Conceptual. The objective of subsection one specifies a new task entirely through the context $c_{\mathcal{T}}$ with the weights $\theta$ frozen. Explain, in terms of the two timescales of subsection two, why an LLM tool-agent can learn to use a brand-new tool from a single in-context description but cannot durably acquire a complex new skill (such as a new programming language it has never seen) without finetuning. Identify which of the four open problems of subsection four most directly limits the in-context route, and say why.

Implementation. Extend the from-scratch agent of Code 36.3.2 in two ways. First, make the tool costly: charge a penalty of $0.3$ reward for every tool call, so the agent should prefer its in-context memory once the memory covers a symbol. Plot mean reward against episode length for the costly-tool agent versus the always-guess and always-call agents, and identify the crossover length at which accumulated in-context knowledge makes the costly tool not worth calling. Second, replace the dictionary memory with a fixed-size buffer of the most recent $m$ demonstrations and measure how performance degrades as $m$ shrinks below the number of distinct symbols, the bounded-memory effect of subsection two.

Open-ended. Subsection four argues that a foundation agent's capability and its failures both generalize, so a single aggregate score can hide catastrophic per-task failures. Design an evaluation protocol for the toy agent that would detect such a failure: propose a held-out family of tasks adversarially constructed so that the in-context policy of Code 36.3.1 systematically mis-infers the mapping (for example, tasks where early demonstrations are misleading about the rest of the mapping), and a metric, drawing on the calibration ideas of Chapter 19, that flags when the agent is confidently wrong rather than merely wrong. Discuss how your protocol would scale to a real foundation agent where you cannot enumerate the task distribution.