TExcelTAD
Home › Generative AI & LLMs › Agents

Agents

An agent is an LLM that works in a loop: it decides on an action (usually a tool call), observes the result, and decides again — until the task is done. Where a single prompt answers a question, an agent can carry out a multi-step task: research a topic across several searches, fix a failing test by reading files and running code, or reorganise a calendar.

The agent loop

text
goal ──► model thinks ──► action (tool call) ──► observation (tool result) ──┐
            ▲                                                                │
            └────────────────────────────────────────────────────────────────┘
         … until the model returns a final answer, or a limit is reached

It is the tool-use loop from the previous section, run for as many steps as needed, with the model choosing the next step each time.

A toy agent

The "model" below is a deterministic policy function that looks at the goal and what it has observed so far — standing in for an LLM deciding the next action. The tools, loop, step limit and trace are real:

python · try it yourself
import json

# --- tools -------------------------------------------------------------
INVENTORY = {"oat milk": 0, "coffee beans": 3, "cups": 40}
SUPPLIERS = {"oat milk": "GreenDairy", "coffee beans": "RoastCo"}
orders = []

def check_stock(item):
    return {"item": item, "count": INVENTORY.get(item, 0)}

def find_supplier(item):
    return {"item": item, "supplier": SUPPLIERS.get(item, "unknown")}

def place_order(item, supplier, quantity):
    orders.append((item, supplier, quantity))
    return {"status": "ordered", "item": item, "quantity": quantity}

TOOLS = {"check_stock": check_stock, "find_supplier": find_supplier, "place_order": place_order}

# --- stand-in for the LLM: chooses the next action from the history -------
def policy(goal, history):
    items = goal["items"]
    seen = {(h["tool"], h["args"].get("item")): h["result"] for h in history}
    for item in items:
        if ("check_stock", item) not in seen:
            return {"tool": "check_stock", "args": {"item": item}}
    for item in items:
        if seen[("check_stock", item)]["count"] < goal["min_stock"]:
            if ("find_supplier", item) not in seen:
                return {"tool": "find_supplier", "args": {"item": item}}
            if ("place_order", item) not in seen:
                supplier = seen[("find_supplier", item)]["supplier"]
                return {"tool": "place_order", "args": {"item": item, "supplier": supplier, "quantity": 10}}
    return {"final": f"Done. Orders placed: {len(orders)}."}

# --- the agent loop -------------------------------------------------------
goal = {"items": ["oat milk", "coffee beans", "cups"], "min_stock": 5}
history = []
for step in range(1, 11):                       # hard step limit
    action = policy(goal, history)
    if "final" in action:
        print(f"step {step}: FINAL -> {action['final']}")
        break
    result = TOOLS[action["tool"]](**action["args"])
    history.append({**action, "result": result})
    print(f"step {step}: {action['tool']}({json.dumps(action['args'])}) -> {result}")
else:
    print("stopped: step limit reached")
step 1: check_stock({"item": "oat milk"}) -> {'item': 'oat milk', 'count': 0}
step 2: check_stock({"item": "coffee beans"}) -> {'item': 'coffee beans', 'count': 3}
step 3: check_stock({"item": "cups"}) -> {'item': 'cups', 'count': 40}
step 4: find_supplier({"item": "oat milk"}) -> {'item': 'oat milk', 'supplier': 'GreenDairy'}
step 5: place_order({"item": "oat milk", "supplier": "GreenDairy", "quantity": 10}) -> {'status': 'ordered', 'item': 'oat milk', 'quantity': 10}
step 6: find_supplier({"item": "coffee beans"}) -> {'item': 'coffee beans', 'supplier': 'RoastCo'}
step 7: place_order({"item": "coffee beans", "supplier": "RoastCo", "quantity": 10}) -> {'status': 'ordered', 'item': 'coffee beans', 'quantity': 10}
step 8: FINAL -> Done. Orders placed: 2.

A real agent's "policy" is the LLM reading the whole history (goal, previous tool calls and results) in its context window and choosing the next tool call. That flexibility is the point — it can handle situations nobody scripted — and also the risk: it can make wrong choices, loop, or act on misleading data.

Planning first

For longer tasks, a common pattern asks the model for a plan first, then executes it step by step, revising the plan when an observation is surprising:

python · try it yourself
plan = [
    "Search the docs for the deprecated function name",
    "List every file that calls it",
    "Update each call to the new API",
    "Run the test suite",
    "Summarise the changes",
]
done = {0, 1}
for i, step in enumerate(plan):
    mark = "x" if i in done else " "
    print(f"[{mark}] {i + 1}. {step}")
print(f"progress: {len(done)}/{len(plan)}")
[x] 1. Search the docs for the deprecated function name
[x] 2. List every file that calls it
[ ] 3. Update each call to the new API
[ ] 4. Run the test suite
[ ] 5. Summarise the changes
progress: 2/5

Keeping the plan as explicit state (a to-do list in the context or in a file) helps the agent stay on track over many steps and lets humans see what it is doing.

Guardrails

Agents act in the world, so they need limits — enforced by your code, not just requested in the prompt:

python · try it yourself
ALLOWED = {"check_stock", "find_supplier", "place_order"}
NEEDS_APPROVAL = {"place_order"}
BUDGET = {"max_steps": 10, "max_order_quantity": 50}

def guard(action, approved_by_human=False):
    if action["tool"] not in ALLOWED:
        return "blocked: tool not allowed"
    if action["tool"] == "place_order" and action["args"]["quantity"] > BUDGET["max_order_quantity"]:
        return "blocked: quantity over limit"
    if action["tool"] in NEEDS_APPROVAL and not approved_by_human:
        return "paused: waiting for human approval"
    return "allowed"

tests = [
    ({"tool": "check_stock", "args": {"item": "cups"}}, False),
    ({"tool": "delete_database", "args": {}}, False),
    ({"tool": "place_order", "args": {"item": "cups", "quantity": 500}}, True),
    ({"tool": "place_order", "args": {"item": "cups", "quantity": 20}}, False),
    ({"tool": "place_order", "args": {"item": "cups", "quantity": 20}}, True),
]
for action, approved in tests:
    print(f"{action['tool']:<16} approved={approved!s:<5} -> {guard(action, approved)}")
check_stock      approved=False -> allowed
delete_database  approved=False -> blocked: tool not allowed
place_order      approved=True  -> blocked: quantity over limit
place_order      approved=False -> paused: waiting for human approval
place_order      approved=True  -> allowed
Guardrail Purpose
Step / time / cost limits stop runaway loops
Tool allow-list, least privilege the agent can only do what it must
Human approval for irreversible actions payments, deletions, sending messages
Sandboxing run code and file operations in an isolated environment
Logging every step debugging, auditing, evaluation

When (not) to use an agent

Agents are slower, more expensive and less predictable than a fixed pipeline. If the steps are always the same (retrieve → answer, or extract → validate → store), write a workflow in code and call the model at specific points. Use an agent when the path genuinely depends on what is discovered along the way.

Test yourself

What distinguishes an agent from a single LLM call?

  1. It uses a larger model
  2. It loops: choosing actions, observing results and deciding again until done
  3. It never uses tools
  4. It has no context window

Where should limits like 'max 10 steps' and 'approval before payments' be enforced?

  1. Only in the prompt
  2. In the application code that runs the loop and the tools
  3. In the tokenizer
  4. Nowhere; agents are self-limiting

Your task always follows the same three steps. What is usually the better design?

  1. A fully autonomous agent
  2. A fixed workflow in code that calls the model at specific steps
  3. No LLM at all, ever
  4. A bigger context window