Level : Advanced
How to build an AI agent: the complete guide, from no-code to code
Building an AI agent means connecting a language model to instructions, to tools it can trigger and to a loop that lets it act until the task is done. You can do it without code on a visual platform or with a Python or TypeScript framework: this guide gives you the shared method, then both paths, from choosing the task all the way to production.
What you are really building
An AI agent is not a souped-up chatbot. A chatbot answers a message. An agent receives a goal, decides on the steps itself, uses tools (looking something up, reading a file, sending a request to another app) and checks the results before choosing what to do next.
Under the hood, everything relies on tool calling: the model does not run anything itself. It produces a structured request such as “call the weather tool with the city Boston”. Your program, or the platform, runs the tool and sends the result back to the model. The model reads that result, then decides: another tool call or a final answer. This alternation of reasoning, action and observation has a name, the ReAct pattern.
Here is the loop stripped to its essentials. It is pseudo-code, meant to show the principle; the frameworks covered below write it for you.
history = [instructions, user request]
repeat at most N times:
reply = model(history, list of tools)
if reply is a final answer: return reply
for each requested tool call:
result = run(tool, arguments)
append result to history
stop and report failure
Two details already matter. The “at most N times” cap stops an agent from going round in circles and running up your bill. And the whole history is sent back to the model on every turn: the longer the agent works, the longer and more expensive each call becomes.
Agent or workflow: the first question to ask
Many “agent” projects are really workflows: a sequence of steps known in advance, where AI steps in at one specific point (summarize, classify, draft). A workflow is more predictable, cheaper and easier to test. An agent becomes worthwhile when the path is not known in advance: investigating an incident, handling varied requests, digging through several sources.
Step 1: choose a task that suits an agent
An agent’s success is decided before the first line of configuration. A good starter task meets four criteria:
- It is frequent. Building an agent for a ten-minute monthly chore is not worth the effort.
- It needs a bit of judgment. If a fixed rule is enough, classic automation will do better.
- Its output is easy to check. You should be able to tell within seconds whether the agent did a good job.
- A mistake can be undone. For a first project, avoid payments, deletions and messages sent to customers without review.
Good candidates: triaging incoming requests and drafting a reply, preparing a briefing note from several documents, checking that a product page follows a template, enriching a contact list from public sources.
Check yourself Is an agent that automatically pays supplier invoices received by email a good first project?
No. The action is irreversible, checking it takes time and a mistake costs money. A better first project: an agent that reads invoices, extracts the amount, due date and supplier, compares them with the purchase order and prepares a list for a person to approve. Payment stays a human decision.
Step 2: assemble the four building blocks
Whatever the tool, no-code or code, you will find the same building blocks.
The model
This is the “brain” that reads the situation and decides. For an agent, three properties matter more than the overall score: how reliably it calls tools, how well it follows long instructions, and price, since the agent calls the model many times. A fast, cheap model is often enough to classify or extract; a more capable model is justified for planning a long task or writing code.
The instructions
The system prompt describes the agent’s role, its goal, its limits and the expected format. For an agent, add three things people often forget: when to stop, what to do when in doubt (ask rather than guess) and what it must never do. Our guide to prompt engineering covers writing techniques in detail.
The tools
Each tool is a function described by a name, a description and parameters. The model picks a tool based on that description: a vague description leads to random calls. A useful rule: few tools, well named, each doing one thing. A “read_order” tool and a “refund_order” tool beat a catch-all “manage_order” tool, not least because you can put the second one behind an approval step.
Memory and context
An agent has a working memory, its context window, which holds the history of the current task. It is limited in size and every token reread is paid for. To remember things between sessions, or to consult your documents, you need external memory: a database, files, or search over your documents with RAG (see below). Choosing what goes into the context at each step has become a discipline of its own, context engineering.
Step 3: choose your path, no-code or code
| Criterion | No-code (visual platform) | Code framework |
|---|---|---|
| Profile | Freelancer, business team, no-coder | Python or TypeScript developer |
| Getting started | Fast, with blocks and forms | Slower, but everything is under your control |
| Connectors | Many ready-made connectors | Written or imported (MCP, libraries) |
| Automated tests | Limited, often manual | Unit tests, evaluations, continuous integration |
| Hosting | With the vendor, sometimes self-hosted (n8n) | Wherever you like, but you run it |
| Cost | Platform subscription + model | Model + hosting (library often free) |
| Typical limit | Complex logic is hard to maintain | More engineering work up front |
There is no wrong choice, only poorly matched ones. A team without developers will get a useful result faster on a visual platform; a team that must embed the agent in its own product will need code. Here are a few representative tools from both worlds, with the characteristics recorded by the site:
| Tool | Type | License | MCP | Multi-agent | Level |
|---|---|---|---|---|---|
| n8n | Low-code | fair-code | Yes | Yes | Intermediate |
| Make | No-code | proprietary | Yes | — | Beginner |
| Zapier Agents | No-code | proprietary | — | — | Beginner |
| OpenAI Agents SDK | Code | MIT | Yes | Yes | Intermediate |
| Claude Agent SDK | Code | proprietary | Yes | Yes | Intermediate |
| Pydantic AI | Code | MIT | Yes | Yes | Intermediate |
| LangGraph | Code | MIT | Yes | Yes | Advanced |
Path 1: build an AI agent without code
On an automation platform such as n8n, Make or Zapier Agents, the build always follows the same logic:
- A trigger: an incoming email, a form submission, a set time, a message in a chat app.
- An agent block: you choose the model, paste your instructions and tick the allowed tools. In n8n, this is the AI Agent node, which can also delegate to specialist agents.
- Tools: the platform’s connectors (calendar, spreadsheet, CRM, email) or an MCP server.
- An output: a draft, a row in a sheet, a notification, ideally with a human approval step before any sensitive action.
This path is covered in detail, with a full example, in our tutorial on how to build an AI agent without code.
Two things to watch in a fast-moving market. First, check the tool’s status: according to the site’s data as of October 22, 2026, OpenAI announced the deprecation of Agent Builder (AgentKit) on June 3, 2026, with shutdown planned for November 30, 2026, and the Flowise team announced the project’s end of life on July 29, 2026. Do not start a new project on these tools. Second, read the billing model: credits, “activities” or executions, every platform counts differently, and the model cost is often added on top of the subscription.
Path 2: build an AI agent with a code framework
An agent framework spares you the loop, the history management, the tool-call format and part of the security work. You write the business logic. The examples below follow the syntax of the official documentation, consulted on October 22, 2026; they are deliberately short and need adapting to your case. For a detailed comparison, see our AI agent frameworks comparison.
A first agent with the OpenAI Agents SDK
The OpenAI Agents SDK is a lightweight, MIT-licensed SDK available in Python and TypeScript. Install it with pip install openai-agents. According to its official documentation, an agent is defined by a name, instructions and tools, then started with the Runner:
import asyncio
from agents import Agent, Runner
from agents.decorators import tool
@tool
def order_status(number: str) -> str:
"""Return the status of an order from its number."""
return "Shipped on October 20, delivery expected within 48 hours."
agent = Agent(
name="Order support",
instructions="You answer questions about orders. "
"Use the status tool and never make up a date.",
tools=[order_status],
)
async def main():
result = await Runner.run(agent, "Where is my order A-1042?")
print(result.final_output)
asyncio.run(main())
The function’s docstring becomes the tool description: write it carefully, because that is what the model reads. The SDK also offers handoffs to specialist agents, sessions, guardrails and built-in tracing.
A well-equipped agent with the Claude Agent SDK
Anthropic’s Claude Agent SDK reuses the engine behind Claude Code: out of the box, the agent can read and edit files, run commands or search the web, depending on the tools you allow. It only works with Claude models, and its use is governed by Anthropic’s Commercial Terms. Its Python reference pages show how to add your own tools as a small in-process MCP server:
import asyncio
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, query
@tool("order_status", "Status of an order", {"number": str})
async def order_status(args):
text = f"Order {args['number']}: shipped."
return {"content": [{"type": "text", "text": text}]}
shop = create_sdk_mcp_server(name="shop", version="1.0.0", tools=[order_status])
options = ClaudeAgentOptions(
system_prompt="You answer questions about orders.",
mcp_servers={"shop": shop},
allowed_tools=["mcp__shop__order_status"],
)
async def main():
async for message in query(prompt="Where is order A-1042?", options=options):
print(message)
asyncio.run(main())
The allowed_tools parameter is your first line of defense: only allow what the agent actually needs.
Typed answers with Pydantic AI
Pydantic AI is built around typing: you describe the exact shape of the answer and the framework validates it. An invalid structured output is caught instead of breaking your application. Switching providers means changing the string that names the model. An example based on the official documentation:
from pydantic import BaseModel
from pydantic_ai import Agent, RunContext
class Ticket(BaseModel):
category: str
urgent: bool
summary: str
# exact model ID: see your provider's documentation
agent = Agent("openai:model-name", output_type=Ticket,
instructions="Classify the customer's request.")
@agent.tool
def customer_history(ctx: RunContext, email: str) -> str:
"""Return the customer's latest requests."""
return "2 requests in October, none urgent."
result = agent.run_sync("My parcel never arrived, and this is the second time!")
print(result.output)
result.output is a validated Ticket object: your code can use it directly to route the request.
A controlled flow with LangGraph
LangGraph describes the agent as a graph: nodes (steps), edges (transitions) and shared state. It demands more effort, but according to its documentation you get durable execution, human intervention at any point, and short- and long-term memory. The minimal skeleton looks like this:
from langgraph.graph import StateGraph, MessagesState, START, END
def classify(state: MessagesState):
return {"messages": [{"role": "ai", "content": "category: delivery"}]}
graph = StateGraph(MessagesState)
graph.add_node(classify)
graph.add_edge(START, "classify")
graph.add_edge("classify", END)
graph = graph.compile()
graph.invoke({"messages": [{"role": "user", "content": "Parcel not received"}]})
In a real project, the node calls a model, and conditional edges route to a “tool” node, a “human approval” node or the end.
Step 4: connect the agent to your tools with MCP
Writing a different connector for every framework quickly becomes a burden. The Model Context Protocol (MCP) standardizes how an agent discovers and calls tools: you expose your tools once, as an MCP server, and any compatible client can use them. According to the site’s data, every code framework mentioned in this guide supports MCP, as do n8n and Make.
In practice, an MCP server declares a list of tools (name, description, parameters), possibly some resources to read, and answers calls. That is exactly what the Claude Agent SDK example above does, embedded in the program. For a standalone server that several agents can reuse, follow our tutorial to build an MCP server.
One design tip: an MCP server is a doorway into your systems. Give it limited permissions (read-only where possible), log every call and only connect servers whose origin you know.
Step 5: give the agent your documents
A model knows nothing about your procedures, your contracts or your catalog. To let an agent rely on them without loading everything into its context, you use RAG: documents are split into chunks and indexed, and the agent gets a “search the knowledge base” tool that returns the relevant passages. It then cites its sources instead of answering from memory.
Inside an agent, RAG simply becomes one tool among others. The agent decides when to search, rephrases its query if the first result is thin, and can combine several searches. Quality depends mostly on how documents are split and on the search itself; our explainer on what RAG is and how to give an AI your documents walks through these choices.
Step 6: choose the model and keep costs under control
An agent multiplies calls: one turn of the loop is a full call carrying the whole history. The price per million tokens therefore weighs far more than for a chat. Here are a few recent models, with their price and context window according to models.dev, recorded on October 22, 2026:
| Model | Developer | Release | Context (tokens) | Input ($/M tokens) | Output ($/M tokens) | Open weights |
|---|---|---|---|---|---|---|
| Claude Haiku 5.5 | Anthropic | October 7, 2026 | 1 M | $0.10 | $0.50 | No |
| GPT-6 Luna | OpenAI | September 22, 2026 | 1.05 M | $0.10 | $0.50 | No |
| Claude Sonnet 5.5 | Anthropic | September 28, 2026 | 1 M | $2 | $10 | No |
| GPT-6.1 Sol | OpenAI | September 29, 2026 | 1.05 M | $2 | $10 | No |
| Gemini 4 Argon | Google DeepMind | October 13, 2026 | 1.05 M | $2 | $10 | No |
| Claude Opus 5.5 | Anthropic | September 22, 2026 | 1 M | $4 | $20 | No |
A common strategy is to mix tiers: a small, cheap model to triage, classify or extract, and a more capable model only for steps that require planning or long reasoning. According to the same data, Claude Haiku 5.5 and GPT-6 Luna are listed at $0.10 per million input tokens and $0.50 per million output tokens, versus $4 and $20 for Claude Opus 5.5: forty times more.
Other levers cut the bill: capping the number of turns, summarizing the history instead of resending it all, and reusing an identical prompt prefix with prompt caching where the provider offers it. The AI agent cost calculator lets you simulate a scenario, and our guide to AI API pricing explains how to read and reduce the bill.
Step 7: test before you launch
An agent that works on three examples is not a reliable agent. Before going live, build a test set: at least twenty or so real cases, including easy ones, ambiguous ones and traps (off-topic request, missing information, a tool that returns an error). For each case, write down the expected result.
Then measure three things: is the final answer correct, did the agent call the right tools with the right parameters, and how much did the run cost. Replay the test set every time you change the model, the instructions or a tool: an improvement in one place often breaks something elsewhere. For answers that are hard to score automatically, a second model can act as the grader, a method called LLM-as-a-judge, as long as you check a sample of its scores yourself.
Observability complements testing: logging every step (model calls, tools, durations, costs) so you can understand an error after the fact. Several frameworks include tracing, such as the OpenAI Agents SDK, or rely on OpenTelemetry, such as Pydantic AI. The full approach is covered in our guide on how to evaluate an AI agent.
Step 8: secure the agent
An agent acts, so it can act badly. The main risk has a name: prompt injection. A text the agent reads, in an email, a web page or a document, contains hidden instructions that hijack its behavior. No technique eliminates it entirely, so you limit the possible damage.
- Least privilege. The agent only gets the tools and data it strictly needs, read-only where possible.
- Human in the loop. Every irreversible action (payment, sending, deletion) goes through approval: this is the human-in-the-loop principle.
- Sandbox. An agent that runs code or commands works in an isolated environment, with no access to your sensitive files.
- Guardrails. Guardrails check what goes in and what comes out: off-topic requests, personal data, non-compliant formats.
- Limits. Number of turns, token budget and maximum time per task.
Frameworks often provide these pieces. In the OpenAI Agents SDK, for example, an input guardrail is a function that can trip a “tripwire” and halt the run; here is a shortened version of the example in the guardrails documentation:
from agents import Agent, GuardrailFunctionOutput, Runner
from agents.decorators import input_guardrail
@input_guardrail
async def off_topic(ctx, agent, input):
result = await Runner.run(checker_agent, input, context=ctx.context)
return GuardrailFunctionOutput(
output_info=result.final_output,
tripwire_triggered=result.final_output.off_topic,
)
agent = Agent(name="Support", instructions="...", input_guardrails=[off_topic])
When the tripwire fires, the SDK raises an InputGuardrailTripwireTriggered exception, which your code catches to reply politely. Before handing over a task, the Can I trust an agent with this? tool helps you gauge the level of risk, and our guide to AI agent security details the attacks and the defenses.
Step 9: go to production
Moving from prototype to a service people use every day calls for a few extra precautions.
- Version everything: instructions, tool list, model and parameters. An unexpected answer should be traceable to a specific version.
- Pin the model. Use a specific version rather than an alias that changes on its own, and replay your tests before every switch.
- Plan for outages. Provider down, rate limit reached, tool failing: the agent must fail cleanly and alert someone.
- Watch the cost day by day, with an alert and a cap.
- Collect user feedback and add every real failure to your test set.
- Check the legal framework. If the agent processes personal data, data protection law applies: the GDPR in the EU, and the UK GDPR overseen by the ICO in the United Kingdom. For sensitive uses in the EU, the AI Act may impose obligations. A lawyer or your organization’s data protection officer is the right person to ask.
Summary: your roadmap
| Step | Question to ask | Deliverable |
|---|---|---|
| 1. Task | Frequent, checkable, reversible? | A one-sentence description |
| 2. Building blocks | Which model, instructions and tools? | A system prompt and a tool list |
| 3. Path | Visual platform or code framework? | A prototype |
| 4. MCP | Are my tools reusable? | An MCP server or connectors |
| 5. Documents | Does the agent need my data? | A search tool (RAG) |
| 6. Cost | What does a real run cost? | An estimate and a budget |
| 7. Tests | Does the agent pass my real cases? | A test set and traces |
| 8. Security | What happens if it is manipulated? | Limited permissions and human approvals |
| 9. Production | What if it fails or drifts? | Versions, alerts, user feedback |
Frequently asked questions
Do I need to know how to code to build an AI agent?
No. Visual platforms such as n8n, Make or Zapier Agents let you assemble an agent from blocks and forms. Code becomes worthwhile when you need fine-grained control, automated tests or a deep integration into your own software.
How much does it cost to run an AI agent?
Most code frameworks are free, but every model call is billed per token by the provider. An agent uses far more tokens than a simple chat, because it calls the model at every step and rereads its whole context. Estimate the cost on a realistic scenario before running the agent at scale.
Which framework should I pick for a first coded agent?
A lightweight SDK such as the OpenAI Agents SDK, Pydantic AI or smolagents is often enough to start: few concepts and an agent loop already written for you. LangGraph is a better fit when the flow must be controlled step by step, with recovery after failures and human approval.
Can an AI agent make serious mistakes?
Yes. It can misread an instruction, call the wrong tool or be manipulated by a booby-trapped text it reads. That is why you limit its permissions, require human confirmation before any irreversible action and test it on real cases before putting it into service.