8 Applications 1 / 8
  1. In this chapter
  2. Your first agent
  3. Prompt Engineering
  4. Structured Outputs and Function Calling
  5. RAG in Practice
  6. Agents and Tool Calling in Practice
  7. Agent context and memory
  8. Agent Evaluation
  9. MCP and the Tool Ecosystem
All chapters →

Chapter 8 · Applications 8.1

Your first agent: a read-only tool and a bounded loop

Use a tiny library lookup to distinguish a function call, a fixed workflow, and an agent loop. Run action, observation, and stopping cases in standard Python.

Beginner 7 min read Updated Companion code ↓

After this page you will be able to

  • Distinguish a direct function call, a workflow, and a loop that chooses actions.
  • Explain what tools, the policy, the controller, and traces each do.
  • Run a read-only tool loop and verify that it stops.
  • Define minimal tests and validations before connecting a model.
On this page
  1. Start with a lookup
  2. Define tools, actions, and observations
  3. Experiment: run a bounded read-only loop
  4. Grow the loop one feature at a time
  5. Summary and exercises
  6. Quick self-check
  7. Assign responsibility for a missing book
  8. Further reading
  9. FAQ

A minimal agent reads a task, chooses an action, observes the result, and decides whether to continue. A model can supply the action policy. Application code runs the tool and returns its result. Here a deterministic rule stands in for the model so you can follow the whole loop before adding model calls, tool protocols, and evaluation.

Start with a lookup

Suppose you need to find a book. There are three useful designs.

DesignWhat controls the flowWhen it helps
Direct callThe program calls the catalog onceThe task is one lookup
Fixed workflowCode orders lookup, enrichment, and formattingSteps and branches are known
Agent loopThe policy chooses actions from the task and observationsLater steps depend on intermediate results

A single book lookup usually needs only a direct call. We keep the task small so that the parts of an agent can be tested separately. Finding several books or switching lookup methods after an empty result makes dynamic decisions more useful.

Define tools, actions, and observations

A tool is an operation the application permits. Here, read-only lookup takes a book name and returns a shelf or an explicit absence. A policy reads the task and the history and asks for an action. The controller accepts lookup and finish. A different name leads to an error before any tool can run.

ConceptIn the example
TaskLocate the atlas
ActionRequest lookup("atlas")
ObservationThe catalog returns shelf A
TraceA record of the book name and lookup result
StopThe policy finishes or the step budget runs out

The observation is data the application obtained. The policy assembles the final answer from it. A real application should verify that cited evidence exists and belongs to the task and account. A model’s tool name and arguments are proposals. The controller checks them against its allowlist and application rules before calling anything.

The first agent loop: actions, observations and stopping Flow diagram: a task goes to the policy, which picks the action lookup("atlas"); the loop controller validates the tool name and arguments and, once they pass, runs the read-only tool; the tool returns the observation shelf A, the observation goes into the trajectory, and the trajectory is handed back to the policy to pick the next step. When the policy returns finish, the loop ends with the final answer shelf A; when the step budget runs out, it reports it clearly. The first agent loop: actions, observations and stopping Final answer: shelf A ends when the policy returns finish finish("shelf A") Policy reads the task and the trajectory so far, picks the next action (a rule script here; later a model) action lookup("atlas") Loop controller (the app) validates the tool name and arguments appends the observation to the trajectory step limit: stop when exceeded run only after validation Tool lookup read-only catalog query returns shelf A or a clear missing result observation Trajectory (a reviewable history) [("atlas", "shelf A")] — every tool call leaves a record hand the new observation back to the policy to pick the next step budget exhausted: say so clearly a budget is a stopping condition too
The loop of the page's experiment: the policy only issues requests, the controller validates and executes, observations accumulate in the trajectory until the policy answers with finish or the step budget stops it. The code below runs exactly this loop.

Experiment: run a bounded read-only loop

Tool-loop and stopping-condition lab script

A Python function acts as the policy. It asks for a lookup, reads the result, and then finishes. Try an unknown book and a run with too few steps. The example uses an in-memory catalog and ran on an Apple M2 Max with Python 3.12.14. It requires neither an account nor model weights.

from __future__ import annotations

from collections.abc import Callable

Action = tuple[str, str]
Observation = tuple[str, str]
Policy = Callable[[str, tuple[Observation, ...]], Action]


def lookup(book: str) -> str:
    catalog = {"atlas": "shelf A", "algebra": "shelf B"}
    return catalog.get(book, "not in the catalog")


def scripted_policy(task: str, history: tuple[Observation, ...]) -> Action:
    """Stand in for a model so each transition is reproducible."""
    if history:
        return "finish", history[-1][1]
    return "lookup", task


def run(
    task: str,
    policy: Policy,
    max_steps: int,
) -> tuple[str, tuple[Observation, ...]]:
    history: list[Observation] = []
    for _ in range(max_steps):
        action, value = policy(task, tuple(history))
        if not isinstance(value, str):
            raise ValueError("tool arguments and final answers must be strings")
        if action == "finish":
            return value, tuple(history)
        if action != "lookup":
            raise ValueError("unrecognized tool or argument")
        history.append((value, lookup(value)))
    raise RuntimeError("step budget exhausted")


answer, trace = run("atlas", scripted_policy, 2)
missing, _ = run("missing", scripted_policy, 2)
assert answer == "shelf A" and trace == (("atlas", "shelf A"),)
assert missing == "not in the catalog"
print("found:", answer, trace)
print("missing:", missing)
try:
    run("atlas", scripted_policy, 1)
except RuntimeError:
    print("budget exhausted")
else:
    raise AssertionError("expected the step limit to stop the loop")
found: shelf A (('atlas', 'shelf A'),)
missing: not in the catalog
budget exhausted

For an unknown book, the tool records that the catalog lacks it and the policy can stop. A one-step budget lets the lookup happen, but the code stops before the policy can produce a final answer. Keeping these outcomes distinct helps identify tool failures, an exhausted budget, and a valid empty result.

The widget below runs run() in the browser one step at a time: the trace the policy saw and the action it returned at each step, and what the program did with it. Change the task, the step limit and the policy to see how “found”, “not in the catalog”, “step budget exhausted” and “unrecognized tool” each come about.

Grow the loop one feature at a time

  1. Add a read-only tool. Browsing by category is one example. Define its inputs and outputs and test that the policy chooses it for the right tasks.
  2. Replace the scripted policy with a model. Specify structured actions and validate tool names, argument types, and business rules. Replay a fixed observation trace.
  3. Add stopping conditions. Limit steps, wall time, and repeated calls, and record each reason for stopping. A tool timeout can trigger a limited retry with a trace.
  4. Evaluate outcomes and cost. Check that the user obtained the needed information and report calls, timeouts, and repeats. Tools that change external state need separate validation and explicit authorization.

First make the loop explainable for a valid request, missing data, and an exhausted budget. Then continue with structured output and function calling, context and memory, and agent evaluation.

Summary and exercises

  • Tools act, the policy chooses actions, and the loop controls history and stopping.
  • Record observations so later decisions can be checked.
  • Start with a read-only lookup and add tools, a model, and evaluation in stages.

Quick self-check

1. Who performs the lookup?

  • A read-only tool called by the application.
  • The tool name emitted by the policy.

The tool name is only a request. The program executes the operation.

2. What happens when the catalog lacks a book?

  • The system treats it as a successful find.
  • The observation lets the policy finish with an explicit absence.

Absence is a normal result the system can explain.

3. What stops an endless repeated lookup?

  • A step or repetition limit in the controller.
  • The book name.

Stopping conditions belong to the controller.

4. When does dynamic action selection help?

  • A single fixed lookup already solves the task.
  • Later actions depend on intermediate results.

Start with a direct call or workflow for a predictable short task.

Assign responsibility for a missing book

Which layer should decide that a book is absent from the catalog? If the policy repeatedly requests the same lookup, which layer stops the repetition?

Worked answer

The catalog tool reports absence. The policy uses that observation to stop and explain the result. The controller enforces the step budget. A larger application can also count repeated tool-and-argument pairs and log the stopping reason.

Further reading

FAQ

Does one lookup require an agent?
A direct call often suffices. A loop helps when intermediate results should change the next action.
Who actually runs a proposed tool call?
The controller validates the name and arguments, executes the tool, and records its observation.
Why cap steps in a small example?
A policy can repeat an action or fail to finish. A cap bounds the run and records an explicit failure reason.