Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

The Loop in Sixty Lines

Write a complete agent loop in about sixty lines of Python without a framework: keep the message history valid across turns, dispatch each tool call to a handler, turn tool errors into results, and stop on a final answer or a turn limit.

Contentsand lesson path

What you will learn

  • Implement a framework-free agent loop that alternates model calls and tool executions until a final answer or a stop condition.

Prerequisites: Tool Calling

01. The Core Loop Inside Every Framework

Many teams build agents with a framework such as LangGraph, CrewAI, LlamaIndex, the OpenAI Agents SDK or the Claude Agent SDK. These libraries come with ready-made connectors, but they also hide how the agent actually runs. When an agent repeats the same call again and again, makes up tool arguments or loses part of its context, a developer who knows only the framework's classes has a hard time finding the cause.

At the core of most agent frameworks is the same model-call and tool-dispatch loop, and that core fits in about sixty lines of standard Python. Frameworks add persistence, checkpointing, streaming, interrupts, concurrency and tracing around it; those parts are real work, and later skills (stateful agent graphs, human-in-the-loop) cover them. Knowing the core loop tells you what every one of those features is wrapped around.

The loop goes through the same four phases on every turn:

  1. Prompt assembly and model call. The client sends the current conversation history and the tool catalogue to the model endpoint. The model generates its reply from that whole transcript.

  2. Decision inspection. The client inspects the returned assistant message. If msg.tool_calls is empty, the model has decided that the goal is met; the loop ends and returns the final answer in natural language.

  3. Action dispatch. If msg.tool_calls is populated, the client records the assistant message in the transcript, extracts each tool name and its arguments, and runs the matching local Python function. When the model asks for several calls in one turn (parallel tool calls), the client runs every one of them; this loop runs them one after another.

  4. Observation feedback. The client turns each return value into a message with role: "tool", pairs it with the tool_call_id it answers, appends it to the transcript, and starts the next turn.

Once you know this four-phase cycle, you can see every message your agent sends, debug a misrouted tool call, and add your own policies (approvals, limits, logging) at a place you choose, instead of searching for the right hook in a framework.

02. Worked Example: The Complete Framework-Free Agent Loop in Python

Examine the complete agent loop below. It uses only the official openai Python SDK (checked with 3.51.0, pip install "openai>=3,<4") and the standard library, with no agent framework. It defines the two tool schemas it sends (TOOLS) and has an entry point, so with OPENAI_API_KEY and OPENAI_MODEL set (for example OPENAI_MODEL=gpt-6-luna) you can run it with python agent/core_loop.py. It is a teaching core, not a production service: it has no tracing, retries or persistence yet.

The loop uses the Chat Completions API because its message list is the easiest shape to read. On current OpenAI models, Chat Completions supports tool calls only with reasoning turned off, hence reasoning_effort="none" in the call. That works with the default gpt-6-luna. The current top models, GPT-6.2 Astra and GPT-6.2 Sol (released on 17 November 2026), reject any request that sets reasoning effort to none, so this call fails with them; use the Responses API instead. OpenAI recommends the Responses API for new agent code. Its loop has the same four phases: calls arrive as function_call items and results go back as function_call_output items.

Notice how the loop appends every message to one history list, stops after max_turns, dispatches each tool call through a handler mapping, and turns tool errors into ordinary tool results.

Look closely at the dispatch dictionary TOOL_REGISTRY. It maps each tool name the model may use to a Python callable, so the loop itself never needs to know what a tool does. The arguments arrive as a JSON string. The loop parses them with json.loads and passes the resulting dict to the handler, which unpacks it into keyword arguments. Nothing checks the dict against the schema, so a missing or unexpected argument fails inside the handler with a TypeError. Two branches handle failures. An unknown tool name is caught by the if not handler: check. The try/except catches malformed JSON and any exception a handler raises. Both write the error as a normal tool result and hand control back to the model.

This keeps a failing tool from crashing the loop: the model sees the error and can try something else. Errors outside the tool handlers (a network failure on the model call, an exhausted turn budget) still raise, and they should, because the caller has to decide what to do with them. The same goes for a reply that stopped early: when finish_reason is length (the output limit cut the reply) or content_filter, the message or its tool arguments may be incomplete, so the loop raises instead of treating it as a final answer.

Python · agent/core_loop.py
import json
import os
from typing import Any, Callable, Dict, List
from openai import OpenAI

MODEL = os.environ["OPENAI_MODEL"]  # for example gpt-6-luna

# Tool handlers
def add(a: float, b: float) -> float:
    return a + b

def search_kb(query: str) -> str:
    return "Knowledge base entry: The enterprise server port is 8443."

TOOL_REGISTRY: Dict[str, Callable[..., Any]] = {
    "add": lambda kwargs: add(**kwargs),
    "search_kb": lambda kwargs: search_kb(**kwargs),
}

# JSON schemas sent to the model, one per handler above
TOOLS: List[Dict[str, Any]] = [
    {"type": "function", "function": {
        "name": "add", "description": "Add two numbers.",
        "parameters": {"type": "object", "required": ["a", "b"],
            "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}}},
    {"type": "function", "function": {
        "name": "search_kb", "description": "Search the internal knowledge base.",
        "parameters": {"type": "object", "required": ["query"],
            "properties": {"query": {"type": "string"}}}}},
]

def run_agent_loop(
    client: OpenAI,
    task: str,
    tools: List[Dict[str, Any]],
    max_turns: int = 10,
) -> str:
    messages: List[Dict[str, Any]] = [
        {"role": "system", "content": "You are a concise agent with tools."},
        {"role": "user", "content": task},
    ]
    
    for turn in range(1, max_turns + 1):
        # Phase 1: Call foundation model with conversation history
        response = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=tools,
            reasoning_effort="none",  # Chat Completions tool calls need it
        )
        choice = response.choices[0]
        if choice.finish_reason in ("length", "content_filter"):
            raise RuntimeError(f"Model stopped early: {choice.finish_reason}")
        msg = choice.message
        # CRITICAL: record the assistant turn (with its tool calls) first
        messages.append(msg.model_dump(exclude_none=True))
        
        # Phase 2: Check for termination condition
        if not msg.tool_calls:
            return msg.content or "Task completed without output."
        
        # Phase 3 & 4: Dispatch actions and append observations
        for call in msg.tool_calls:
            func_name = call.function.name
            try:
                args = json.loads(call.function.arguments)
                handler = TOOL_REGISTRY.get(func_name)
                if not handler:
                    output = f"Error: Tool '{func_name}' is not registered."
                else:
                    output = str(handler(args))
            except Exception as exc:
                output = f"Execution error in '{func_name}': {exc}"
            
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": output,
            })
    
    raise RuntimeError(f"Agent exceeded maximum turn budget of {max_turns}")


if __name__ == "__main__":
    question = "What is 2 + 3, and which port does the enterprise server use?"
    print(run_agent_loop(OpenAI(), question, TOOLS))

03. What a Hand-Written Loop Gives You

Looking at this sixty-line implementation shows what a hand-written loop gives you:

  • Plain debugging. When an action fails, you can place a standard Python breakpoint (breakpoint()) directly inside the for loop. You can inspect the exact list of messages sent over the wire, the token counts in response.usage and the tool arguments, without stepping through framework middleware classes.

  • Explicit error boundaries. Exceptions raised inside tool handlers are caught and converted into string outputs ("Execution error in..."). A failing tool therefore does not crash the process, and the model can correct itself on the next turn.

  • Hard resource limits. The max_turns limit is a hard stop that the model cannot talk its way past. If the model gets caught in a circular loop, execution stops after max_turns model calls, so the cost of a stuck run has an upper bound.

  • Room to extend. From this sixty-line foundation, you can add tracing spans, token budget counters and human-in-the-loop approval hooks where you can see them; each is real work (later skills cover them), but none needs a framework.

  • Visible context pruning. In long-running conversations, the messages list keeps growing. With a raw loop you can compact it directly, for example by replacing old tool payloads with short summaries. Keep each role: "tool" message together with the assistant message that requested it: a plain slice that cuts between them produces the HTTP 400 error described above.

  • Contained provider migration. This loop is written against the OpenAI Chat Completions shape: tool_calls on the assistant message, function.arguments as a JSON string, and results sent back as role: "tool" messages. Other APIs differ. Anthropic's Messages API returns tool_use content blocks with an input object, signals a tool turn with stop_reason == "tool_use", expects results as tool_result blocks inside a user message, and declares tools with input_schema. Its content is a list of blocks that can start with a thinking block, so read the answer from the blocks whose type is "text", never from content[0], and send the assistant's blocks back unchanged, thinking blocks included, before the tool results. It also has its own stop reasons: besides end_turn and tool_use, handle max_tokens (the reply was cut off), refusal (the model declined) and pause_turn (a server-side tool paused a long turn: send the reply back to let it continue). Because the loop owns the message list, migrating is still a contained change: you rewrite the call, how tool calls and text are read, how results and thinking blocks are appended, how each stop reason is handled, and the tool schema format. Keep those parts in one adapter function and the rest of the loop stays the same. OpenAI-compatible servers such as vLLM accept this shape with fewer changes, and moving to OpenAI's own Responses API is the same kind of adapter change.

04. Practice questions

Practice check · 3 questions

Hand-crafted agent loop mechanics check

Three scenario-based questions evaluating loop state management, message sequence invariants, and framework-free architecture.

Q1. In Chat Completions, what is `call.function.arguments`, and what does the loop do with it before it calls a handler?
Q2. You port the loop from OpenAI Chat Completions to Anthropic's Messages API. Which change is needed besides the client call?
Q3. The loop reaches `max_turns` while the model is still requesting tools. What should happen, as in this lesson's code?
Practice only: not graded, not saved, not evidence.

05. Apply it

Use these loop patterns in your own systems:

  • Write your first agent with a plain loop like this one before you adopt a framework, so you know what the framework does for you.
  • Append msg to messages as soon as it arrives, before any tool result, so every tool message answers a call the API has seen.
  • Wrap each handler call in try/except, so an exception becomes a tool result the model can read instead of crashing the loop.
  • Set a conservative max_turns cap (for example 5 to 10) that fits the expected complexity of the task.
  • Log each turn, each tool call with its arguments, and the size of each tool result, so you can replay what happened.

06. Review prompt

Walk through the four phases of a minimalist agent execution loop. Explain why omitting the assistant message before appending tool results causes fatal API errors, and describe how setting explicit turn limits protects systems from runaway failures. Finally, name one thing a hand-written loop makes easier to see or debug, and one thing a framework adds that this loop does not have.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check