Skip to content

Module 01 · Lesson 1.3

Agent Components: Model, Instructions, Tools, State and Runtime

40 minUpdated 13 Nov 2026Part of AI Agent Foundations · AI Agent Development
On this page
  1. What you will learn
  2. Five components, five jobs
  3. Instructions: guidance, not enforcement
  4. Tools: a contract and a risk level
  5. State: three things that get confused
  6. Step by step: build the five components apart
  7. The contract for the approval-gated tool
  8. Security and reliability: put each control where it can work
  9. Common errors and fixes
  10. Validation checklist
  11. Hands-on exercise
  12. Knowledge check
  13. References

When an agent misbehaves, teams often reach for the prompt first. Sometimes that is right. Just as often the fault is somewhere else: a tool that accepts any argument, a history that grows until the useful facts fall out of view, or a loop with no limit. If you cannot say which part of the system is responsible for a behaviour, you cannot fix it on purpose.

This lesson names five components and gives each one a single job. You will meet the questions to ask about each, then see all five as separate, replaceable pieces in one runnable Python file. The model is still a scripted stand-in, so the example works offline. The new idea compared with the previous lessons is a tool that needs human approval before it takes effect.

What you will learn

  • Name the five components of an agent and state what each one is responsible for.
  • Write instructions that separate role, rules, scope and output format.
  • Describe a tool as a contract with a risk level, and decide when it needs approval.
  • Distinguish run state, conversation history and persistent memory.
  • Place each safety control in the component that can actually enforce it.

Before you start

Five components, five jobs

Every agent in this program, whatever framework or provider it uses, can be described with the same five parts. Frameworks bundle them differently and give them different names, but the separation is a design principle rather than a vendor feature, and it is the quickest way to locate a problem.

Model
The language model that reads the instructions and the history and proposes the next action. It is the only non-deterministic part. Its job is judgement over language: which tool, with what arguments, or what to say.
Instructions
The standing text that tells the model its role, rules, scope and output format. Instructions shape behaviour, but they are guidance, never enforcement.
Tools
The functions the agent may request, each described by a contract: name, purpose, argument schema and risk level. Tools are the only way the agent touches the outside world.
State
Everything the run knows: the messages so far, the number of steps taken, queued approvals and the log. Some state is shown to the model; some, such as the step counter, is for the runtime alone.
Runtime
The ordinary code that runs the loop. It calls the model, validates each request, executes or queues tools, updates state and decides when to stop. It is deterministic and testable.
How the components fit together
  1. Instructions and state

    Assembled into the next request

  2. Model

    Proposes a tool call or an answer

  3. Runtime

    Validates, applies limits, queues approvals

  4. Tool

    Read-only runs now; write waits for a person

  5. State updated

    Observation and log recorded; loop or stop

The model sits inside the runtime. It never reaches tools or state directly.

Instructions: guidance, not enforcement

Good instructions are short and specific. A useful structure has four parts: the role (who the agent is helping and with what), the rules (how it must behave), the scope (what it must decline or hand over) and the output format (what a reply looks like). Here are the instructions for a Quillfeather Cycles order assistant, used in the code below.

Textinstructions.txt
Role: You help Quillfeather Cycles customers with questions about their own orders.
Rules: Look facts up with tools. Never guess a status or a date.
       A return is never decided by you: request it, then tell the customer that a member of staff will confirm it.
Scope: Decline refunds, payment problems and anything about other customers; offer to pass the customer to a person.
Format: Two short sentences or fewer, plain text, no promises about outcomes.

Notice what the instructions do not try to do. They do not say "never issue a refund" as if that were the safeguard. The safeguard is that no refund tool exists. Instructions reduce how often the model attempts something unwanted; the tool list and the runtime decide what is possible. Module 2 covers writing instructions in depth.

Tools: a contract and a risk level

A tool has two faces. To the model it is a description and a schema. To your runtime it is a function with consequences. Record both, and add a third attribute that the model never sees: how risky the tool is.

ToolEffectRiskRuntime treatment
lookup_orderReads one orderLow: read-onlyValidate arguments, run immediately
request_returnRecords a return request for staffMedium: creates a record that staff act onValidate arguments, queue for approval, run only after a person approves
issue_refund (not built)Moves moneyHigh: irreversibleNot offered to this agent at all
Risk is decided by the effect of the tool, not by how it is described to the model.

Least privilege applies here exactly as it does for any service account: give the agent the smallest set of tools that lets it do its job. A tool you did not register cannot be called, no matter what the model asks for. Module 3 looks at schemas, authentication and error handling for real APIs.

State: three things that get confused

"Memory" is used for several different things. Separate them early, because they have different lifetimes, different privacy implications and different failure modes.

  • Run state lives for one run: the step counter, queued approvals and the trace. Mostly for the runtime; the model rarely needs it.
  • Conversation history is the list of messages the model is shown. It grows with every step, costs tokens and eventually has to be trimmed or summarised.
  • Persistent memory survives between runs, such as a customer's stated preferences. It needs a retention rule, a way to correct or delete entries and a clear reason to exist.

The example below keeps only run state and history. It deliberately has no persistent memory, because nothing in the task requires one. Module 4 covers context windows, retrieval and the data lifecycle of memory.

Step by step: build the five components apart

  1. Step 1: Describe each tool with a dataclass

    Tool bundles the contract (name, description, required arguments) with the handler and a needs_approval flag. Registering a tool means adding it to one dictionary, which is also your allowlist.

  2. Step 2: Keep state in one object

    RunState holds the messages, the step count, the approval queue and the log. Passing one object around makes a run easy to inspect and easy to save for a test.

  3. Step 3: Validate before you execute

    check_call() rejects unknown tools, missing or extra arguments and a malformed order ID. It returns an error string or None. The error becomes an observation, so the model can recover.

  4. Step 4: Queue write tools for a person

    When a tool has needs_approval, the runtime stores the request in state.approvals and returns an awaiting_approval observation. Nothing runs until approve() is called, which stands in for a staff member's decision.

  5. Step 5: Run the file

    Save it as agent_components.py and run python agent_components.py.

    What you should see: A trace of three steps, a pending approval, and then the approved action recorded.

Pythonagent_components.py
"""The five agent components as separate pieces.

Model:        call_model()  (scripted here; a real provider call later)
Instructions: INSTRUCTIONS  (passed to the model every turn)
Tools:        Tool + TOOLS  (contract, handler, approval flag)
State:        RunState
Runtime:      Runtime       (validates, queues approvals, enforces limits)
"""
import json
import re
from dataclasses import dataclass, field
from typing import Callable

# Fictional sample data for Quillfeather Cycles.
ORDERS = {
    "QF-1042": {"status": "dispatched", "estimated_delivery": "2026-11-18"},
    "QF-1044": {"status": "delivered", "estimated_delivery": "2026-11-09"},
}

INSTRUCTIONS = (
    "Help Quillfeather Cycles customers with their own orders. Look facts up "
    "with tools. A return is never decided by you: request it and say that "
    "staff will confirm. Decline refunds and payment problems."
)

ORDER_ID = re.compile(r"^QF-[0-9]{4}$")


@dataclass(frozen=True)
class Tool:
    name: str
    description: str
    handler: Callable[..., dict]
    required: tuple[str, ...]
    needs_approval: bool = False  # runtime-only attribute; the model never sees it


def lookup_order(order_id: str) -> dict:
    order = ORDERS.get(order_id)
    if order is None:
        return {"error": f"no order with id {order_id}"}
    return {"order_id": order_id, **order}


def request_return(order_id: str) -> dict:
    # In a real system this would create a record for staff to review.
    return {"order_id": order_id, "return_request": "recorded"}


TOOLS = {
    t.name: t
    for t in [
        Tool("lookup_order", "Read-only: status of one order.", lookup_order, ("order_id",)),
        Tool("request_return", "Ask staff to review a return.", request_return,
             ("order_id",), needs_approval=True),
    ]
}


@dataclass
class RunState:
    messages: list = field(default_factory=list)
    steps: int = 0
    approvals: list = field(default_factory=list)  # queued write requests
    log: list = field(default_factory=list)


def call_model(instructions: str, messages: list[dict]) -> dict:
    """Scripted stand-in. A real model would receive instructions and messages."""
    wants_return = "return" in messages[0]["content"].lower()
    last = messages[-1]
    if last["role"] == "user":
        match = re.search(r"QF-\d{4}", last["content"])
        if match is None:
            return {"type": "final", "text": "Which order? Order IDs look like QF-1234."}
        return {"type": "tool_call", "name": "lookup_order",
                "arguments": {"order_id": match.group()}}
    result = json.loads(last["content"])
    if "error" in result:
        return {"type": "final", "text": "That order could not be found or the request was invalid."}
    if result.get("return_request") == "awaiting_approval":
        return {"type": "final", "text": "I have asked a member of staff to review a return. "
                                         "You will hear from us once they decide."}
    if wants_return and result.get("status") == "delivered":
        return {"type": "tool_call", "name": "request_return",
                "arguments": {"order_id": result["order_id"]}}
    if wants_return:
        return {"type": "final", "text": "That order has not been delivered yet, so it cannot be returned."}
    return {"type": "final", "text": f"Order {result['order_id']} is {result['status']}."}


class Runtime:
    def __init__(self, tools: dict[str, Tool], max_steps: int = 5):
        self.tools = tools
        self.max_steps = max_steps

    def check_call(self, name: str, args: dict) -> str | None:
        """Return an error message, or None if the call is acceptable."""
        tool = self.tools.get(name)
        if tool is None:
            return f"unknown tool {name}"
        if set(args) != set(tool.required):
            return f"arguments must be exactly {list(tool.required)}"
        if not ORDER_ID.match(str(args.get("order_id", ""))):
            return "order_id must look like QF-1234"
        return None

    def run(self, state: RunState, user_message: str) -> str:
        state.messages.append({"role": "user", "content": user_message})
        while state.steps < self.max_steps:
            state.steps += 1
            decision = call_model(INSTRUCTIONS, state.messages)
            if decision["type"] == "final":
                print(f"  step {state.steps}: final")
                return decision["text"]
            name, args = decision["name"], decision["arguments"]
            error = self.check_call(name, args)
            if error:
                result, note = {"error": error}, "rejected"
            elif self.tools[name].needs_approval:
                state.approvals.append({"tool": name, "arguments": args})
                result, note = {"return_request": "awaiting_approval"}, "queued for approval"
            else:
                result, note = self.tools[name].handler(**args), "ok"
            print(f"  step {state.steps}: {name} {args} -> {note}")
            state.messages.append({"role": "assistant", "content": json.dumps(decision)})
            state.messages.append({"role": "tool", "content": json.dumps(result)})
        return "Stopped: step limit reached."

    def approve(self, state: RunState, index: int) -> dict:
        """Stands in for a person approving one queued action."""
        request = state.approvals.pop(index)
        return self.tools[request["tool"]].handler(**request["arguments"])


if __name__ == "__main__":
    runtime, state = Runtime(TOOLS), RunState()
    print(runtime.run(state, "Can I return order QF-1044?"))
    print("pending:", state.approvals)
    print("after staff approval:", runtime.approve(state, 0))

Offline and provider-neutral. Only call_model() would change when you connect a real model.

Sample runIllustrative — your output will differ
  step 1: lookup_order {'order_id': 'QF-1044'} -> ok
  step 2: request_return {'order_id': 'QF-1044'} -> queued for approval
  step 3: final
I have asked a member of staff to review a return. You will hear from us once they decide.
pending: [{'tool': 'request_return', 'arguments': {'order_id': 'QF-1044'}}]
after staff approval: {'order_id': 'QF-1044', 'return_request': 'recorded'}

Compare the trace with the code. The model chose both tool calls, but the runtime decided that the second one waits. The customer-facing answer was written before anything irreversible happened, and the model's text says staff "will" decide, which matches the runtime's record.

The contract for the approval-gated tool

The model-facing contract is provider-neutral JSON. Notice that it describes the approval step honestly, so the model does not promise the customer something the runtime will not do. The needs_approval flag itself is not part of the contract. The runtime owns it.

JSONrequest_return.tool.json
{
  "name": "request_return",
  "description": "Ask Quillfeather staff to review a return for one delivered order. This only records a request; a member of staff decides. Use it when a customer asks to return an order whose status is delivered.",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "description": "Order ID: QF- followed by four digits.",
        "pattern": "^QF-[0-9]{4}$"
      }
    },
    "required": ["order_id"],
    "additionalProperties": false
  }
}

Security and reliability: put each control where it can work

ControlBelongs inWhy
Step limitRuntimeA counter cannot be argued with; wording can
Tool allowlistRuntime and tool registryAn unregistered tool cannot run
Argument validationRuntimeModels produce plausible but sometimes wrong arguments
Approval for write toolsRuntimeOnly code can hold an action until a person decides
Tone, scope and formatInstructionsGuidance the model usually follows, and the right place for style
SecretsTool handlers, from environment variablesThey never enter instructions, messages or logs

Common errors and how to fix them

The agent attempts actions it should not, and the team keeps rewriting the instructions.

Why it happens: A control that needs enforcement was placed in the instructions.

Fix: Move it to the runtime or the tool list: remove the tool, validate the arguments or require approval.

A write tool runs as soon as the model asks.

Why it happens: The runtime treats every registered tool the same way.

Fix: Give tools a risk attribute that the runtime reads, and queue anything with consequences for a person.

Answers get worse as a conversation gets longer.

Why it happens: History grows without limit and the useful facts are buried or truncated.

Fix: Keep history in one place, measure it and trim or summarise it deliberately. See Module 4.

The model's reply says an action was completed when it was only queued.

Why it happens: The observation or the tool description did not make the pending state clear.

Fix: Return an explicit status such as awaiting_approval and describe the approval step in the tool contract.

A test that reruns a failed conversation cannot reproduce it.

Why it happens: State was spread across globals and not captured.

Fix: Keep run state in one object that you can serialise and replay.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Add a third tool and place its controls

Extend agent_components.py with a tool draft_reply_to_customer(order_id, text) that returns a draft message for a person to send. Decide its risk level, whether it needs approval, and where each rule you add belongs.

You will need

  • agent_components.py from this lesson.
  • Rule 1: a draft must be 300 characters or fewer.
  • Rule 2: the agent must never send the message itself.
  • Rule 3: drafts must be written in a friendly, plain tone.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Rules that can be checked by code, such as length, are runtime rules. Rules about style are instruction rules.
  • check_call() currently expects exactly one argument. Generalise it so each tool lists its own required arguments.
  • Returning a draft is different from sending one. Consider whether the draft tool needs approval, or whether the later send step does.
Show a model answer

A good answer rates the draft tool as low to medium risk: it changes nothing outside the system, but a person might send a draft without reading it, so the UI must label it as unsent. The length limit belongs in the runtime because it is checkable: extend check_call() to read a per-tool validator and return an error string when len(text) > 300, so the model sees the error and can shorten the draft. The tone rule belongs in the instructions because code cannot judge friendliness reliably; add one line to INSTRUCTIONS and leave the runtime alone. Rule 2 is enforced by construction: the handler returns {"draft": text} and no function in the file sends a message. Approval is not needed to create the draft, but any future send tool would be High risk and needs it. The note should say that each rule is placed in the one component that can actually guarantee it.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Which component should enforce a maximum of five steps per run?
    Show the answer and explanation

    Answer: C. The runtime owns the loop, so a counter there is certain. The instructions option is tempting because it is easy to write, but a model can miscount or be steered past it. A single tool cannot see the whole run unless the runtime tells it, which makes the loop the natural place.

  2. 2.What is the difference between run state and persistent memory?
    Show the answer and explanation

    Answer: B. Lifetime is the difference, and lifetime drives privacy and cleanup decisions. The last option is tempting but wrong: what is shown to the model is a separate choice, and some run state, such as the step counter, is only for the runtime.

  3. 3.A tool records a request that staff will act on. Which treatment is most appropriate?
    Show the answer and explanation

    Answer: B. A request staff act on has consequences, so it needs both validation and approval. Valid arguments alone do not make an action appropriate, which is why the first option falls short. Staff review does not replace validation either: bad input should be stopped early.

Written by
PromptFable Editorial
Last updated 13 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.