Method·8 min read·4 July 2026

Claude Agent Tutorial: Build Reliable Agentic Loops

This claude agent tutorial walks through agentic loop design, tool integration, context management, and human handoff patterns for production-grade Claude agents.

By Solomon Udoh · AI Architect & Certification Lead

Claude Agent Tutorial: Build Reliable Agentic Loops

This claude agent tutorial is for engineers who want working code and principled design, not framework hype. We cover the agentic loop mechanics, tool integration, context management, and the human-oversight patterns that the CCA-F exam tests directly. Domain 1 (Agentic Architecture and Orchestration) carries 27% of the exam weight, the single largest slice, so getting these fundamentals right matters both in production and on the day.

What exactly is a Claude agent?

A Claude agent is a process in which the model drives its own next action by reading tool results, deciding what to do next, and calling tools again until a stopping condition is met. The loop is not magic: it is a while loop in your code that keeps calling the Messages API until stop_reason equals "end_turn" or your own guard fires.

The minimal anatomy is:

  1. A system prompt that defines the agent's goal and constraints.
  2. A set of tools the model may call.
  3. A host process that appends tool results and re-calls the API.
  4. A termination condition that is explicit, not assumed.

That last point is where most first implementations fail. We cover agentic loop anti-patterns in depth elsewhere; here we build the correct version from the start.

How does the agentic loop work in code?

The loop centres on inspecting stop_reason after every API call. When the value is "tool_use", you execute the requested tool and append the result. When it is "end_turn", you exit. Anything else is an error path.

python
import anthropic
import json
client = anthropic.Anthropic()
def run_agent(system: str, tools: list[dict], initial_message: str) -> str:
messages = [{"role": "user", "content": initial_message}]
max_iterations = 20 # hard guard against runaway loops
for _ in range(max_iterations):
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
system=system,
tools=tools,
messages=messages,
)
# Append the assistant turn
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "end_turn":
# Extract the final text block
for block in response.content:
if block.type == "text":
return block.text
return ""
if response.stop_reason != "tool_use":
raise RuntimeError(f"Unexpected stop_reason: {response.stop_reason}")
# Execute every tool call in this turn
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = dispatch_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result),
})
messages.append({"role": "user", "content": tool_results})
raise RuntimeError("Agent exceeded max_iterations without reaching end_turn")

The max_iterations guard is non-negotiable. Without it, a confused model can loop indefinitely, burning tokens and potentially taking unintended actions. Per Anthropic's guidance on agentic systems, prefer minimal footprint: request only necessary permissions and err on the side of doing less when uncertain.

Prefer reversible over irreversible actions, and err on the side of doing less and confirming with users when uncertain about intended scope in order to preserve human oversight and avoid making hard-to-fix mistakes.

Anthropic , Claude Documentation: Building with Claude

Understanding stop_reason field inspection and tool result appending are two of the 30 task statements the CCA-F exam tests. The code above encodes both correctly.

How do you design tools that agents actually use correctly?

Tool descriptions are the primary selection mechanism. The model reads your description, not your implementation. A vague description produces misrouting; a precise one produces correct calls on the first attempt.

A minimal but effective tool definition looks like this:

json
{
"name": "search_knowledge_base",
"description": "Full-text search over the internal product knowledge base. Use this when the user asks about product features, pricing, or support policies. Do NOT use for general web search or code execution.",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query, written as a natural-language question."
},
"max_results": {
"type": "integer",
"description": "Maximum number of results to return. Default 5, max 20.",
"default": 5
}
},
"required": ["query"]
}
}

Three rules that pay off immediately:

  1. State what the tool is for. Lead with the use-case, not the implementation.
  2. State what it is NOT for. Explicit exclusions prevent the model from reaching for the wrong tool when two tools overlap.
  3. Constrain the schema tightly. Enums, min/max values, and required fields reduce hallucinated inputs.

When you have too many tools in a single context, the model's accuracy drops. The tool overload problem is real: empirically, performance degrades as the available tool count grows. Scope tools to roles, not to the entire agent surface.

Tool design mistakeConsequenceFix
Vague descriptionModel picks the wrong toolAdd use-case and exclusion clauses
Overlapping namesInconsistent routingSplit into narrower, named tools
Too many tools in one contextAccuracy degradesScope tools per subagent role
No schema constraintsHallucinated inputsAdd enums, required fields, min/max
Missing error semanticsSilent failuresReturn structured error with isError flag

How should you manage context in a long-running agent?

Context is the resource most engineers underestimate. Every tool result you append grows the context window. After enough turns, two problems emerge: cost rises linearly, and the model's effective attention on early content weakens (the attention dilution problem).

The practical strategies, in order of preference:

1. Trim tool results before appending. If a tool returns 10,000 tokens of raw data and the agent needs three fields, extract those fields in your dispatch_tool function before appending. Never pass raw API responses verbatim.

2. Use summary injection for fresh sessions. When a task spans multiple sessions, end each session by asking the model to produce a structured summary, then inject that summary as the first user message of the next session. This is the summary injection for fresh sessions pattern.

python
SUMMARY_PROMPT = """
Before we end this session, produce a JSON summary of:
- completed_steps: list of actions taken and their outcomes
- pending_steps: list of steps not yet completed
- key_findings: facts discovered that the next session will need
- open_questions: anything that needs human clarification
Respond with only the JSON object, no prose.
"""

3. Fork sessions for divergent exploration. When the agent needs to explore two incompatible hypotheses, fork the conversation rather than letting both branches pollute a single context. See fork_session for divergent exploration for the mechanics.

4. Set a context budget and monitor it. Track usage.input_tokens in every response. When you approach 80% of the model's context limit, trigger a compaction step rather than waiting for a context error.

python
CONTEXT_BUDGET = 180_000 # tokens, for claude-opus-4-5
def should_compact(response) -> bool:
return response.usage.input_tokens > CONTEXT_BUDGET * 0.8

When should a human step in?

Autonomous agents are not appropriate for every action. The CCA-F exam consistently rewards answers that apply proportionate human oversight: more autonomy for reversible, low-stakes actions; mandatory human approval for irreversible or high-stakes ones.

The structured handoff to human agents pattern formalises this. Rather than silently failing or guessing, the agent produces a structured handoff object and pauses.

python
HANDOFF_SCHEMA = {
"type": "object",
"properties": {
"reason": {"type": "string"},
"action_proposed": {"type": "string"},
"reversible": {"type": "boolean"},
"data_needed_from_human": {"type": "array", "items": {"type": "string"}},
"urgency": {"type": "string", "enum": ["low", "medium", "high"]}
},
"required": ["reason", "action_proposed", "reversible", "data_needed_from_human"]
}

Three triggers that should always pause the agent and surface a handoff:

  1. The proposed action is irreversible (deleting records, sending external communications, deploying to production).
  2. The agent has reached a decision point not covered by its instructions.
  3. Confidence in the next action is low and the cost of a wrong action is high.

Two triggers that are tempting but unreliable: the model "feeling uncertain" (models can be confidently wrong) and elapsed time (time alone does not indicate a problem). Root the decision in action type and stakes, not in model-reported confidence.

How do you structure a multi-agent system?

Single agents handle single-concern tasks well. When a task has multiple concerns, a hub-and-spoke architecture separates coordination from execution cleanly.

Loading diagram...

The coordinator receives the user request, decomposes it into subtasks, dispatches subagents, and synthesises results. Each subagent receives only the context it needs (subagent context isolation keeps costs down and reduces cross-contamination of reasoning).

The coordinator's system prompt should be goal-based, not step-based. Tell it what a good outcome looks like, not which subagents to call in which order. Goal-based vs step-based prompts is a tested concept: step-based prompts break when the environment deviates from the assumed sequence; goal-based prompts adapt.

As of 3 June 2026, more than 10,000 individuals have earned the CCA-F certification, and Domain 1 (which covers all of the above) carries the highest exam weight at 27%. Investing time in these patterns pays off both in production systems and on the exam.

What does a production-ready agent checklist look like?

Before shipping any agent to production, verify each of the following:

CheckWhy it mattersExam domain
Hard iteration cap in the loopPrevents runaway cost and unintended actionsDomain 1 (27%)
stop_reason inspection on every turnCatches unexpected terminations earlyDomain 1 (27%)
Tool results trimmed before appendingControls context growthDomain 5 (15%)
Structured error returns from all toolsEnables graceful recoveryDomain 2 (18%)
Human handoff for irreversible actionsPreserves oversightDomain 1 (27%)
Context budget monitoringPrevents silent context overflowDomain 5 (15%)
Goal-based coordinator promptResilience to environmental deviationDomain 4 (20%)
Subagent context isolationCost control and reasoning clarityDomain 1 (27%)

In agentic contexts, Claude must apply particularly careful judgment about when to proceed versus when to pause and verify with the operator or user, since mistakes may be difficult to reverse, and could have downstream consequences within the same pipeline.

Anthropic , Claude Documentation: Agentic and tool use

Our concept library at /concepts maps all 174 atomic concepts to the five exam domains and 30 task statements. If any of the patterns above feel unfamiliar, that is the right place to drill before sitting the CCA-F.

Where do you go from here?

The patterns in this tutorial cover the core of Domain 1 and touch Domains 2, 4, and 5. The next logical steps are:

The CCA-F exam launched on 12 March 2026 and costs $99 per attempt. It is scored on a 100-to-1000 scale with a passing mark of 720. The patterns in this tutorial are not exam trivia: they are the engineering decisions the exam's scenario-based questions are designed to probe.

Frequently asked questions

How do I stop a Claude agent from running forever?
Set a hard iteration cap in your agentic loop before you call the API for the first time. A limit of 20 to 50 iterations is typical for most tasks. Also inspect stop_reason on every response: only continue the loop when the value is 'tool_use'. Any other value should either exit cleanly or raise an error, never silently continue.
What model should I use for a Claude agent?
For complex multi-step reasoning and tool use, claude-opus-4-5 offers the strongest instruction-following and tool-call accuracy. For high-volume, lower-complexity agentic tasks where cost matters, claude-haiku-3-5 is significantly cheaper per token. Match the model to the task complexity and your cost budget rather than defaulting to the largest model for everything.
How many tools can I give a Claude agent before performance drops?
Anthropic's documentation does not publish a hard number, but the tool overload problem is well-documented: as the available tool count in a single context grows, routing accuracy degrades. In practice, keep any single agent or subagent to fewer than 10 to 15 tools. Use a hub-and-spoke architecture to distribute tools across specialised subagents when you need a larger surface area.
Do I need a framework like LangChain or AutoGen to build a Claude agent?
No. The agentic loop is a while loop around the Anthropic Messages API. Frameworks add abstraction that can obscure what the model is actually receiving and doing. For most production use cases, a direct API integration with explicit stop_reason inspection and tool dispatch gives you more control, better observability, and fewer unexpected behaviours than a framework layer.
How do I pass context between agent sessions without hitting the context limit?
At the end of each session, prompt the model to produce a structured JSON summary covering completed steps, pending steps, key findings, and open questions. Store that summary and inject it as the first user message of the next session. This summary injection pattern keeps each session's input token count bounded regardless of how many prior sessions have occurred.
Does building Claude agents help with the CCA-F exam?
Yes, directly. Domain 1 (Agentic Architecture and Orchestration) carries 27% of the CCA-F exam weight, the largest single domain. The exam uses scenario-based questions that test whether you can identify correct loop design, appropriate human handoff triggers, and proportionate tool use. Hands-on agent building is the most effective preparation for those scenarios.

People also ask

How do Claude agents work?
Claude agents work by repeatedly calling the Messages API, inspecting the stop_reason field, executing any requested tool calls, appending the results to the conversation, and calling the API again. The loop continues until stop_reason equals 'end_turn' or a host-defined guard condition fires. The model drives its own next action; the host process executes tools and manages state.
What is the difference between a Claude agent and a Claude chatbot?
A chatbot completes one response per user turn. An agent runs an autonomous loop: it calls tools, reads results, decides the next action, and repeats until a goal is met or a stopping condition fires. Agents can take dozens of actions across multiple tool calls before returning a final answer, whereas a chatbot responds once and waits.
How do I give a Claude agent access to tools?
Pass a tools array in your Messages API request. Each tool has a name, a description, and a JSON schema for its inputs. The model selects tools based on the description text, not the implementation. When the model calls a tool, your host process executes it and appends the result as a tool_result content block before the next API call.
How do Claude agents handle errors?
Well-designed agents return structured error objects from tool calls rather than raising exceptions that crash the loop. The MCP isError flag pattern signals to the model that a tool call failed without terminating the session. The model can then decide whether to retry, try an alternative tool, or escalate to a human handoff, depending on its instructions.
Can Claude agents run without human supervision?
Partially. Claude agents can run autonomously for reversible, low-stakes actions within a well-defined scope. Irreversible actions, decisions outside the agent's instructions, and high-stakes choices should trigger a structured human handoff rather than autonomous execution. Anthropic's guidance explicitly recommends preferring reversible actions and pausing to verify when scope is uncertain.

About the author

Solomon Udoh

AI Architect & Certification Lead

Solomon Udoh is an AI Architect who designs and ships production agent systems on the Claude API and Claude Code. He built AI Skill Certs' adaptive engine and authored its 174-concept knowledge graph, mapping every Claude Certified Architect - Foundations objective to hands-on, exam-aligned practice.

  • Designs production multi-agent systems on the Claude API and Agent SDK
  • Author of the AI Skill Certs knowledge graph (174 mapped exam concepts)
  • Builds with MCP, Claude Code, structured outputs, and agentic loops daily
  • Reviews every concept page against the official Anthropic exam guide

You might also like

Ready to put it into practice?

Study every exam concept with an adaptive tutor.

Start studying