Most agent projects die in the gap between the demo and the deploy. The prototype works on a Tuesday afternoon, someone shows it in a meeting, and then it meets real inputs and quietly falls apart.
I have shipped agents that screen CVs, qualify B2B leads, answer WhatsApp support threads and drive outbound calls. The ones that survived shared the same shape: narrow scope, few tools, real evaluation sets, hard limits. So when someone asks me how to build an AI agent, the answer is mostly about everything surrounding the model call. This is the path I actually follow, in the order I follow it.
What is an AI agent, and when do you actually need one?
An AI agent is a language model running in a loop with tools: it reads a goal, chooses a tool, observes the result, and repeats until it finishes or hits a limit. You need one when the sequence of steps cannot be known before the request arrives.
If you can draw the flowchart, build the flowchart. A deterministic pipeline is cheaper, faster and easier to debug than an agent, and it never invents a step. I go deeper on that boundary in what AI agents are and are not.
Skip the agent and write ordinary code when any of these are true:
- The steps are the same every time, only the data changes.
- A wrong action costs money or trust and cannot be reversed by an undo.
- The task is a single model call plus a template, which is a chain, not an agent.
- You have no way to check whether the output was correct after the fact.
"Every tool you hand an agent is a permission you granted a system that cannot be cross-examined."
How to build an AI agent: the eight-step path
The short version of how to build an AI agent is eight steps, and the order is not cosmetic. Teams that write guardrails before evals end up guessing, and teams that add memory before tools end up storing noise.
The full build path, prototype through production:
- 1Scope the job to one outcome you can measure.
- 2Pick the loop: single-pass tool call, ReAct, planner-executor, or handoff.
- 3Define three to seven tools with typed schemas and narrow permissions.
- 4Add state and retrieval only where the loop demonstrably needs them.
- 5Build an eval set from twenty to fifty real historical cases.
- 6Add guardrails: step ceilings, cost caps, allowlists, human approval on write actions.
- 7Deploy behind an API with idempotency, timeouts and structured logging.
- 8Monitor cost per task, tool error rate, step distribution and escalation rate.
How do you scope an agent job so it can succeed?
Scope to a job that a competent junior could do with a checklist and access to your systems. If you cannot write that checklist, the agent has no chance either.
Four questions I ask before writing a line of code:
- What is the single artefact the agent produces? A ranked list, a ticket reply, a booked slot, a structured record.
- What does correct look like, and who decides? Name the human, not the department.
- What is the worst thing this agent can do if it is confidently wrong?
- What is the fallback when it fails, and how fast does a human find out?
On AgenticAI, a GPT-4o CV screening platform, scope was the whole game. The agent does not hire anyone. It reads a role spec, reads a CV, extracts evidence against criteria and produces a scored shortlist with citations back to the document. A recruiter still makes the call, and that boundary is what made the system deployable.
Which agent loop should you pick?
Pick the simplest loop that can complete your task. Most production work I have shipped runs on a single-pass tool call or a short ReAct loop, not a multi-agent swarm.
Loop selection, with the failure mode each one brings:
| Loop | How it works | Use when | Failure mode |
|---|---|---|---|
| Single-pass tool call | One model call picks one tool, you return the result and format it | Lookups, classification, routing | Cannot recover from a bad tool result |
| ReAct loop | Model alternates reasoning and tool calls until it answers | Research, triage, multi-source questions | Loops on itself without a step ceiling |
| Planner-executor | One call writes a plan, a cheaper model executes each step | Long tasks with stable sub-steps | Plan drifts from reality mid-run |
| Multi-agent handoff | Specialised agents pass control with a shared state object | Genuinely distinct skill domains | Cost and latency multiply; blame is hard to assign |
A minimal tool loop in Python
Everything else is decoration on this. The loop below is the whole idea: call the model, run the tools it asked for, feed results back, stop at a ceiling.
import json
from openai import OpenAI
client = OpenAI()
TOOLS = [{
'type': 'function',
'function': {
'name': 'get_order_status',
'description': 'Look up the delivery status of one order by its ID.',
'parameters': {
'type': 'object',
'properties': {'order_id': {'type': 'string'}},
'required': ['order_id'],
},
},
}]
HANDLERS = {
'get_order_status': lambda order_id: lookup_order(order_id),
}
def run_agent(messages, max_steps=6):
for _ in range(max_steps):
reply = client.chat.completions.create(
model='gpt-4o',
messages=messages,
tools=TOOLS,
).choices[0].message
messages.append(reply)
if not reply.tool_calls:
return reply.content
for call in reply.tool_calls:
args = json.loads(call.function.arguments)
try:
result = HANDLERS[call.function.name](**args)
except Exception as exc:
result = {'error': str(exc)}
messages.append({
'role': 'tool',
'tool_call_id': call.id,
'content': json.dumps(result),
})
raise RuntimeError('agent hit the step ceiling without finishing')Four details matter more than the model name. The step ceiling is not optional. Tool exceptions get returned to the model as data instead of crashing the run, so it can try a different approach. Every assistant message goes back into the history unchanged. And the ceiling raises loudly, so a stuck agent becomes an alert rather than a bill. The same structure works against Anthropic Claude, where tool_use and tool_result blocks replace the tool_calls field, and against OpenAI models through the function calling API.
How do you define tools the agent will not misuse?
Design tools as if a fast, literal-minded contractor will call them without reading the internal wiki. OpenAI's function calling guide describes tools as JSON Schema definitions the model selects between, and Anthropic's tool use documentation describes the same loop, so the discipline transfers across providers.
Rules I apply to every tool an agent gets:
- One verb per tool. Not manage_order, but get_order_status and cancel_order.
- Constrain in the schema, not the prompt. Enums, max lengths and required fields are enforced; instructions are advice.
- Return structured data plus a short human-readable summary. The model reasons better over both.
- Return errors as values with a hint about what to try next, never as silent nulls.
- Keep the count low. Somewhere past seven or eight tools, selection accuracy in my builds starts to visibly degrade and it is worth splitting into two agents.
- Scope credentials per tool. A read tool gets a read-only role, not the same key as the write tool.
When I built AgentFlow, a visual no-code AI agent builder, most of the engineering went into tool contracts rather than prompting. Non-technical users could compose flows safely because each block exposed a narrow, validated action instead of raw system access.
What memory does an AI agent actually need?
Most agents need less memory than teams assume. Add layers only when the loop fails without them, because every layer is a new source of stale or poisoned context.
Memory layers, in the order I add them:
| Layer | What it holds | Typical store | Add it when |
|---|---|---|---|
| Working context | The current message list and tool results | Process memory | Always, by definition |
| Task state | Run ID, step count, partial results, status | Postgres or Supabase row | The task spans more than one request |
| Retrieval | Documents, policies, product data | pgvector or a hybrid keyword index | The agent needs facts outside its tools |
| Long-term profile | Stable user or account preferences | Key-value rows, written deliberately | Repeat users notice the agent forgetting |
Two warnings from experience. Vector search is not memory; it is retrieval with fuzzy recall, and it will happily return a policy document that was superseded last quarter unless you filter on recency and version. And anything the agent writes to long-term memory should be an explicit tool call the model chose, not a silent background summariser you cannot audit.
How do you evaluate an agent before customers see it?
Build an eval set of twenty to fifty real historical cases with known-good outcomes, and run it on every prompt or model change. Vibes-based testing is why agents regress silently.
The evaluation sequence I use:
- 1Pull real inputs from logs, tickets or spreadsheets. Synthetic cases hide the messiness that breaks agents.
- 2Label the expected outcome per case, including the cases where the correct answer is to escalate.
- 3Score deterministically wherever possible: did it call the right tool, did the extracted field match, did it stay under the step ceiling.
- 4Use an LLM judge only for open-ended text, and spot-check the judge against human labels before trusting it.
- 5Track a regression suite of every bug you have ever fixed, so old failures cannot come back.
Report two numbers to stakeholders: task success rate and escalation rate. A high escalation rate with high success is a healthy, honest agent. High success with zero escalation usually means the agent is guessing confidently. I unpack more of these operational failure patterns in lessons from running agents in production.
What guardrails and monitoring does production require?
Guardrails are the layer that decides whether a bad model output becomes a bad business outcome. The OWASP Top 10 for Large Language Model Applications names prompt injection and excessive agency directly, and both are agent problems rather than chatbot problems.
The production floor I will not ship without:
- Hard step ceiling and wall-clock timeout per run.
- Per-run and per-tenant cost cap that halts the loop rather than warning about it.
- Human approval on any irreversible write: refunds, sends, deletions, bookings.
- Allowlists for URLs, domains and database tables the tools may reach.
- Treat retrieved documents and tool output as untrusted input, not as instructions.
- Structured logs of every step: prompt hash, tool name, arguments, latency, tokens, outcome.
- Idempotency keys so a retried run does not send the same email twice.
Deploy the loop behind a plain FastAPI service with a queue for long runs, not inside a request handler that times out at thirty seconds. How much autonomy to grant is its own decision, and it is the one question I would settle with stakeholders in writing before launch rather than after the first incident.
How much does it cost to build and run an AI agent?
Running cost scales with tokens per step multiplied by steps per task multiplied by task volume, so the cheapest optimisation is almost always fewer steps rather than a cheaper model. Build cost is dominated by integration and evaluation work, not by prompting.
Where the money actually goes:
| Cost driver | What controls it | Lever with the biggest effect |
|---|---|---|
| Model tokens | Context size times steps times volume | Trim system prompt and tool schemas; cap steps |
| Retrieval | Embedding calls plus vector store hosting | Cache embeddings; chunk once, not per query |
| Integration work | Number and messiness of upstream systems | Fewer tools, cleaner API contracts |
| Evaluation | Case labelling and judge calibration | Reuse real historical cases instead of writing new ones |
| Human review | Escalation rate times reviewer minutes | Raise precision on the escalate decision |
Providers price per million input and output tokens, with cached input usually billed lower, and those rates change often. Check the current OpenAI and Anthropic pricing pages rather than any number in a blog post, then model your own cost per task from step counts you measured. If you are deciding whether to build at all, I compare that trade honestly in custom AI builds versus AI SaaS tools. Either way, the useful answer to how to build an AI agent is to ship one narrow workflow, prove it against real cases, and expand only from there.
Key takeaways
- An agent is a model in a loop with tools; if you can draw the flowchart, build the flowchart instead.
- Scope to one measurable outcome and name the human who decides what correct means.
- Three to seven narrowly typed tools have outperformed large toolboxes in my builds, where selection accuracy visibly degrades as the list grows.
- Evals built from real historical cases must exist before guardrails, because you cannot guard an unmeasured behaviour.
- Step ceilings, cost caps and human approval on irreversible writes are the difference between a demo and a deployable system.
- Running cost is driven by steps per task far more than by the model you picked.
Frequently asked questions
- How long does it take to build an AI agent?
- A working prototype loop takes a day or two. Production takes weeks, because integration, evaluation, guardrails and monitoring dominate the schedule. In the builds I have run, the loop itself is the smallest piece; wiring real systems and proving reliability against historical cases is where the calendar goes.
- What programming language should I use to build an AI agent?
- Python, in almost every case. The OpenAI and Anthropic SDKs, evaluation tooling, vector clients and data libraries are all Python-first, and FastAPI gives you a production service quickly. TypeScript is a reasonable second choice when the agent lives inside an existing Node application.
- Do I need a framework like LangChain or LangGraph to build an agent?
- No. A first agent is roughly forty lines of Python around the provider SDK, and writing it yourself teaches you where failures come from. Frameworks earn their place later for durable state, retries and multi-step orchestration. Start with the raw loop, adopt a framework when you feel the specific pain it solves.
- How much does it cost to run an AI agent per task?
- Cost per task equals tokens per step times steps per task times the provider rate, plus retrieval and hosting. Providers bill per million input and output tokens with cached input usually cheaper, and rates change, so check the official pricing pages and multiply by step counts you measured in your own eval runs.
- What is the difference between an AI agent and a workflow automation?
- A workflow automation follows a fixed sequence you defined in advance. An agent chooses its own sequence at runtime from the tools you gave it. Automation is cheaper and more predictable; agents are worth the overhead only when the steps genuinely vary per request and the variation cannot be enumerated.
- Is it worth building a custom AI agent instead of buying a SaaS tool?
- Buy when your process resembles everyone else's and the tool covers it. Build when the agent must touch your proprietary data, follow your internal rules, or produce an output no vendor models. The decision usually turns on integration depth rather than on model capability.
- Can an AI agent take actions in my real systems safely?
- Yes, with constraints. Give each tool its own scoped credential, allowlist the resources it may reach, require human approval on irreversible writes, and use idempotency keys so retries cannot duplicate side effects. OWASP calls unconstrained action-taking excessive agency, and it is the most common way agents cause real damage.
- How do I know if my AI agent is good enough to launch?
- When it passes a regression suite of real historical cases, its escalation rate is honest rather than zero, cost per task is predictable, and every run is logged well enough to reconstruct what happened. If you cannot answer why a specific run failed yesterday, you are not ready to launch.
Sources
Written by Syed Husnain Haider Bukhari
AI engineer, data scientist, and founder of Revolutionary Technologies LLC. Ships production AI agents, automations, and data platforms for teams in the US, UK, and UAE — including AgentFlow, AI Walay, and ProLeads.
Get in touch →Related pages
Want this built instead of researched?
Book a 30-minute scoping call. You get a one-page plan and a fixed-scope quote within 48 hours.
Start a conversation