Zum Inhalt springen

Understanding the Agent Loop

Knowledge

Your agent is now configured: system prompt, model, tools, and MCP integration are all in place. But how does it actually work? In this section, you'll observe the agent loop in action -- the cycle of thinking, acting, and observing that you know from Module 04 as the ReAct pattern.

ReAct in Practice

Remember: An agent doesn't work linearly like a chatbot. It runs through a loop:

  1. Think: The agent analyzes the task and plans the next step
  2. Act: The agent calls a tool -- e.g., reading a file or running a search
  3. Observe: The agent evaluates the result of the tool call
  4. Repeat: Back to Think -- until the task is done

The Loop in Code

Here's what the agent loop looks like as a Python implementation:

import anthropic

client = anthropic.Anthropic()

def agent_loop(task: str, tools: list, system_prompt: str):
    messages = [{"role": "user", "content": task}]

    while True:
        # THINK: Agent analyzes and decides
        response = client.messages.create(
            model="claude-sonnet-5",
            max_tokens=4096,
            system=system_prompt,
            tools=tools,
            messages=messages
        )

        # Check if the agent is done
        if response.stop_reason == "end_turn":
            # Agent has given its final answer
            return extract_text(response)

        # ACT: Agent wants to call a tool
        if response.stop_reason == "tool_use":
            tool_calls = [
                block for block in response.content
                if block.type == "tool_use"
            ]

            # Collect tool results
            tool_results = []
            for call in tool_calls:
                # OBSERVE: Execute tool and get result
                result = execute_tool(call.name, call.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": call.id,
                    "content": result
                })

            # Continue the conversation
            messages.append({"role": "assistant", "content": response.content})
            messages.append({"role": "user", "content": tool_results})

        # Safety cutoff after 20 iterations
        if len(messages) > 40:
            return "Agent loop aborted: Too many iterations."

Why the Safety Cutoff Matters

Without a limit, an agent can get stuck in an infinite loop -- for example, if it keeps calling a tool repeatedly without properly interpreting the result. This costs not only time but also money (every iteration consumes tokens). A limit of 10-20 iterations is a good starting point.

Understand

Try It Out: The Agent Playground

In the following playground, you can walk through predefined scenarios and observe how an agent thinks, acts, and observes. Click through step by step and notice how each phase builds on the previous one.

Task

Find the current Bitcoin price

Press Start or Space to start the agent loop.

What to Watch For

As you walk through the scenarios, pay attention to three things:

  1. Planning before action: The agent always thinks before calling a tool. It doesn't jump in blindly.
  2. Contextual observation: After each tool call, the agent interprets the result in the context of the task -- it doesn't just read, it understands.
  3. Convergence: With each step, the agent gets closer to the solution. Good agents need few iterations.

Apply

An agent calls the same tool five times in a row without making progress. What is the most likely cause?

Reflect

The agent loop is the heart of every agent. The better you understand how Think, Act, and Observe work together, the better you can debug and optimize agents. The most common problem in practice isn't bad models -- it's unclear tool descriptions and missing guardrails.