Skip to main content
LearnMLAcademy
Advanced10 min read

Build a Simple AI Agent End-to-End

Build an autonomous AI agent from scratch with step-by-step reasoning, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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

Minimum parts of a bounded agent
ComponentMinimum implementationFailure prevented
GoalOne measurable jobAimless behavior
InstructionsAllowed sources, actions and abstention rulePolicy drift
ToolsOne narrow read-only schema firstExcessive authority
StateGoal, evidence, steps and traceLost progress
ValidationCheck tool name and argumentsMalformed or unauthorized calls
Stop rulesSuccess, max steps, no progress, escalationInfinite loops
TraceDecision, action, observation and stop reasonUndiagnosable runs
EvaluationSuccess and failure scenariosUnmeasured reliability

Connect the goal, approved tool and stopping condition

  1. Choose one narrow task with a clear success condition.

  2. Give the agent one read-only tool with validated inputs.

  3. Keep a tiny state containing the goal, evidence, step count, and trace.

  4. Repeat decide → tool → observe only while the goal is unfinished and the step budget remains.

  5. Return a supported answer when evidence is sufficient; otherwise stop safely and abstain.

  6. 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?

Goal
Instructions
Tool schemas
Decide
search/final/abstain
Validate
tool + arguments
Read-only tool
approved docs
Observe
source + result
↺ State: evidence + step count + trace
Supported answer
Safe abstention
Stop rule
success / 5 steps
The model may propose a decision, but the application validates it, runs only approved tools, records observations, and enforces success or abstention.

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.

  1. A supported query triggers one validated search of the approved in-memory documentation.
  2. 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.
  3. An unsupported query returns no evidence. The deterministic loop may try another bounded search, but it never invents a document.
  4. 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.

Runnable Python — no external dependency required
"""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"], "
")
Learner note: Make this example genuinely runnable with only the Python standard library by mocking a tiny documentation search tool and a deterministic decision loop. The point is to expose the mechanics, not depend on a framework.
Expected trace: The password question records 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

  1. Run both supplied questions and match each printed trace to the architecture figure.
  2. Add one approved document and predict which terms will retrieve it before running.
  3. Create one malformed tool argument and confirm validation rejects it.
  4. 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.

supported_answer ⇒ status = success AND source_id belongs to retrieved evidence
The implication is a result contract, not a probability formula. Returning text alone is insufficient: the controller must retain the source that supports it.
  1. Accept only the search_docs tool and an arguments object containing one non-empty string topic.
  2. Run the approved lookup and retain the returned document rather than letting a proposal invent its contents.
  3. Return the document text and source ID on success; return abstain when the lookup finds nothing.
  4. 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

Validate the proposal before lookup. Invalid arguments are rejected; approved evidence leads to a sourced answer, while no document leads to abstention.Tool proposalValidate contractinvalidREJECTApproved lookupD1 foundanswer + sourceNo documentabstain
Rejected means the proposal is invalid. Abstain means a valid lookup found no approved evidence. Success requires the retrieved text and its source ID.

Rejected means the proposal is invalid. Abstain means a valid lookup found no approved evidence. Success requires the retrieved text and its source ID.

Complete Python ExercisepythonRunnable
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")
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
success | Open Settings, then Security, then Reset password. | ['D1']
abstain | No approved source found | []
rejected | topic must be text | []
3 contract tests passed
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. Success and abstention both involve a valid request; rejection means the request itself is unacceptable.
  2. Only a retrieved document can populate sources. There is no model-controlled citation field.
  3. 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

From the Exercise to an Application
SituationPractical choiceImportant qualification
First implementationOne read-only tool and explicit testsAdd complexity only after failure paths are observable.
Model integrationParse a structured proposal into the same controllerReject malformed output; do not execute arbitrary text.
Expanding retrievalReplace exact lookup with a evaluated retrieverKeep source ownership and abstention independent of ranking.
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.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Build a Simple AI Agent End-to-End"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5practical selection
Which is the best starting tool set for a first production experiment with an agent?
Question 2 of 5numerical/formula
A sample agent has MAX_STEPS=5 and successfully finishes after 3 steps. How many additional steps should it execute?
Question 3 of 5conceptual
What information should be updated after a tool returns?
Question 4 of 5interpretation
Why is a runnable framework-free example valuable in this lesson?
Question 5 of 5debugging/diagnostic
The agent reaches step 5 without enough evidence to answer. What should it do?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Which is the best starting tool set for a first production experiment with an agent?▼

Correct Answer: Read-only tools for one narrow task

Read-only tools let you measure agent decision quality while limiting real-world side effects.

2A sample agent has MAX_STEPS=5 and successfully finishes after 3 steps. How many additional steps should it execute?▼

Correct Answer: 0

A maximum is a safety ceiling, not a target. The agent should stop as soon as success is verified.

3What information should be updated after a tool returns?▼

Correct Answer: The agent’s state/evidence used for the next decision

Tool output becomes an observation that updates state/evidence for the next step.

4Why is a runnable framework-free example valuable in this lesson?▼

Correct Answer: It exposes the core loop, validation, state, and stopping mechanics without hiding them behind abstractions

The lesson’s purpose is to teach the mechanism first so frameworks are later understood as implementation choices.

5The agent reaches step 5 without enough evidence to answer. What should it do?▼

Correct Answer: Abstain or escalate with what it tried

A bounded agent treats the limit as a stop condition and should return partial status or request help rather than guessing.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next