AI agent development means building software in which a language model works in a loop: it reads a goal, chooses a tool to call (an API, a database query, a search), looks at the result and decides the next step, until the task is done or your code stops it. The model is the easy part. Most of the work is designing a few narrow tools, limiting what the agent may do without a person, and testing it on real cases before it touches production.
Before you build one, check whether a fixed workflow with a single model call would do the job. It usually costs less, and when it fails, it fails in ways you can predict.
In practice the work runs in this order:
- Pick one task and decide whether it needs an agent at all, or whether a fixed workflow will do.
- Collect a few dozen real cases from that task, with the correct outcome written down for each. These cases become your test set and your definition of done.
- Design a few narrow tools, and decide which actions need a person's approval.
- Write the loop yourself or pick a framework, with a hard step limit and a log of every call from the first day.
- Run the test set after every change to the prompt, the tools or the model.
- Roll out in stages, with the agent only proposing actions at first, and track the cost per task.
We're a small software team in Ankara. Where the advice below comes from our client projects (a document-extraction workflow, an exercise program generator, and data and AI work on a bookkeeping assistant), we say so; the rest comes from vendors' documentation.
Agent or workflow: decide this first
Anthropic's engineers draw the line clearly in Building effective agents. In a workflow, the model and tools follow code paths you wrote in advance. In an agent, the model decides its own steps and which tools to use. Their advice is to start with the simplest solution that works and add autonomy only when it pays for itself, because an agent buys flexibility with extra latency and cost. Microsoft's Agent Framework documentation is even blunter: if a plain function can handle the task, write the function.
Three questions usually settle it:
- Can you write the steps down? If the process is the same every time (read a document, extract fields, file it, notify someone), build a workflow. If the number and order of steps depend on what the system finds along the way, an agent starts to make sense.
- Is one task worth several model calls? An agent spends several calls on what a workflow does in one. That is fine for a support case that would take someone an hour and wasteful for tagging product photos.
- Can a mistake be caught and undone? Drafts, suggestions and read-only research are safe places to start. Payments, emails to customers and deletions need a person in the loop however good the model is.
The field-ticket automation we built with an automation partner for an oilfield services company is a good example of a job that people often picture as an agent and that works perfectly well as a workflow. Tickets arrive by Gmail. Every evening an n8n workflow picks up the day's PDFs, has an LLM extract the invoice fields into JSON, files each PDF with its JSON in dated Google Drive folders and emails the billing team a consolidated report. It has run every day since September 2025 and handles about 100 documents a day. The path never changes, so no step needs the model to decide what happens next. The case study has the details.
A common middle ground is a fixed workflow that passes only the odd cases to an agent with a few lookup tools. Most runs stay cheap and predictable, and you pay for the extra model calls only on the cases that need them.
How an agent works: the loop
Every agent framework wraps the same loop. Your code sends the model the conversation so far and a list of tools. The model either answers or asks for a tool call. Your code runs the tool, appends the result and calls the model again. It follows the ReAct idea from a 2022 paper (reason, act, observe the result, repeat), which the major model APIs now support directly as tool calling.
Here is that loop in plain Python with the Anthropic SDK, for a shop assistant that can look up orders and refund one. Other providers' SDKs have the same shape.
import json
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
MODEL = "claude-opus-5-5"
MAX_STEPS = 8 # hard stop, whatever the model wants
NEEDS_APPROVAL = {"refund_order"} # every write goes past a person
TOOLS = [
{
"name": "find_orders",
"description": "Read-only. Returns the customer's 10 most recent orders as "
"JSON (id, date, total, status). Call it before any refund.",
"input_schema": {
"type": "object",
"properties": {"email": {"type": "string"}},
"required": ["email"],
"additionalProperties": False,
},
"strict": True,
},
{
"name": "refund_order",
"description": "Refunds one delivered order in full. Fails for any other "
"status. A person approves every call.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}, "reason": {"type": "string"}},
"required": ["order_id", "reason"],
"additionalProperties": False,
},
"strict": True,
},
]
def run_agent(task, handlers, approve):
messages = [{"role": "user", "content": task}]
for step in range(MAX_STEPS):
response = client.messages.create(
model=MODEL, max_tokens=16000, tools=TOOLS, messages=messages,
system="You handle refund requests for an online shop. "
"Use the tools and never guess order details.",
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use": # done, refused or out of tokens
return next((b.text for b in response.content if b.type == "text"), "")
results = []
for call in [b for b in response.content if b.type == "tool_use"]:
print(f"step {step}: {call.name} {json.dumps(call.input)}") # keep this log
result = {"type": "tool_result", "tool_use_id": call.id}
if call.name in NEEDS_APPROVAL and not approve(call.name, call.input):
result |= {"content": "A person declined this action.", "is_error": True}
else:
try:
result["content"] = handlers[call.name](**call.input)
except Exception as exc: # let the model see the failure
result |= {"content": f"Error: {exc}", "is_error": True}
results.append(result)
messages.append({"role": "user", "content": results})
raise RuntimeError(f"No answer after {MAX_STEPS} steps; hand it to a person.")You call it with your own functions behind each tool (each returns a string) and a way to ask a person:
answer = run_agent(
"ayse@example.com says her last order arrived broken and wants her money back.",
handlers={"find_orders": find_orders, "refund_order": refund_order},
approve=lambda name, args: input(f"Allow {name} {args}? [y/N] ") == "y",
)The parts that matter here have little to do with intelligence:
MAX_STEPSis a hard stop. A model that keeps calling tools keeps spending money, and Anthropic's article recommends a maximum number of iterations for exactly this reason.- Writes go through
approve. The model can ask for a refund; a person decides. - Tool errors go back to the model as
is_errorresults instead of crashing the run, so it can try another route or explain the problem. - Every tool call is printed with its arguments. When a run goes wrong, this log is what you will read.
refund_orderrefunds in full and refuses orders that aren't delivered. The model can't choose a wrong amount because the tool doesn't accept one.
Frameworks add state persistence, retries, streaming, tracing and multi-agent orchestration on top of this. The loop underneath stays the same, so it's worth writing it by hand once before you choose one.
Tools are most of the work
The model knows only what your tool names, descriptions and schemas tell it. Anthropic suggests spending as much effort on tool definitions as on the prompt, testing tools with many example inputs, and shaping them so that mistakes are hard to make. In practice:
- Fewer, narrower tools.
refund_order(order_id)is safer and easier for the model to use thanrun_sql(query). OWASP lists excessive functionality, meaning tools that can do more than the task needs, as the first root cause of Excessive Agency, its entry on LLM systems that can be steered into damaging actions. - Descriptions a new colleague could follow: what the tool does, when to use it, what it returns and what it refuses. The rules for writing good prompts apply here too.
- Small, relevant results. Return the five fields the agent needs, not the whole customer record. The context stays short, and personal data stays out of places it doesn't need to be.
- Permissions enforced in the system behind the tool. Run the tool with the user's rights or a narrowly scoped service account, and let the backend reject what isn't allowed, whatever the model asks for. OWASP calls this complete mediation.
- Idempotent writes. If the agent retries a refund, the second call should change nothing.
When the same tools have to serve several agents or AI clients, put them behind a Model Context Protocol (MCP) server instead of hard-coding them into one app. MCP is now an open standard under the Linux Foundation, and most frameworks can use MCP tools directly. We're building one for a client's property-search platform at the moment, and our MCP post covers how a server is put together.
Choosing a framework in 2026
The framework matters less than the tools and limits around it, and Anthropic warns that heavy abstractions can hide the prompts and responses you need to see when debugging. With that said, these are the options teams compare today:
Option | What it is | A good fit when |
|---|---|---|
Provider SDK, your own loop | The code above, or the SDK's tool runner helper (in beta) | You have a handful of tools and want to see every request |
LangGraph | Graph-based, stateful agent runtime from the LangChain team; 1.0 since October 2025 | You need explicit branches, checkpoints and pauses for human review |
OpenAI Agents SDK | Lightweight Python framework for agents and handoffs between them; works with other providers' models through LiteLLM | You want little abstraction with tracing and handoffs included |
Claude Agent SDK | The Claude Code agent as a library, with file, shell and search tools built in | The agent works on files, code or a machine you give it |
Google ADK | Code-first framework, tuned for Gemini but model-agnostic | You're on Google Cloud or Gemini |
Microsoft Agent Framework | Python and .NET, with Go in preview; successor to AutoGen and Semantic Kernel | You're a .NET or Azure shop, or have AutoGen code to migrate |
CrewAI | Role-based "crews" of agents plus event-driven Flows; independent of LangChain | The task splits naturally into roles such as researcher and reviewer |
Pydantic AI | Typed Python agent framework with many model providers | You want type-checked inputs and outputs in a Python codebase |
If an article recommends AutoGen for a new project, it is out of date: Microsoft describes Agent Framework as the direct successor to both AutoGen and Semantic Kernel.
Whichever you choose, keep the model swappable. Two things from our client work show why. On the field-ticket workflow, what broke most often was the LLM API's rate limit (HTTP 429), and the fix was falling back to alternative models so that a document still gets processed. On Jenesys AI's bookkeeping assistant, custom models we built were later overtaken by frontier models. Put the model name in configuration rather than code, and run your test set against a second model now and then.
Security: plan for the agent being tricked
Any text the agent reads can carry instructions: a customer email, a PDF, a web page, a tool result. This is indirect prompt injection, and OWASP's entry on prompt injection says plainly that it is unclear whether a fool-proof prevention method exists. Filters and careful prompts lower the risk without removing it.
So design for the case where the model has been talked into something:
- Give each agent the smallest set of tools and permissions its task needs, read-only wherever possible.
- Keep secrets (API keys, tokens, passwords) out of the model's context. The tools hold the credentials; the model sees only results.
- Require a person's approval before anything that spends money, sends a message outside the company or deletes data.
- Mark untrusted content as untrusted in the prompt, and never let it change which tools are available.
- Be most careful with an agent that has access to private data, reads untrusted input and can send data out (email, web requests, uploads). If one agent truly needs all three, put a human approval on the outbound step.
Logging, monitoring and rate limits still belong in the design. OWASP's Excessive Agency entry is clear about their role: they limit the damage and show you that something happened, but they don't prevent the attack.
Testing before and after launch
Agents fail in ways a demo won't show you, so build a test set before you write much code. Collect a few dozen real cases from the process you're automating, write down what a correct outcome looks like for each, and run the agent against all of them after every change to the prompt, the tools or the model. Check the path along with the answer: an agent that gives the right reply after calling the refund tool on the wrong order has failed.
Real cases beat invented ones. Before the field-ticket workflow went live, we tested its extraction on real tickets for a month. For a sports physiotherapy clinic, we built a system in which an LLM drafts strength and rehab programs using retrieval over more than 1,800 exercise entries. Coaches rate the results with a thumbs up or down and can swap exercises for alternatives, and this year we're adding stored comparisons between the AI's programs and the coaches' own, so the logic can be checked against past athletes (case study).
After launch:
- Log every model call, tool call and tool result under a run ID, so you can replay a bad run step by step.
- Add checks on the output next to your error alerts. On Jenesys AI's assistant, our engineer built checks that raise an alert when key extracted fields (category, VAT rate, tracking category) come back empty, so they no longer pass silently.
- Treat the model's stated reasoning as a debugging hint. Current reasoning models often summarize or hide their reasoning, and a model's account of what it did is an unreliable record of why it acted. The tool calls and their results are the record.
Roll out in stages. Start in shadow mode: the agent proposes actions, people carry them out, and you compare the two. Then let the agent act with an approval on every write. Remove the approval only for actions that are low-risk and easy to undo, and keep it everywhere else.
What an agent costs to run
An agent is billed per token like any other LLM call, but it makes several calls per task, and each call resends the whole conversation so far. Cost therefore grows faster than the number of steps.
Here is a rough example with Claude Opus 5.5, which costs $4 per million input tokens and $20 per million output tokens according to Anthropic's pricing page. Assume 2,000 tokens of system prompt and tool definitions, six model calls, about 1,000 tokens added to the conversation per step, and 400 output tokens per call with reasoning included:
- Input: 2,000 + 3,000 + 4,000 + 5,000 + 6,000 + 7,000 = 27,000 tokens, about $0.108
- Output: 6 × 400 = 2,400 tokens, about $0.048
- Total: about $0.16 per task, or about $156 a day at 1,000 tasks
A single-call workflow step of similar size (3,000 tokens in, 500 out) costs about $0.02, roughly a seventh of that. Your numbers will differ, and output is the figure most likely to be off: thinking tokens are billed as output, and Opus 5.5 decides per request how much to think, guided by the effort setting. Every API response reports its token usage, including how many output tokens went to thinking, so log it per run from the first prototype and you'll have the real cost per task.
The usual levers are prompt caching (on Opus 5.5, cached input is billed at 5% of the base input price, and most of each agent call is a repeated prefix), a lower effort setting or a smaller model for simple sub-steps, leaner tool results and a lower step limit.
If you're hiring someone to build it
Ask these before you sign:
- Which cases in the test set does the agent fail today, and how will you see that number change?
- What can it do without a person's approval?
- What happens when the model provider is down or rate-limits you?
- Who owns the prompts, the tool code and the logs when the project ends?
- How will you see the cost per task?
If you'd like a second opinion on whether your process needs an agent at all, we can look at it with you.
Frequently asked questions
What is the difference between an AI agent and a chatbot?
A chatbot answers inside the conversation. An agent can take actions through tools (look up an order, open a ticket, run a query) and decides how many steps it needs. Plenty of products sold as chatbots are small agents with one or two tools.
Do I need a vector database to build an agent?
Only if the agent has to search a large body of text, and then retrieval is one more tool. The physiotherapy program generator above uses retrieval over the clinic's exercise library; the refund agent in the code needs none.
Can an agent run on an open-source or self-hosted model?
Yes. Most frameworks accept local models (Microsoft Agent Framework lists Ollama, for example), but tool-calling reliability varies a lot from model to model. Run your test set on it before you commit.
Can I build an agent without writing code?
For simple cases, yes. Visual workflow tools have agent steps: n8n's AI Agent node, for example, connects a chat model to the tools you attach and lets the model decide which one to call. Everything above still applies: a few narrow tools, approval before writes, a test set and a log of every call. Check that the platform will stay around, too: OpenAI is shutting down its visual Agent Builder on 30 November 2026.
How long does it take to build an AI agent?
A prototype with two or three tools can run within days. Getting it through a real test set, with approvals, logging and monitoring in place, takes longer. The closest example we can point to is the field-ticket workflow: the engagement started in July 2025 and the workflow went live in September 2025, after a month of testing on real tickets.
Related Articles
MLOps Guide: What to Set Up First, and What Can Wait
MLOps gets a model into production and keeps it useful there. Here is the order we'd set it up in, with current MLflow and DVC examples, and what changes for LLM features.
Read More: MLOps Guide: What to Set Up First, and What Can WaitComputer Vision Applications: Where It Works and Where It Struggles
Where computer vision works today, from inspection lines to invoices and medical scans, what makes some applications hard, and when a general vision model saves you training your own.
Read More: Computer Vision Applications: Where It Works and Where It StrugglesHow to Build an MCP Server: Python Code, Testing, Hosts and Auth
A working Python MCP server for the 2026-07-28 spec, how to test it and connect it to Claude or ChatGPT, and the tool design and auth rules that matter once it goes remote.
Read More: How to Build an MCP Server: Python Code, Testing, Hosts and Auth
