Skip to content
AgenticAIWiki
  1. Learn
  2. Part 9
  3. 51. Agent frameworks compared
  4. 51.5

Lesson 51.5 · 5 of 6 · 4 min read · Reviewed 24 Nov 2026

No framework: the plain loop

By the end, you can

  • Build an agent with no framework.
  • Know when that's the best choice.

The whole thing

def run(task, tools, max_steps=20):
    messages = [{"role": "user", "content": task}]
    for step in range(max_steps):
        r = client.messages.create(model=MODEL, max_tokens=4096,
                                   system=SYSTEM, tools=SCHEMAS, messages=messages)
        log(step, r)                                   # trace every call
        messages.append({"role": "assistant", "content": r.content})
        if r.stop_reason != "tool_use":
            return text_of(r)
        results = [execute(b, tools) for b in r.content if b.type == "tool_use"]
        messages.append({"role": "user", "content": results})
    return "Stopped: step limit reached"

Add as needed: retries with backoffExponential backoff: Waiting longer after each failed retry, for example 1, 2, 4 then 8 seconds. (1.7), prompt cachingPrompt caching: Reusing the processed form of a repeated prompt prefix across requests, which cuts cost and latency. (70.1), compactionCompaction: Summarising older conversation history so a long session fits in the context window while keeping what matters. (chapter 60), permission checks before risky tools (chapter 44).

The official SDKs also include a lightweight tool runner that drives this loop for tools you define, which sits between a hand-written loop and a full framework.

When it’s the right choice

  • Small and medium agentsAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. with a handful of tools.
  • When cost and behaviour must be fully visible.
  • When you want to understand agents before adopting a framework.

When to reach for more

  • You need durable checkpoints, human-in-the-loopHuman-in-the-loop: A design where a person reviews, approves or corrects AI decisions at defined points. pauses and resumable runs at scale (51.3).
  • You want file and shell tools with proven permissionsPermission rule: An allow, ask or deny rule that controls which tools, commands or paths a coding agent may use. (51.2).

Key points

  • A plain loop is a few dozen lines: call the model, run any tool calls, send results back, stop on a final answer.
  • You see and control every prompt, call and token.
  • You write your own state, retries, tracing and limits, which is often less work than it sounds.
  • It's a strong default for small to medium agents and for learning how agents really work.
Hands-on labRuns in the Playground

Write the plain loop with full tracing

Own every part of a small agent loop, and log each call with its stop reason and token counts.

You will have: A plain agent loop with a step limit and a printed trace of every model call.

Steps

  1. Run the starter: it answers, but the trace is empty.
  2. Write log() to record the step, stop reason and token counts.
  3. Print the total input tokens at the end.
  4. Set max_steps to 1 and check the loop returns the step-limit message.
  5. List what you would add next: retries, a budget, or a hook-style check before execute().

Done when

  • The trace shows 2 calls: tool_use, then end_turn.
  • The answer mentions order A-1042.
  • With max_steps = 1 the run ends with 'Stopped: step limit reached'.

Open in the Playground No API key needed.

Starter code (Python)
import json
import anthropic

# The plain loop: a few dozen lines, and you see every call and token.
client = anthropic.Anthropic()   # simulated key and model
MODEL = "claude-sonnet-5-5"
SYSTEM = "You are a support agent for a lamp shop."
ORDERS = {"A-1042": {"item": "desk lamp", "status": "delivered", "total": 35}}
TOOLS = [{
    "name": "get_order",
    "description": "Look up an order by its id, like A-1042. Returns item, status and total.",
    "input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
}]
trace = []


def log(step, r):
    # TODO: append (step, stop_reason, input_tokens, output_tokens) to trace and print one line
    pass


def execute(content):
    results = []
    for b in content:
        if b.type == "tool_use":
            order = ORDERS.get(b.input.get("order_id"))
            results.append({"type": "tool_result", "tool_use_id": b.id,
                            "content": json.dumps(order) if order else "No such order", "is_error": order is None})
    return results


def run(task, max_steps=5):
    messages = [{"role": "user", "content": task}]
    for step in range(1, max_steps + 1):
        r = client.messages.create(model=MODEL, max_tokens=400, system=SYSTEM, tools=TOOLS, messages=messages)
        log(step, r)
        messages.append({"role": "assistant", "content": r.content})
        if r.stop_reason != "tool_use":
            return "".join(b.text for b in r.content if b.type == "text")
        messages.append({"role": "user", "content": execute(r.content)})
    return "Stopped: step limit reached"


print("answer:", run("Has order A-1042 arrived?"))
print("calls traced:", len(trace))
Show a solution
import json
import anthropic

# The plain loop: a few dozen lines, and you see every call and token.
client = anthropic.Anthropic()   # simulated key and model
MODEL = "claude-sonnet-5-5"
SYSTEM = "You are a support agent for a lamp shop."
ORDERS = {"A-1042": {"item": "desk lamp", "status": "delivered", "total": 35}}
TOOLS = [{
    "name": "get_order",
    "description": "Look up an order by its id, like A-1042. Returns item, status and total.",
    "input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
}]
trace = []


def log(step, r):
    u = r.usage
    trace.append((step, r.stop_reason, u.input_tokens, u.output_tokens))
    print(f"step {step}: stop_reason={r.stop_reason} in={u.input_tokens} out={u.output_tokens}")


def execute(content):
    results = []
    for b in content:
        if b.type == "tool_use":
            order = ORDERS.get(b.input.get("order_id"))
            results.append({"type": "tool_result", "tool_use_id": b.id,
                            "content": json.dumps(order) if order else "No such order", "is_error": order is None})
    return results


def run(task, max_steps=5):
    messages = [{"role": "user", "content": task}]
    for step in range(1, max_steps + 1):
        r = client.messages.create(model=MODEL, max_tokens=400, system=SYSTEM, tools=TOOLS, messages=messages)
        log(step, r)
        messages.append({"role": "assistant", "content": r.content})
        if r.stop_reason != "tool_use":
            return "".join(b.text for b in r.content if b.type == "text")
        messages.append({"role": "user", "content": execute(r.content)})
    return "Stopped: step limit reached"


print("answer:", run("Has order A-1042 arrived?"))
print("calls traced:", len(trace))
print("total input tokens:", sum(t[2] for t in trace))
Quick checkWhat is the main advantage of a plain, framework-free agent loop?
How sure are you?
Pick an answer and how sure you are