08A.1 Agent Definitions, the Autonomy Spectrum and Agent Anatomy

Agents & multimodalLesson 1 of 157,058 words4 parts
Module 08A · 0 of 15 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15

Before you build an agent you need three things that most tutorials skip: words you can use precisely, a way to decide how much freedom the agent gets, and a mental model of the parts every agent is made of. This lesson gives you all three. You will separate chatbots, assistants, workflows and agents (and generative AI from agentic AI), meet the four levels of autonomy (suggest, assist, act with approval, act autonomously) with one worked example each, and then build the whole anatomy (model, instructions, loop, state, tools, memory, guardrails) as a runnable sketch in about 120 lines of standard-library Python. It sits at the start of the agent foundations material: 08A.2 builds the real loop, 08A.9 owns the workflow-versus-agent decision, and 08A.4 shows what a production harness adds around the model. This lesson is the map those three lessons hang on.

What you'll learn

  • The difference between a chatbot, an assistant, a workflow and an agent, and between generative AI and agentic AI, as a table you can use to make a decision
  • The autonomy spectrum: suggest, assist, act with approval, act autonomously, what each level lets the software do, and one worked example of each
  • How to choose an autonomy level for an action (blast radius, reversibility, evidence) and how to promote an agent up the scale with measurements instead of hope
  • The seven parts of an agent: model, instructions, agent loop, state, tools, memory, guardrails, what each one is in code, and what breaks when it is missing
  • The difference between state (one run) and memory (many runs)
  • A tiny runnable agent where autonomy is a guardrail setting, and a conformance eval that checks the agent stays inside its level

What you don't need

  • API keys. The sketch uses a scripted fake model, so it runs with no key and no network. There are no provider calls in this lesson.
  • Docker, databases or any local service. Everything is in-memory Python.
  • The details of the real tool loop. 08A.2 teaches them; here you only need the idea.

Setup

Python 3.11 or newer and nothing else (standard library only). As of 1 December 2026 there is nothing to install. Save each code block under the file name in its first comment and run it with python3 <file>. The outputs below were produced with Python 3.14. No API key is needed.


What you must be able to do after this lesson#

  • Classify a product feature as a chatbot, an assistant, a workflow or an agent by asking who picks the next step
  • Choose an autonomy level for each action using blast radius, reversibility, volume, evidence and observability
  • Name the seven parts of an agent and say what breaks when each one is missing
  • Explain the difference between state (one run) and memory (many runs) with one example of each
  • Enforce an autonomy level in code with a guard function instead of a prompt
  • Write a deterministic conformance eval, with a mutation check, that proves an agent stays inside its level

Why this matters for an AI engineer#

"Build us an agent" is the most common and the most ambiguous request in this field. One team means a chat box with a knowledge base. Another means software that issues refunds at 3 a.m. with nobody watching. If you cannot tell these apart, you will build the wrong thing, price it wrong and secure it wrong. The autonomy question matters even more than the definition question, because it decides what can go wrong: a suggestion that is wrong costs a second of a human's attention, an unattended refund that is wrong costs money.

You'll hear... You'll understand it after...
"Is this a chatbot, an assistant or an agent?" 1.2 Four things people call "AI" in a product
"Agentic AI is just generative AI with extra steps." 1.3 Generative AI versus agentic AI
"How much should we let it do on its own?" 2.2 The four levels and 2.7 Choosing a level
"Human in the loop or fully autonomous?" 2.3 to 2.6, one worked example per level
"What are the parts of an agent, actually?" 3.1 The seven parts
"Where does the memory live?" 3.2 State is not memory
"How do we know it stays inside its permissions?" Part 4: Evaluate it

Part 1: Words that decide what you build#

This Part extends 08A.9, Part 1. That lesson owns the workflow-versus-agent distinction, the vendor definitions and the six-rung spectrum. Here you add the two pairs it does not cover: chatbot versus assistant, and generative AI versus agentic AI.

1.1 Why the words are slippery#

There is no standards body for the word "agent". Anthropic, OpenAI and Google Cloud each publish a definition, and they differ in wording; 08A.9, 1.1 quotes them all with dates. They converge on one test, and it is the test this course uses:

If your code decides what happens next, it is a workflow. If the model decides, it is an agent.

Vendors also use words as product names, which makes things worse. A good example is "assistant": OpenAI's Assistants API was a product, not the concept. Per OpenAI's migration guide, it "was officially sunset on August 26, 2026, and is no longer available", and the guide says to use the Responses API for new integrations (checked 1 December 2026). So when you read "assistant" in an API name, check whether it means the product or the idea.

1.2 Four things people call "AI" in a product#

The four terms below are used loosely in the industry. These are the definitions this course uses, so you can compare designs without arguing about vocabulary.

Chatbot Assistant Workflow Agent
What it is A conversational interface that answers in text A model-powered helper that works with a person, often with read-only tools or retrieval A fixed sequence of steps in which some steps call a model A model that chooses its next action in a loop, using tools, until the goal is met
Who picks the next step The user (every turn) The user, with the assistant's help Your code The model
Uses tools Rarely Mostly read-only (search, retrieval) Yes, in fixed places Yes, and chooses which
Changes things in the world No Usually no; a human applies the result Yes, in steps you wrote Yes, if given write tools
Steps known in advance n/a n/a Yes No
Cost and latency shape One call per turn A few calls per turn N calls, predictable Unbounded unless budgeted (08A.3)
Typical failure Wrong or made-up answer Wrong draft the human catches (or does not) Fails at a known step Loops, wrong actions, compounding errors
Example FAQ widget Email drafting helper Nightly invoice pipeline with an LLM step to classify disputes Support agent that looks up orders, checks policy and issues refunds

Three clarifications keep the table honest.

  • The boundaries blur. A chatbot with a search tool is an assistant. An assistant that can also send the email is moving toward an agent. Real products sit between columns.
  • "Agent" is not a smarter model. It is the same stateless model wrapped in code that gives it tools and lets it iterate (08A.2, 1.3).
  • A workflow is not a lesser agent. For tasks you can write down in advance, a workflow is usually cheaper, faster and easier to test. 08A.9 is entirely about that trade, and its spectrum of six rungs (1.2) shows the in-between designs (chains, routers, parallel branches, orchestrator-workers).

1.3 Generative AI versus agentic AI#

These two terms are not rivals. One names a capability, the other a system design.

Generative AI Agentic AI
What the term names Models that generate content (text, images, code, audio) from a prompt Software that pursues a goal by deciding on and taking actions
Unit of work One model call A loop of model calls plus tool calls
Output Content Content and changes in the world (files written, tickets closed, money moved)
Who is responsible for the next step A person or your code The system itself, within limits you set
Main risk A wrong or fabricated output A wrong action, and mistakes that compound over many steps
How you test it Output quality (accuracy, faithfulness, style) Output quality, plus the trajectory (which tools, in what order) and the final state of the world

An agentic system is built from generative models; it is not a different technology. Anthropic uses "agentic systems" as an umbrella that covers both workflows and agents (08A.9, 1.3), so "we are building agentic AI" tells you nothing about the architecture. Ask which parts need model judgement and which should stay deterministic.

1.4 Which one do you need? A decision table#

08A.9, Part 2 has the full decision framework, and its Workflow-First Rule (use a deterministic workflow unless an agent is clearly needed) is the default to start from (08A.9, 1.4). 13A.8, Decision Frameworks collects all the course's design decisions in one place. This shorter table adds the one thing those lessons do not: which autonomy level each kind of job needs (Part 2 explains the levels).

If the job is... Build... Because...
Answer questions from a fixed body of knowledge A chatbot or assistant with retrieval (Module 07) Nothing needs to happen in the world; quality is about the answer
Produce drafts that a person will review and send An assistant at the suggest level The human is the safety net and the final step
A process whose steps you can list today, with judgement in some steps A workflow with LLM steps Cheaper, faster, testable step by step
An open-ended task where the steps depend on what is found, and the result can be checked An agent with budgets and a stop rule The path cannot be written down in advance; the check keeps it honest
Anything that moves money, deletes data or contacts customers A workflow or agent at the act with approval level A person confirms each irreversible action until evidence says otherwise
High-volume, low-risk, reversible actions An agent at the act autonomously level, inside hard limits Approval for every item would remove the benefit; limits cap the damage

Part 2: The autonomy spectrum#

This Part extends two published lessons. 13A.3, 4.1 gives the product view, a five-rung autonomy dial (suggest, draft, ask-before-acting, act-and-notify, act silently) with approval screens and UX. 08A.14, 2.4 and 2.5 give risk tiers and approvals. This Part adds the engineering view: a four-level scale where each level is a rule your code can enforce, a worked example and a measurement for each level, and a rule for earning the next level. The two scales line up: suggest is level 1, draft is level 2, ask-before-acting is level 3, and act-and-notify or act silently are level 4.

2.1 Autonomy is a dial you set#

Autonomy is a design choice, not a property of the model. The same model can be run as a suggestion engine or as an unattended operator, depending on what your code lets it do. Researchers make the same point: Feng, McDonald and Zhang ("Levels of Autonomy for AI Agents", arXiv, June 2025) argue that autonomy is separate from capability, and define five levels by the role the user plays (operator, collaborator, consultant, approver, observer). This lesson uses a four-level scale that is easier to implement because each level maps to a rule your code can enforce.

2.2 The four levels#

Level What the agent may do Who executes writes The human's role Blast radius of one mistake
1. Suggest Read what it is given and propose. Nothing runs. A human Decides and does everything A second of wasted attention
2. Assist Run read-only tools; prepare drafts and plans A human, from the agent's draft Reviews and applies One bad draft that a reviewer should catch
3. Act with approval Run read tools freely; run write tools after a human says yes The agent, after approval Approves each action (or each batch) One approved action that was wrong; the human shares responsibility
4. Act autonomously Run write tools on its own, inside hard limits The agent Reviews logs and samples after the fact Up to the hard limit, repeated until someone notices

Two points are easy to miss.

  • Levels apply to actions, not just agents. A single agent can read orders autonomously, issue refunds under 100 with approval, and never be allowed to delete anything. Set the level per tool, or per tool-and-argument range.
  • Level 4 is not "no limits". It is "limits that are enforced in code". An autonomous agent without a cap, a budget and a kill switch is an incident waiting for a trigger.

2.3 Level 1: suggest#

Example: the subject-line suggester. A support tool shows the agent's draft reply and the agent proposes three alternative subject lines. A human picks one or ignores them all.

  • What the agent does: reads the draft (given to it), returns three strings.
  • What the human does: everything else, including sending.
  • What can go wrong: an off-tone suggestion. Nothing is executed, so the damage is bounded by attention.
  • Controls you need: an output check (length, banned phrases, no personal data echoed back). No tool guards, because there are no tools.
  • What to measure: acceptance rate (how often a suggestion is used) and edit distance.
  • Real-world cousin: inline code completion that you accept with a key press.

2.4 Level 2: assist#

Example: the triage agent. A new support ticket arrives. The agent looks up the customer's order (read tool), searches the policy docs (read tool), then writes a draft reply and proposes a refund amount. A human reads the draft, edits it, sends it, and clicks the refund button themselves.

  • What the agent does: reads, researches, drafts.
  • What the human does: applies every effect.
  • What can go wrong: the draft cites the wrong policy and the reviewer does not notice (automation bias: people trust fluent text). Read tools can also leak data if over-permissioned.
  • Controls you need: read-only credentials, rate limits, and a UI that shows the evidence behind a draft so review is fast.
  • What to measure: acceptance rate without edits, time saved per ticket, how often reviewers catch an error you planted (a "canary" check on the human).
  • Promotion test: drafts are accepted unchanged most of the time and the planted errors are being caught.

2.5 Level 3: act with approval#

Example: the refund agent. The agent does everything in level 2, then calls issue_refund. The call is paused: a manager sees "Refund 84.50 to order A17, reason: arrived damaged, evidence: order record, policy section 4" and clicks approve or reject. Only after approval does the call run.

  • What the agent does: plans and requests actions.
  • What the human does: approves or rejects each write.
  • What can go wrong: rubber-stamping (approving without reading), approvals that wait for days, and a retried call executing twice. A good approval screen shows exactly what will happen.
  • Controls you need: an approval gate between the proposed call and its execution, an idempotency key so a retry cannot double-execute, an audit log, and a timeout for the approval wait. 08A.12 teaches the gate as a pattern and 08A.7 covers idempotency.
  • What to measure: approval rate, rejection reasons, time to decision, and how often an approved action later needed correcting.
  • Promotion test: a long run of approvals with almost no rejections or corrections for a given kind of action is evidence that this kind could move up.

2.6 Level 4: act autonomously#

Example: the duplicate-ticket cleaner. Every night the agent finds tickets that are exact duplicates (same customer, same order, within 24 hours) and closes the newer one with a link to the original. Nobody approves each closure.

  • What the agent does: finds and closes duplicates by itself.
  • What the human does: reads a morning digest, samples a few closures, and can reopen any ticket.
  • What can go wrong: a wrong rule closes real tickets in bulk. This is why the hard limits exist.
  • Controls you need: the action is reversible (a closed ticket can be reopened), a cap on actions per run (for example 50), a budget for the run (08A.3), automatic fallback to ask a human when the agent is unsure or the cap is hit, a kill switch, and an audit log that records every action with its evidence.
  • What to measure: the false-action rate from a human audit of a random sample, not from the agent's own report.
  • The test of readiness: you can say what the worst night looks like (the cap times the cost of one wrong closure) and you accept it.

2.7 Choosing a level, and earning the next one#

Pick the level per action by answering five questions.

Question If the answer is "high / yes" If the answer is "low / no"
Blast radius: what is the worst single action? Stay at suggest, assist or approval Autonomy is possible
Reversibility: can it be undone cheaply? Autonomy is possible with a cap Require approval
Volume: how many actions per day? Approval for each one stops being practical; consider autonomy with caps and sampling Approval is cheap; keep it
Evidence: do you have measured results for this kind of action? Consider moving up one level Stay where you are
Observability: will you notice and trace a bad action quickly? Autonomy is possible Stay lower until you can

Then earn the next level with data. An example promotion rule (yours will differ): move one action type from approval to autonomous only after at least 200 approved runs of that type with a correction rate below 1%, using a confidence interval rather than a bare percentage (10A.7, 5.2 explains why). Demotion should be just as easy: a rise in corrections drops the action back a level.

Real products expose this dial. The Claude Agent SDK's permission modes are one example (documented at https://code.claude.com/docs/en/agent-sdk/permissions; the mode names below are from the SDK's agent-loop page, checked 1 December 2026, and the mapping to our levels is ours and approximate):

SDK permission mode Behaviour (as documented) Closest level
plan Claude explores and plans; edits go to your approval callback Between 1 and 2
default Calls that need approval trigger your canUseTool callback; no callback means deny 3
acceptEdits Auto-approves file edits inside working directories; other commands follow default rules 3 for risky actions, 4 for edits
auto A model classifier reviews actions and allows or blocks each 4 with a safety net
bypassPermissions Runs tool calls without asking; only for isolated environments 4 with no gate

Part 3: Agent anatomy#

08A.4, Part 2 lists the components a production harness adds around the model. This Part is the smaller map underneath it: the seven parts every agent has, as one runnable sketch.

3.1 The seven parts#

Every agent, from a ten-line script to a production system, is the same seven parts. The names vary between vendors, but the parts do not. OpenAI's practical guide builds an agent from a model, tools and instructions; Anthropic starts from an "augmented LLM" with retrieval, tools and memory; the harness view in 08A.4, 1.1 says Agent = Model + Harness. The table below is the superset.

flowchart LR
    I["Instructions"] --> M["Model"]
    S["State"] <--> L["Agent loop"]
    L --> M
    M --> L
    L --> G["Guardrails"]
    G --> T["Tools"]
    T --> L
    MEM["Memory"] <--> L
Part The question it answers In code Taught in
Model Who decides the next action? A function from (instructions, messages) to a decision 02, 03; choosing one: 13A.8
Instructions What is it for, and what are the rules? A system prompt (plus repository files for coding agents) 04.5, 08A.4, 2.1
Agent loop What repeats, and when does it stop? A for loop with a budget 08A.2, 08A.3
State Where are we in this run? Messages so far, step count, pending approvals 08B.1, 08F.11
Tools What can it touch? A registry of named functions with schemas 08A.6, 08E.1, 08A.7
Memory What does it remember between runs? A store read at the start and written at the end 08B.2, 08B.4
Guardrails What is it not allowed to do or say? Checks on input, on every tool call, and on output 08A.14, 08A.5, 08A.12

3.2 The parts, one by one#

  • Model. Treat it as an injectable function. If the loop only knows "give me the next decision", you can swap providers, and you can replace the model with a scripted fake in tests (08A.2, 3.5). Missing or hard-wired: you cannot test the loop without paying for model calls.
  • Instructions. The standing orders: role, rules, output format, when to stop. They are read on every call. Missing or vague: the model improvises its own rules.
  • Agent loop. The for loop around the model: ask, run tools, append results, repeat. The loop is where budgets and stop conditions live. Missing a budget: a runaway loop spends money until something external stops it.
  • State versus memory. This pair confuses beginners, so be exact. State is what the loop needs to continue this one run: the message list, the step counter, pending approvals. It is gone when the run ends. Memory is what survives between runs: "this customer prefers email". In the sketch below, RunState is created fresh each run, and Memory is passed in and persists. Missing state: the loop cannot resume or be audited. Missing memory: the agent greets a returning customer as a stranger every time.
  • Tools. The agent's hands. Each tool is a named function with a schema. The model can only reach what is registered, so the registry is also your first permission boundary. Over-broad tools are the most common source of agent incidents.
  • Guardrails. Checks your code enforces whatever the model says: on input (too long, injected instructions), on every tool call (is this allowed at this autonomy level?) and on output (redact secrets). Autonomy is implemented here. The model never decides how much freedom it has; a guard function does.

3.3 The sketch#

The program below is the whole anatomy in one file. The model is a ScriptedModel that replays canned decisions, so the output is the same every time and nothing leaves your machine. Each numbered comment is one of the seven parts. Notice that tool_guard is where the four autonomy levels live.

python
# anatomy.py
"""The seven parts of an agent, in about 120 lines of standard-library Python.

Model, instructions, loop, state, tools, memory, guardrails. The model is a scripted
fake, so this runs with no API key and no network.
"""
from __future__ import annotations

import re
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable


# 1. MODEL: anything that maps (instructions, messages) -> one decision.
class ScriptedModel:
    """Replays canned decisions: ("call", tool, args) or ("say", text)."""

    def __init__(self, script: list[tuple]) -> None:
        self._script = list(script)

    def __call__(self, instructions: str, messages: list[dict]) -> tuple:
        return self._script.pop(0) if self._script else ("say", "[script exhausted]")


class Autonomy(Enum):
    SUGGEST = "suggest"            # propose only; nothing runs
    ASSIST = "assist"              # reads run; writes are drafted for a human
    APPROVE = "approve"            # writes run after a human says yes
    AUTONOMOUS = "autonomous"      # writes run inside hard limits; humans review after


# 2. TOOLS: name -> (function, is_write). The model can only reach what is listed here.
ORDERS = {"A17": {"total": 84.50, "status": "delivered"}}
REFUND_LOG: list[tuple[str, float]] = []


def lookup_order(order_id: str) -> dict:
    return ORDERS.get(order_id, {"error": "unknown order"})


def issue_refund(order_id: str, amount: float) -> dict:
    REFUND_LOG.append((order_id, amount))          # the side effect
    return {"refunded": amount, "order_id": order_id}


TOOLS: dict[str, tuple[Callable[..., dict], bool]] = {
    "lookup_order": (lookup_order, False),
    "issue_refund": (issue_refund, True),
}


# 3. MEMORY: survives between runs. (STATE, below, lives for one run only.)
@dataclass
class Memory:
    notes: dict[str, str] = field(default_factory=dict)

    def as_text(self) -> str:
        return "; ".join(f"{k}={v}" for k, v in self.notes.items()) or "(empty)"


# 4. STATE: everything the loop needs to continue this one run.
@dataclass
class RunState:
    messages: list[dict] = field(default_factory=list)
    step: int = 0
    executed: list[str] = field(default_factory=list)
    drafts: list[str] = field(default_factory=list)
    asked_human: list[str] = field(default_factory=list)


# 5. GUARDRAILS: checks on the way in, on every tool call, and on the way out.
def input_guard(text: str) -> str | None:
    return "input too long" if len(text) > 500 else None


def output_guard(text: str) -> str:
    return re.sub(r"\b\d{12,16}\b", "[REDACTED CARD]", text)


REFUND_CAP = 100.0                                  # the autonomous level's hard limit


def tool_guard(level: Autonomy, name: str, args: dict, is_write: bool, human_ok: bool) -> str:
    """Return 'run', 'ask', 'draft' or 'block' for one proposed tool call."""
    if level is Autonomy.SUGGEST:
        return "block"
    if not is_write:
        return "run"
    if level is Autonomy.ASSIST:
        return "draft"
    if level is Autonomy.APPROVE:
        return "run" if human_ok else "ask"
    return "run" if args.get("amount", 0) <= REFUND_CAP else "ask"   # AUTONOMOUS, with a cap


# 6. INSTRUCTIONS + 7. THE LOOP
INSTRUCTIONS = "You are a support agent. Look orders up, refund damaged ones, then answer."


def run_agent(model, level: Autonomy, task: str, memory: Memory, human_ok: bool = False) -> tuple[str, RunState]:
    problem = input_guard(task)
    if problem:
        return f"refused: {problem}", RunState()
    state = RunState(messages=[{"role": "user", "content": task}])
    instructions = f"{INSTRUCTIONS} Autonomy={level.value}. Memory: {memory.as_text()}"
    for state.step in range(1, 7):                              # the loop, with a step cap
        decision = model(instructions, state.messages)
        if decision[0] == "say":                                # no tool call: the loop ends
            return output_guard(decision[1]), state
        _, name, args = decision
        fn, is_write = TOOLS[name]
        verdict = tool_guard(level, name, args, is_write, human_ok)
        if verdict == "run":
            result = fn(**args)
            state.executed.append(f"{name}({args})")
        elif verdict == "draft":
            result = {"not_executed": "drafted for a human to run"}
            state.drafts.append(f"{name}({args})")
        elif verdict == "ask":
            result = {"not_executed": "waiting for human approval"}
            state.asked_human.append(f"{name}({args})")
        else:
            result = {"not_executed": "suggest mode: nothing runs"}
            state.drafts.append(f"{name}({args})")
        state.messages.append({"role": "tool", "name": name, "content": str(result)})
    return "step limit reached", state

Read it in this order: the ScriptedModel (part 1), the TOOLS table (part 5), tool_guard (part 7, the autonomy policy), then run_agent (parts 6 and 3: instructions and loop). Two details are worth pausing on. First, a blocked, drafted or deferred tool call still produces a tool result that the model reads ("not executed: waiting for human approval"), exactly like an error result in 08A.2. The model never sees an exception. Second, the input guard runs before anything else, and the output guard runs last, so a bad string never enters or leaves unchecked.

3.4 Run it: one request, four levels#

The demo sends the same task ("Order A17 arrived damaged. Please refund it.") through the same scripted model at every level. The model always tries to refund; the level decides what actually happens.

python
# anatomy_demo.py
from anatomy import REFUND_LOG, Autonomy, Memory, ScriptedModel, run_agent

TASK = "Order A17 arrived damaged. Please refund it."


def script() -> list[tuple]:
    return [("call", "lookup_order", {"order_id": "A17"}),
            ("call", "issue_refund", {"order_id": "A17", "amount": 84.50}),
            ("say", "Order A17 is handled. Card 4111111111111111 was not touched.")]


memory = Memory(notes={"customer_pref": "email"})
for level, human_ok in [(Autonomy.SUGGEST, False), (Autonomy.ASSIST, False),
                        (Autonomy.APPROVE, False), (Autonomy.APPROVE, True),
                        (Autonomy.AUTONOMOUS, False)]:
    REFUND_LOG.clear()
    answer, state = run_agent(ScriptedModel(script()), level, TASK, memory, human_ok)
    tag = f"{level.value}{' + human said yes' if human_ok else ''}"
    print(f"== {tag}")
    print("  executed :", state.executed)
    print("  drafted  :", state.drafts)
    print("  asked    :", state.asked_human)
    print("  refunds  :", REFUND_LOG)
    print("  answer   :", answer)

# Autonomy has a ceiling: a refund over the cap goes back to a human even at the top level.
REFUND_LOG.clear()
big = [("call", "issue_refund", {"order_id": "A17", "amount": 400.0}), ("say", "done")]
_, state = run_agent(ScriptedModel(big), Autonomy.AUTONOMOUS, TASK, memory)
print("== autonomous, refund of 400.0 (cap is 100.0)")
print("  executed :", state.executed, "| asked :", state.asked_human, "| refunds :", REFUND_LOG)

# Guardrail on the way in, and the difference between state and memory.
print("== input guard:", run_agent(ScriptedModel([]), Autonomy.ASSIST, "x" * 600, memory)[0])
_, s1 = run_agent(ScriptedModel(script()), Autonomy.ASSIST, TASK, memory)
memory.notes["last_order"] = "A17"      # a memory WRITE: your code decides what is worth keeping
_, s2 = run_agent(ScriptedModel(script()), Autonomy.ASSIST, TASK, memory)
print("== state is per run  :", len(s1.messages), "messages, then", len(s2.messages), "(fresh each run)")
print("== memory persists   :", memory.as_text())
Output · real, run with Python 3.14 on 1 December 202635 lines
== suggest
  executed : []
  drafted  : ["lookup_order({'order_id': 'A17'})", "issue_refund({'order_id': 'A17', 'amount': 84.5})"]
  asked    : []
  refunds  : []
  answer   : Order A17 is handled. Card [REDACTED CARD] was not touched.
== assist
  executed : ["lookup_order({'order_id': 'A17'})"]
  drafted  : ["issue_refund({'order_id': 'A17', 'amount': 84.5})"]
  asked    : []
  refunds  : []
  answer   : Order A17 is handled. Card [REDACTED CARD] was not touched.
== approve
  executed : ["lookup_order({'order_id': 'A17'})"]
  drafted  : []
  asked    : ["issue_refund({'order_id': 'A17', 'amount': 84.5})"]
  refunds  : []
  answer   : Order A17 is handled. Card [REDACTED CARD] was not touched.
== approve + human said yes
  executed : ["lookup_order({'order_id': 'A17'})", "issue_refund({'order_id': 'A17', 'amount': 84.5})"]
  drafted  : []
  asked    : []
  refunds  : [('A17', 84.5)]
  answer   : Order A17 is handled. Card [REDACTED CARD] was not touched.
== autonomous
  executed : ["lookup_order({'order_id': 'A17'})", "issue_refund({'order_id': 'A17', 'amount': 84.5})"]
  drafted  : []
  asked    : []
  refunds  : [('A17', 84.5)]
  answer   : Order A17 is handled. Card [REDACTED CARD] was not touched.
== autonomous, refund of 400.0 (cap is 100.0)
  executed : [] | asked : ["issue_refund({'order_id': 'A17', 'amount': 400.0})"] | refunds : []
== input guard: refused: input too long
== state is per run  : 3 messages, then 3 (fresh each run)
== memory persists   : customer_pref=email; last_order=A17

How to read the output:

  • suggest: executed is empty, even though the model asked for a lookup. Both calls ended up in drafted as proposals. No refund exists.
  • assist: the read tool (lookup_order) ran; the refund became a draft for a human to apply. refunds is still empty.
  • approve: the refund was asked about and did not run. With "human said yes", the same code ran it. The only difference between the two blocks is one boolean.
  • autonomous: the 84.50 refund ran by itself, because it is under the 100 cap. A 400 refund at the same level was sent back to a human. Autonomy has a ceiling.
  • The card number in the model's final text was redacted by output_guard, a guardrail on the way out.
  • State and memory: each run started with a fresh 3-message state, while the memory note about the customer persisted, and a note written after one run was visible to the next.

3.5 What the sketch leaves out#

The sketch is anatomy, not production code. It has no real model, no argument validation, no budgets beyond a step cap, no tracing and no durable storage. Each gap has a home:

Missing from the sketch Where to learn it
A real provider adapter, tool schemas, validation, timeouts 08A.2, 08A.6
Token, money and deadline budgets; stagnation detection 08A.3
A real approval pause and resume 08A.12
Idempotent tools, result validation and truncation 08A.7
Real memory stores and context management 08B.1 to 08B.5
Tracing every step 03.12
Security (injection, least privilege, sandboxing) 08A.5

Part 4: Evaluate it#

This lesson's claims are testable: the agent stays inside its autonomy level, the guardrails catch what they should, and the agent still gets the job done at that level. Evaluation has two layers: deterministic checks of your own guard code (cheap, run on every commit) and measurements of a real model's behaviour (sampled, with statistics).

4.1 Where to read first#

Start with the concept lessons, then the tooling.

Then the tooling (all required unless marked optional):

4.2 What to measure for this lesson#

What How Typical pass rule
Autonomy conformance For every level, run a battery of tasks and count actions the level forbids (a write at suggest, a write without approval, a refund above the cap unattended) Zero violations. This is a deterministic test of your guard code, not of the model
Task success at the level Share of tasks reaching the right end state, with an interval Set from the business need; compare levels on the same tasks
Approval load (level 3) Approval rate, rejection reasons, median time to decision Rejection rate under your promotion threshold, with an interval
Guardrail catch rate Planted bad inputs and outputs (too-long text, card numbers) Every planted case caught
Cost per successful task Tokens or money divided by successes (10A.7, 5.6) Reported with every success number, so autonomy gains are not bought with spend

4.3 A concrete tiny eval#

Inputs: six scripted tasks that try a small refund, a refund exactly at the cap, a refund just over the cap, a huge refund, a read-only lookup and a repeated write. Metric: violations per level. Pass rule: zero violations at every level. The script also runs a mutation check: it breaks the cap on purpose and confirms the eval notices. An eval that cannot fail proves nothing.

python
# autonomy_eval.py
"""A tiny conformance eval: does the agent stay inside the autonomy level it was given?

Inputs: six scripted tasks (what the fake model will try). Metric: violations per level.
Pass rule: zero violations at every level. This tests YOUR guard code, not the model."""
from anatomy import REFUND_LOG, Autonomy, Memory, ScriptedModel, run_agent

TASKS = {
    "refund small":      [("call", "issue_refund", {"order_id": "A17", "amount": 20.0}), ("say", "ok")],
    "refund at cap":     [("call", "issue_refund", {"order_id": "A17", "amount": 100.0}), ("say", "ok")],
    "refund over cap":   [("call", "issue_refund", {"order_id": "A17", "amount": 100.01}), ("say", "ok")],
    "refund huge":       [("call", "issue_refund", {"order_id": "A17", "amount": 5000.0}), ("say", "ok")],
    "read only":         [("call", "lookup_order", {"order_id": "A17"}), ("say", "ok")],
    "write then repeat": [("call", "issue_refund", {"order_id": "A17", "amount": 50.0})] * 2 + [("say", "ok")],
}


def violations(level: Autonomy, human_ok: bool) -> list[str]:
    found = []
    for name, script in TASKS.items():
        REFUND_LOG.clear()
        _, state = run_agent(ScriptedModel(script), level, name, Memory(), human_ok)
        writes = [r for r in REFUND_LOG]
        if level in (Autonomy.SUGGEST, Autonomy.ASSIST) and (writes or state.executed and any("refund" in e for e in state.executed)):
            found.append(f"{name}: a write ran at level {level.value}")
        if level is Autonomy.APPROVE and not human_ok and writes:
            found.append(f"{name}: a write ran without approval")
        if level is Autonomy.AUTONOMOUS and any(amount > 100.0 for _, amount in writes):
            found.append(f"{name}: a refund above the cap ran unattended")
    return found


total = 0
for level, human_ok in [(Autonomy.SUGGEST, False), (Autonomy.ASSIST, False), (Autonomy.APPROVE, False),
                        (Autonomy.APPROVE, True), (Autonomy.AUTONOMOUS, False)]:
    v = violations(level, human_ok)
    total += len(v)
    label = level.value + (" (human said yes)" if human_ok else "")
    print(f"{label:28s} violations: {len(v)}", v if v else "")
print("PASS" if total == 0 else f"FAIL ({total} violations)")

# Does the eval itself work? Break the guard on purpose (a wrong cap) and make sure it notices.
import anatomy

anatomy.REFUND_CAP = 1000.0
broken = violations(Autonomy.AUTONOMOUS, False)
print("with a wrongly raised cap:", broken)
print("eval detects the bug" if broken else "EVAL IS BLIND: fix the eval")
Output · real, run with Python 3.14 on 1 December 20268 lines
suggest                      violations: 0 
assist                       violations: 0 
approve                      violations: 0 
approve (human said yes)     violations: 0 
autonomous                   violations: 0 
PASS
with a wrongly raised cap: ['refund over cap: a refund above the cap ran unattended']
eval detects the bug

Three things to notice. The boundary cases are in the battery: 100.0 sits on the cap and 100.01 just over it. The mutation check printed a violation, which shows the eval is not blind to a cap that is too high. And the eval only counts forbidden actions, so it cannot see an agent that has become uselessly cautious; that is what the task-success measurement in 4.2 is for. With a real model you would replace the scripted decisions with recorded or live runs, keep the same invariants, and add a success-rate measurement with an interval.


Common misconceptions#

  • "An agent is a smarter chatbot." It is a different shape: a loop with tools, not a better conversation. A chatbot with a better model is still a chatbot.
  • "Agentic AI replaces generative AI." It is built on it. Generative AI is the engine; agentic is how you wire the engine to actions.
  • "Autonomy is a feature of the model." It is a setting in your code. The same model runs at level 1 or level 4 depending on tool_guard.
  • "More autonomy is always the goal." The goal is the right autonomy for each action. Many of the best agents in production sit at levels 2 and 3 for most actions.
  • "Human in the loop means a human watches everything." At level 3 the human decides on each risky action, at level 4 they review after the fact. Both are legitimate; they are different loads and different risks.
  • "Memory and state are the same thing." State lives for one run, memory persists across runs, and they fail in different ways.
  • "If the prompt says 'never refund over 100', it is safe." A prompt is a request. A cap in tool_guard is a rule. Enforce limits in code.

Key takeaways#

  • The one question that separates the terms: who picks the next step? Your code means workflow; the model means agent.
  • Generative AI names a capability, agentic AI a system design built on it. They are not rivals.
  • Autonomy has four levels: suggest, assist, act with approval, act autonomously. Choose per action by blast radius, reversibility, volume, evidence and observability.
  • Earn autonomy with measurements (with intervals) and make demotion as easy as promotion.
  • An agent is seven parts: model, instructions, loop, state, tools, memory, guardrails. Name the part when you debug.
  • State is one run; memory is many runs.
  • Autonomy lives in the guardrails. Enforce it with code that holds even when the model is wrong.
  • Test the policy with a deterministic conformance eval that includes a mutation check.

Terms introduced in this lesson#

Term Meaning
Chatbot A conversational interface that answers in text and rarely takes actions
Assistant A model-powered helper that works alongside a person, usually read-only; a human applies the result
Workflow A predefined sequence of steps in which some steps call a model; your code decides what happens next
Agent A system in which the model chooses its next action in a loop, using tools, until the goal is met
Generative AI Models that generate content from a prompt; a capability
Agentic AI Software that pursues goals by deciding on and taking actions; a system design built on generative models
Autonomy spectrum The range from suggest through assist and act-with-approval to act-autonomously
Suggest Autonomy level 1: the agent proposes; nothing runs
Assist Autonomy level 2: the agent runs read tools and drafts; a human applies writes
Act with approval Autonomy level 3: the agent runs writes only after a human approves each one
Act autonomously Autonomy level 4: the agent runs writes by itself, inside hard limits, with review after the fact
Blast radius The worst damage one action can do before something stops it
Agent anatomy The seven parts of an agent: model, instructions, loop, state, tools, memory, guardrails
State Everything the loop needs to continue one run; gone when the run ends
Memory Information that persists between runs
Guardrail A check enforced in code on input, on tool calls or on output, whatever the model says
Policy layer The function that maps (tool, arguments, context) to run, ask, draft or block
Conformance eval A deterministic test that the agent stays within the rules of its autonomy level
Mutation check Breaking a rule on purpose to confirm the eval notices

Exercises#

  1. A per-tool level. Add a delete_order write tool that is never autonomous: even at the top level, it must ask a human. Show it in the demo. Hint: give TOOLS a third field per tool, a min_level_to_run_unattended, or add a name check at the top of tool_guard so delete_order returns "ask" for AUTONOMOUS. Then add a task to autonomy_eval.py that tries it.
  2. An audit log. Record every guard decision (step, tool, arguments, verdict, level) in a list on RunState, and print it after a run. Which verdicts would you want to alert on? Hint: append a dict in run_agent right after tool_guard returns; the interesting alerts are repeated ask verdicts for the same tool and any block at a level that should never block.
  3. Break the eval. Make two separate changes to the autonomous cap check, one at a time: change <= to <, then (with <= restored) change the constant to 100.01. Does the eval notice each change? One of them it will miss. Say which, say why, and add a check that catches it. Hint: the eval only counts forbidden actions. Mutation one makes the agent too cautious (the 100.0 refund now asks instead of running), which is not a violation, so add an "expected to run unattended" assertion for the at-cap task. Mutation two lets 100.01 run, which the existing over-cap task catches.
  4. Classify five ideas. Place each on the four-level scale and say what would make you promote it: (a) a code-completion tool, (b) a meeting-notes summariser that emails the notes to attendees, (c) a cloud-cost agent that shuts down idle servers, (d) a research agent that searches the web and writes a report for you, (e) a tool that auto-replies to customer complaints. Hint: ask for each one what the worst single action is and whether it can be undone; (b) and (e) contact other people, which is rarely reversible.
  5. A real model behind the guard. Take the OpenAI Responses or Anthropic Messages loop from 08A.2, Part 2 and put this lesson's tool_guard between the model's tool call and run_tool. Run it with a key and check your output against the conformance eval's invariants. Hint: the guard needs only the tool name, the parsed arguments and the level; return a "not executed" result string for ask, draft and block so the model reads it as a tool result.

Check yourself#

  1. What single question separates a workflow from an agent?
  2. Why is "agentic AI versus generative AI" not a choice between two technologies?
  3. Name the four autonomy levels and say who executes the write actions at each.
  4. Why can one agent have several autonomy levels at once?
  5. Give three questions you ask when choosing the autonomy level for an action.
  6. What is the difference between state and memory? Give one example of each.
  7. Where in the anatomy does autonomy live, and why not in the prompt?
  8. What is a mutation check, and why does the conformance eval include one?
  9. A team says "the agent is autonomous because it never asks for approval". What would you ask before agreeing?

Further resources#


← Module 07: Retrieval-Augmented Generation (RAG) | Module 08A overview | 08A.2 — The Tool Loop: From One Round Trip to an Agent →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close