How to Build an AI Agent: A Minimal Tool Loop
Build a minimal AI agent in Python with a tool-use loop, check that it works, and find where it breaks, using Claude's Messages API docs as of 2026-11-21.
Updated · Markdown version
An AI agent is a loop: the model requests a tool, your code runs it, the result goes back to the model, and the cycle repeats until the model replies with text instead of another tool request. You can build the smallest working version in one Python file with the Messages API, then add the limits that stop it from running indefinitely.
Build the smallest loop
- Create a client with
anthropic.Anthropic(), as the SDK examples in Anthropic's tool use docs do. - Describe each tool with a
name, adescription, and aninput_schema(a JSON Schema object). Claude reads the description to decide whether a request needs the tool. - Send
tools=andmessages=in amessages.createcall. - Append
response.contenttomessagesas the assistant turn. Keep thetool_useblocks as returned; rebuilding them from text breaks the ids. - If
response.stop_reasonis"tool_use", run eachtool_useblock and build atool_resultblock withtool_use_idset to that block'sid. Send all results in one user message. - Repeat until the stop reason is anything else, with a hard cap on iterations.
import anthropic
client = anthropic.Anthropic()
MODEL = "<current-model-id>" # check the Claude docs for current IDs
MAX_STEPS = 5
tools = [{
"name": "get_weather",
"description": "Get the current weather for a given location.",
"input_schema": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
}]
def run_tool(name, args):
if name == "get_weather":
return "15 degrees Celsius, partly cloudy" # replace with a real lookup
return f"Unknown tool: {name}"
messages = [{"role": "user", "content": "What's the weather in San Francisco?"}]
for _ in range(MAX_STEPS):
response = client.messages.create(
model=MODEL, max_tokens=1024, tools=tools, messages=messages
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break
results = [
{"type": "tool_result", "tool_use_id": block.id,
"content": run_tool(block.name, block.input)}
for block in response.content if block.type == "tool_use"
]
messages.append({"role": "user", "content": results})
print(response.content[-1].text if response.content[-1].type == "text" else response.content)Check that it worked. Run the script as written. You should see one get_weather call and a text answer that uses the stub result. Then change the prompt to a question no tool covers, such as arithmetic. The model should answer without requesting a tool. If it does not, the tool description is probably too broad.
Pitfalls
- Missing or mismatched ids. A
tool_resultwith the wrongtool_use_idfails the next request. Passblock.idthrough unchanged. - Runaway loops. A model that keeps requesting tools never reaches a text reply. The
MAX_STEPScap is the guard; Anthropic's guidance also recommends stopping conditions for this reason. - Parallel calls you did not plan for. A single response can contain several
tool_useblocks. The loop above answers all of them. If your tools must run one at a time, setdisable_parallel_tool_useintool_choice. - Silent tool failures. If
run_toolraises an exception and you do not return it as a result, the loop stops with no explanation. Catch errors and return them as tool output so the model can react. - Cost growth. Each turn resends the full history, including tool definitions and results. A long tool output repeated across many turns costs input tokens every time. Truncate large results before returning them.
When to use a skill instead
A one-off agent can live in a single script like the one above. A reusable skill fits better when the same procedure, such as checking a tool's output format or following a fixed set of steps, has to run across many sessions. subagent-design helps when part of the work should go to a separate agent, since it covers what to delegate and how to write the brief. llm-eval-test-sets builds the test cases that show whether a change to the loop, its prompts or its tool descriptions made results worse. Ad-hoc prompting is enough for a single tool and a single task.
FAQ
How do I build an AI agent? Start with the loop: send tools with a request, run any tool_use block the response contains, return a tool_result, and repeat with a cap on iterations. Test with one tool before you add more.
How do I build skills for an AI agent? A skill packages a repeatable procedure; the loop itself does not need one. Write a skill when the same steps recur across tasks, and keep the loop code separate so the skill can change without touching it.
Does an agent need a skill to call tools? No. Tool calls depend only on the tool definitions you pass to the API. A skill helps with repeated procedures and is optional for a working agent.
Related skills in this catalog
Platform Score is our assessment under a published method. It is not a safety guarantee.
Related guides
Terms this guide uses
This item is a worked example in the AI glossary for:
- Agent evaluation
- AI agent
- AI agent builder
- AI agent framework
- AI automation
- AI voice agent
- AI workflow
- Amazon Bedrock
- AutoGen (Microsoft)
- AutoGPT
- Azure AI Foundry (Microsoft Foundry)
- Chainlit
- Claude Agent SDK
- CrewAI
- Dify
- GAIA benchmark
- Kubeflow
- LangChain
- Langflow
- Langfuse
- LangGraph
- LangSmith
- LlamaIndex
- LLMOps
- Microsoft Copilot Studio
- Monte Carlo tree search (MCTS)
- n8n
- OpenAI Agents SDK
- PydanticAI
- Rate limit
- ReAct prompting
- Semantic Kernel
- smolagents
- Weights & Biases (W&B)
Sources
- https://www.anthropic.com/engineering/building-effective-agents (accessed 2026-11-21)
- https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview (accessed 2026-11-21)
This page is not offered to search engines yet: The content file does not mark this page indexable yet.