Build a small documentation agent with a clear stopping rule
You already know the two ideas needed to build a first agent: an agent chooses a next step toward a goal, and tool calling lets it request a controlled action. Now we will connect those ideas in one tiny end-to-end program. You do not need to master planning, context engineering, memory, or graph frameworks yet—we will deliberately use the smallest versions here and unpack each one in the lessons that follow.
What You Will Learn
- Connect the first two lessons—agent loops and tool calling—into one complete working example.
- Identify the minimum parts of a bounded agent without needing planning, memory, or a framework yet.
- Run a standard-library example through both supported-answer and safe-abstention paths.
- Read the trace so later lessons on planning, context, memory, graphs, and evaluation have a concrete foundation.
Build the core loop before learning the advanced subsystems
You already have enough background to build a first agent. Lesson 1 introduced the bounded decide → act → observe loop, and Lesson 2 showed that a model may propose a tool call while trusted application code validates and executes it. This lesson simply connects those two ideas into one small program.
Start with one narrow job whose success can be checked. Write the goal and instructions separately: the goal describes the requested outcome, while instructions define permitted behavior, evidence requirements, and when to abstain. Add one read-only tool with a small schema and validate every proposed argument before execution.
The tiny state in this example records only the goal, evidence, step count, and trace. That is enough to understand the mechanism. Later lessons will improve one part at a time: planning chooses better next steps, context engineering chooses what the model sees, memory persists useful information, state graphs make execution explicit, and durable execution survives long waits and restarts.
On each iteration, a decision function chooses search, final answer, or abstain; the tool returns an observation; state is updated; and stop rules prevent an endless loop. In a real LLM application the model may propose the decision, but validation and limits remain deterministic application responsibilities.
Minimum parts of a bounded agent
Connect the goal, approved tool and stopping condition
Choose one narrow task with a clear success condition.
Give the agent one read-only tool with validated inputs.
Keep a tiny state containing the goal, evidence, step count, and trace.
Repeat decide → tool → observe only while the goal is unfinished and the step budget remains.
Return a supported answer when evidence is sufficient; otherwise stop safely and abstain.
Save the successful and failed traces as tests before adding planning, memory, more tools, or write permissions.
Instructional figure
A complete bounded agent architecture
Where do instructions, decisions, tools, state, validation, and stopping rules connect?
Follow one success path and one failure path
For a supported question, the example searches approved documents, records the observation, and returns a cited answer. For an unsupported question, repeated searching cannot manufacture evidence: the loop reaches its limit and explicitly abstains. Both traces are valuable evaluation cases.
Worked Example: A five-step documentation agent
The developer chooses MAX_STEPS = 5. The limit is a safety budget, not a fact learned by the model.
- A supported query triggers one validated search of the approved in-memory documentation.
- The observation is stored with its source; on the next decision the agent has enough evidence and returns a cited answer after 1 tool step.
- An unsupported query returns no evidence. The deterministic loop may try another bounded search, but it never invents a document.
- When step 5 is reached without evidence, the agent returns an abstention message and records stop_reason = 'step_limit'.
What the result means: Success and safe abstention are both correct outcomes. The important property is that the trace explains why the loop stopped.
A Realistic Example: A documentation assistant you can understand end to end
The agent answers “How do I reset a password?” only by searching approved documentation. A supported question follows plan → search → answer. An unsupported question such as “How do I deploy to Mars?” eventually reaches the step limit and explicitly abstains instead of inventing a source.
Read the Mechanism in Code
Use the label and note to understand what this block represents before reading each line.
"""A tiny bounded documentation agent using only the Python standard library."""
DOCS = [
{
"title": "Reset a password",
"text": "Open Settings, choose Security, then select Reset password.",
},
{
"title": "Export an invoice",
"text": "Open Billing, choose an invoice, then select Download PDF.",
},
]
MAX_STEPS = 5
INSTRUCTIONS = (
"Use only the approved documentation tool. "
"Answer only when a source supports the answer; otherwise abstain."
)
def search_docs(query):
"""Validated read-only tool: return documents sharing useful words."""
if not isinstance(query, str) or not query.strip():
raise ValueError("query must be a non-empty string")
terms = {word.strip("?.,").lower() for word in query.split() if len(word) > 3}
return [doc for doc in DOCS if terms & set(doc["text"].lower().split())]
def decide(state):
"""Deterministic stand-in for a model's proposed next decision."""
if state["step"] == 1:
return {"type": "plan", "query": state["goal"]}
if state["evidence"]:
return {"type": "final"}
if state["step"] == MAX_STEPS:
return {"type": "abstain"}
return {"type": "tool", "name": "search_docs", "query": state["query"]}
def run_agent(goal):
state = {"goal": goal, "query": goal, "evidence": [], "step": 0, "trace": []}
for step in range(1, MAX_STEPS + 1):
state["step"] = step
decision = decide(state)
state["trace"].append(f"step {step}: {decision['type']}")
if decision["type"] == "plan":
state["query"] = decision["query"]
continue
if decision["type"] == "tool":
if decision["name"] != "search_docs":
raise PermissionError("Only search_docs is allowed")
state["evidence"] = search_docs(decision["query"])
state["trace"].append(f" observation: {len(state['evidence'])} document(s)")
continue
if decision["type"] == "final":
doc = state["evidence"][0]
return {"status": "success", "answer": doc["text"], "source": doc["title"], "trace": state["trace"]}
return {"status": "abstain", "answer": "I could not verify this in the approved documentation.", "trace": state["trace"]}
for question in ["How do I reset a password?", "How do I deploy to Mars?"]:
result = run_agent(question)
print(question)
print("
".join(result["trace"]))
print(result["status"], "-", result["answer"], "
")plan → tool → final and succeeds at step 3. The unsupported Mars question reaches step 5: abstain. The limit is a safety and cost ceiling, not a target the successful run should consume.Practice the End-to-End Agent
- Run both supplied questions and match each printed trace to the architecture figure.
- Add one approved document and predict which terms will retrieve it before running.
- Create one malformed tool argument and confirm validation rejects it.
- Turn the success and abstention traces into two repeatable tests before adding any write tool.
Hands-On Runnable Python Lab: Test Success, Missing Evidence and Invalid Arguments
Three proposals exercise three distinct outcomes. No search engine, API key or model download is needed. The source texts are fictional application documentation.
- Accept only the search_docs tool and an arguments object containing one non-empty string topic.
- Run the approved lookup and retain the returned document rather than letting a proposal invent its contents.
- Return the document text and source ID on success; return abstain when the lookup finds nothing.
- Run assertions for all three paths so a future model or tool adapter cannot silently change the contract.
Three distinct outcomes at the tool boundary
Rejected means the proposal is invalid. Abstain means a valid lookup found no approved evidence. Success requires the retrieved text and its source ID.
DOCS = {
"password": {"id": "D1", "text": "Open Settings, then Security, then Reset password."},
"invoice": {"id": "D2", "text": "Open Billing and select Download PDF."},
}
def run(proposal):
if proposal.get("name") != "search_docs":
return {"status": "rejected", "answer": "Tool not allowed", "sources": []}
args = proposal.get("arguments")
if not isinstance(args, dict) or set(args) != {"topic"}:
return {"status": "rejected", "answer": "Invalid argument fields", "sources": []}
topic = args["topic"]
if not isinstance(topic, str) or not topic.strip():
return {"status": "rejected", "answer": "topic must be text", "sources": []}
doc = DOCS.get(topic.lower())
if doc is None:
return {"status": "abstain", "answer": "No approved source found", "sources": []}
return {"status": "success", "answer": doc["text"], "sources": [doc["id"]]}
cases = [
({"name": "search_docs", "arguments": {"topic": "password"}}, "success"),
({"name": "search_docs", "arguments": {"topic": "Mars"}}, "abstain"),
({"name": "search_docs", "arguments": {"topic": 42}}, "rejected"),
]
for proposal, expected in cases:
result = run(proposal)
assert result["status"] == expected
if expected == "success":
assert result["sources"] == ["D1"]
else:
assert result["sources"] == []
print(result["status"], "|", result["answer"], "|", result["sources"])
print("3 contract tests passed")
success | Open Settings, then Security, then Reset password. | ['D1']
abstain | No approved source found | []
rejected | topic must be text | []
3 contract tests passedWhat This Run Shows
- Success and abstention both involve a valid request; rejection means the request itself is unacceptable.
- Only a retrieved document can populate sources. There is no model-controlled citation field.
- The assertions turn examples into regression tests rather than relying on a visually pleasing answer.
This harness complements the earlier multi-step loop. It isolates the tool boundary so you can add an LLM without losing the ability to test it. A production agent needs both layers: a bounded loop and validated tool/result contracts.
From the Exercise to an Application
Experiment: Change the tool name to delete_docs and run the same controller.
The controller returns rejected before consulting documents. Adding a plausible description or a valid topic cannot make an unregistered tool executable.
Summary / Key Takeaways
- A useful first agent should solve one narrow job with a clear success condition rather than trying to be a general autonomous assistant.
- The minimum architecture is goal/instructions + model decision + small tool set + validation + state + bounded loop + stop condition.
- Read-only tools are the safest place to begin because they let you measure agent quality before granting consequential permissions.
- Every tool result becomes an observation that updates state and informs the next decision.
- Step limits, abstention, and human escalation are normal successful outcomes when the agent cannot verify a result.
- Tracing the full run makes debugging possible because you can inspect decisions, tools, observations, and stop reasons.
- Frameworks are optional—the core agent mechanism can be learned and tested with a small transparent Python loop.
Verified Further Reading
These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.
OpenAI: A practical guide to building agents
Primary guidance on agent suitability, orchestration, tools, guardrails, and human intervention.
Hugging Face Agents Course: Introduction to Agents
Official course covering tool use and the thought-action-observation cycle.
OpenAI API: Function Calling
Current API documentation for tool schemas, strict structured arguments, application-side execution, and returning tool results.