Solution Patterns & Playbooks

Agentic Loops with Tool Use: Building Reliable Autonomous Workers

An agent is just a loop: the model requests a tool, your code runs it, the result goes back, repeat until done. Reliability comes from what you build around that loop.

Claude 3P 101 · Updated July 2026 · Unofficial guide

Strip away the hype and an "AI agent" is a small, well-documented protocol. You send a request with tool definitions; if Claude wants to act, the response has stop_reason: "tool_use" and one or more tool_use blocks; your application executes the tools and sends back tool_result blocks; the loop repeats until Claude answers in plain text. Everything outside that protocol — sandboxing, validation, stopping conditions, audit — is yours to build, and it's what separates a reliable worker from an expensive random walk. This pattern covers the loop skeleton and its four reliability layers. Core tool use is GA on all five surfaces (first-party Claude API, Claude Platform on AWS, Amazon Bedrock, Google Vertex AI, and Microsoft Foundry), making this the most portable agent architecture available.

The loop skeleton

from anthropic import AnthropicFoundry

client = AnthropicFoundry(api_key="...", resource="my-resource")
messages = [{"role": "user", "content": task}]
for _ in range(MAX_TURNS):                      # hard iteration cap
    resp = client.messages.create(model="claude-opus-4-8", max_tokens=4096,
                                  tools=TOOLS, messages=messages)
    messages.append({"role": "assistant", "content": resp.content})
    if resp.stop_reason != "tool_use":
        break                                   # agent is done
    results = [run_tool(b) for b in resp.content if b.type == "tool_use"]
    messages.append({"role": "user", "content": results})

Three documented details make this skeleton correct. Claude may request multiple tool calls in one response — return all results in a single user message. Failed executions go back as a tool_result with "is_error": true and an informative message, so the agent can adapt instead of stalling. And if you use server-side tools (web search, code execution — available on the Claude API and Claude Platform on AWS, beta on Foundry, not on Bedrock or Vertex AI), the server runs its own sampling loop with a default limit of 10 iterations; hitting it returns stop_reason: "pause_turn", and you simply re-send the conversation for the server to resume.

Tool schemas are the steering wheel

Each custom tool is a name, description, and JSON Schema input_schema — and the description is prompt engineering: say what the tool does, when to use it, and when not to. Add strict: true to guarantee calls match the schema exactly (strict tool use is GA on the Claude API, Claude Platform on AWS, Bedrock, and Vertex AI; beta on Foundry), which eliminates malformed-argument handling from your executor. tool_choice tunes the loop's freedom: auto (default), any (must use some tool), a specific tool, or none; any of these can add disable_parallel_tool_use: true if your executor can't handle concurrent calls. Keep the toolset small — official guidance notes selection accuracy degrades past 30–50 loaded tools, and the tool search tool exists for genuinely large catalogs.

Validation and sandboxing: treat outputs as untrusted

Everything the model emits is untrusted input to your systems. The documented security guidance for the bash tool is the template for any powerful tool: run commands in an isolated environment, use an allowlist of executables (a blocklist is not sufficient), set timeouts and resource limits, and log every command. The text editor tool's guidance is analogous — canonicalize model-supplied paths and confine operations to a fixed root, rejecting traversal. Generalize the principle: every tool executor validates its arguments against business rules the schema can't express, and every side-effecting tool is idempotent or checked before execution. For agents processing external content (web pages, inbound email), remember that content is a prompt-injection surface — see prompt injection 101 — so gate consequential actions on human approval, as in the escalation pattern.

Stopping conditions: never trust the loop to end itself

The model signals completion by not requesting tools, but production loops need independent brakes: a hard iteration cap (the MAX_TURNS above), a token/cost budget summed from each response's usage fields, a wall-clock deadline, and a no-progress detector (identical tool call twice in a row is the classic tell). On long runs, context management keeps the loop from drowning in its own history: the memory tool (GA; {"type": "memory_20250818", "name": "memory"}) gives the agent durable notes, and the docs pair it with context editing — which clears old tool results past a token trigger — and compaction for exactly this long-horizon case. See the memory pattern for details.

Build or buy the harness: everything above is you building the agent harness. Anthropic's Managed Agents offers the harness pre-built — managed sessions, containers, permission gates — but it's beta and only on the first-party Claude API and Claude Platform on AWS, not Bedrock, Vertex AI, or Foundry. On Bedrock or Vertex, the self-built loop in this article is the supported path.

Where to go next

Fixed multi-step processes are better served by workflow orchestration — save agentic loops for tasks where the path genuinely can't be predetermined. The feature matrix shows which tools run where.

Sources