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.
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
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.
| Design | What controls the flow | When it helps |
|---|---|---|
| Direct call | The program calls the catalog once | The task is one lookup |
| Fixed workflow | Code orders lookup, enrichment, and formatting | Steps and branches are known |
| Agent loop | The policy chooses actions from the task and observations | Later 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.
| Concept | In the example |
|---|---|
| Task | Locate the atlas |
| Action | Request lookup("atlas") |
| Observation | The catalog returns shelf A |
| Trace | A record of the book name and lookup result |
| Stop | The 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.
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
- 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.
- Replace the scripted policy with a model. Specify structured actions and validate tool names, argument types, and business rules. Replay a fixed observation trace.
- 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.
- 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.