Skip to content
Streak:0Loading your progress…Sign in

Module 11 · Lesson 1 of 2

The agent loop

An agent is an LLM using tools in a loop until the task is done. ~30 min

Lesson notes

The whole idea, in pseudocode
messages = [{"role": "user", "content": task}]
for step in range(MAX_STEPS):
    response = llm(messages, tools)
    messages.append({"role": "assistant", "content": response.content})
    if response.stop_reason != "tool_use":
        return response            # done
    results = run_tools(response.tool_uses)
    messages.append({"role": "user", "content": results})   # ALL results, one message
raise StepLimitExceeded()

Start simple. Most production "agents" should be workflows: code decides the steps (classify → retrieve → draft → check), and the LLM fills in each step. Use an autonomous agent only when the steps genuinely can't be known in advance — and then bound it: step limits, token/cost budgets, timeouts, and narrow tools.

Practice

  1. 1. Implement an agent loop

    hard50 XP

    Write run_agent(llm, tools, task, max_steps=5) -> (final_text, messages). llm(messages) returns {"stop_reason": str, "content": [blocks]} where blocks are {"type": "text", "text"} or {"type": "tool_use", "id", "name", "input"}. tools maps name → function(input) -> str. Loop: append the assistant content; if stop_reason is "tool_use", run every tool_use block (unknown tool or exception → is_error: True result) and append one user message containing all tool_result blocks; otherwise return the concatenated text blocks. Raise RuntimeError("step limit") after max_steps LLM calls without finishing.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor