How to Build an AI Agent (Without the Hype)

19–29 minutes
P1 how to build an ai agent

An agent is a loop, some tools, and a bit of memory. Here is a working one in about forty lines of Python — plus the failure modes the launch posts leave out.

Last updated: 19 August 2026  ·  Reading time: 12 min  ·  By: the geminy.ai editors

Search “how to build an AI agent” and you will mostly find framework tours. Install this, decorate that, admire the diagram. What you rarely get is the thing underneath: an agent is a small, comprehensible program, and you can write one from scratch in an afternoon. This guide does that first, then adds tools, then explains where a framework genuinely earns its keep — and where it just adds a dependency.

One honest caveat up front. A large share of products currently marketed as “AI agents” are a single prompt with a nice interface. That is not a scandal; some of those products are excellent and solve real problems. But it does mean the word “agent” tells you almost nothing about what is inside. Knowing the actual mechanics is the fastest way to tell a useful product from a repackaged prompt — and to decide whether you should build one at all.

Quick answer

How do you build an AI agent? Three components: a loop that calls a language model repeatedly, a set of tools the model can invoke (ordinary functions with a JSON Schema attached), and memory — the running message history you feed back on every turn. Send the model the conversation plus the tool list, check whether it asked for a tool, run that tool, append the result to the history, and go round again until it answers in plain text. That is roughly forty lines of Python with no framework at all. Frameworks (OpenAI Agents SDK, LangGraph, Claude Agent SDK) become worthwhile once you need persistence, human approval steps, multi-agent routing or durable resumption — not before.

1. What an agent actually is, stripped of marketing

A language model on its own does one thing: text in, text out. It cannot read your database or send an email. An agent is the wrapper that gives it the ability to act, and it has exactly three moving parts.

  • A loop. Instead of one model call, you call in a cycle. The model decides what to do next; your code does it; the result goes back in. The loop ends when the model stops asking for actions, or when you cut it off.
  • Tools. Plain functions — search_orders(), send_invoice(), read_file() — described to the model as JSON Schema. The model never runs them. It emits a structured request naming a tool and its arguments; your code executes it and hands back the output.
  • Memory. At minimum, the growing list of messages: user turns, model turns, tool calls, tool results. Everything more sophisticated (vector stores, summarisation, scratchpad files) is an optimisation on top of that list.

That is the entire concept. The evolution from scripted chatbots to models that call tools is covered in more depth in our piece on the shift from bots to intelligent agents, but the mechanics have not changed since: loop, tools, memory.

The hard parts are not conceptual. They are operational — cost, termination, error handling — and we get to those in section six.

2. The minimum viable agent, in about forty lines

Here is a complete agent using nothing but the Anthropic Python SDK. It runs. Install with pip install anthropic, set ANTHROPIC_API_KEY in your environment, and execute it.

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

def word_count(text: str) -> str:
    """The actual tool. An ordinary Python function."""
    return str(len(text.split()))

TOOLS = [{
    "name": "word_count",
    "description": (
        "Count the words in a block of text. Use this whenever the user asks "
        "how long something is or how many words it contains. Returns the "
        "count as a string. Does not count characters or sentences."
    ),
    "input_schema": {
        "type": "object",
        "properties": {
            "text": {"type": "string", "description": "The text to count words in"}
        },
        "required": ["text"],
    },
}]

HANDLERS = {"word_count": word_count}

def run(task: str, max_steps: int = 8) -> str:
    messages = [{"role": "user", "content": task}]

    for _ in range(max_steps):                      # the loop
        response = client.messages.create(
            model="claude-opus-5",
            max_tokens=1024,
            tools=TOOLS,
            messages=messages,                      # the memory
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":      # model answered; we're done
            return "".join(b.text for b in response.content if b.type == "text")

        results = []
        for block in response.content:              # the tools
            if block.type != "tool_use":
                continue
            try:
                output = HANDLERS[block.name](**block.input)
                results.append({"type": "tool_result",
                                "tool_use_id": block.id, "content": output})
            except Exception as exc:
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": f"Error: {exc}", "is_error": True})
        messages.append({"role": "user", "content": results})

    return "Stopped: step limit reached."

if __name__ == "__main__":
    print(run("How many words are in: 'the cat sat on the mat'?"))

Four things are worth noticing.

The loop is a for statement with a hard ceiling, not a while True. That single decision prevents the most expensive class of agent bug. The stop_reason check is how the model tells you it is finished — when it stops returning tool_use, it has produced a final answer. Tool results go back as a user message containing tool_result blocks, and each one must carry the tool_use_id that matches the request; the blocks must also come first in the content array, before any text. And errors are handled by returning them to the model with is_error: true rather than crashing, so it can try something else.

Swap anthropic for the OpenAI SDK and the shape is the same — different field names, identical structure. The loop is the agent. Everything else is convenience.

3. Adding tools properly

Getting tools to work is easy. Getting the model to use the right one at the right moment is where the actual engineering lives, and it is mostly a writing problem.

Descriptions do the heavy lifting. Anthropic’s own guidance is blunt about this: the tool description is by far the largest factor in tool-use performance, and three or four sentences is a floor, not a target. Say what the tool does, when it should and should not be used, what each parameter means, and what the tool does not return. A description reading “gets user data” will produce erratic behaviour no matter how good the model is.

Fewer, broader tools beat many narrow ones. Rather than create_ticket, update_ticket, close_ticket and assign_ticket, expose one tickets tool with an action parameter. Every additional tool widens the space the model has to choose from and adds tokens to every single request.

Namespace once you cross a handful. github_list_prs and slack_send_message stay unambiguous as your library grows; list and send do not.

Return only high-signal output. A tool that dumps a 400-row JSON blob burns context and makes the model’s next decision harder. Return the fields needed to reason about the next step and stable identifiers, not everything the API gave you.

Both major SDKs will now generate the schema from your function signature, which removes the most tedious part. Anthropic’s @beta_tool decorator reads type hints and the docstring, and its Tool Runner handles the loop you wrote by hand above:

import json
from anthropic import Anthropic, beta_tool

client = Anthropic()

@beta_tool
def get_weather(location: str, unit: str = "celsius") -> str:
    """Get the current weather in a given location.

    Args:
        location: The city and country, e.g. Lisbon, Portugal
        unit: Temperature unit, either 'celsius' or 'fahrenheit'
    """
    return json.dumps({"temperature": "20", "condition": "Sunny"})

runner = client.beta.messages.tool_runner(
    model="claude-opus-5",
    max_tokens=1024,
    max_iterations=10,        # your loop ceiling, kept
    tools=[get_weather],
    messages=[{"role": "user", "content": "What's the weather in Lisbon?"}],
)

final_message = runner.until_done()
for block in final_message.content:
    if block.type == "text":
        print(block.text)

Note that the Tool Runner is still marked beta at the time of writing, and that max_iterations is not set by default. If you use it, set it.

4. When to reach for a framework — and when it’s overkill

The honest answer: build the loop yourself first. It takes an hour, you will understand every failure you hit afterwards, and roughly half of production agents never outgrow it. Reach for a framework when you hit one of these specific walls.

The OpenAI Agents SDK is the lightest of the three. It gives you agents, tools, guardrails, sessions and handoffs to other agents, with tracing built in. Install with pip install openai-agents:

import asyncio
from agents import Agent, Runner
from agents.decorators import tool

@tool
def history_fun_fact() -> str:
    """Return a short history fact."""
    return "Sharks are older than trees."

agent = Agent(
    name="History Tutor",
    instructions="Answer history questions clearly. Use history_fun_fact when it helps.",
    tools=[history_fun_fact],
)

async def main():
    result = await Runner.run(agent, "Tell me something surprising about ancient life.")
    print(result.final_output)

asyncio.run(main())

Reach for it when you want handoffs between specialist agents, input/output guardrails running in parallel with execution, or a trace viewer you did not have to build.

LangGraph is the opposite trade: more ceremony, far more control. You define the agent as an explicit graph of nodes and edges, which means you can checkpoint state, pause for a human, and resume a run days later from exactly where it stopped. The loop from section two, expressed as a graph:

from langchain.tools import tool
from langchain.chat_models import init_chat_model
from langchain.messages import AnyMessage, SystemMessage, ToolMessage
from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict, Annotated
from typing import Literal
import operator

model = init_chat_model("claude-sonnet-4-6", temperature=0)

@tool
def add(a: int, b: int) -> int:
    """Adds `a` and `b`.

    Args:
        a: First int
        b: Second int
    """
    return a + b

tools_by_name = {"add": add}
model_with_tools = model.bind_tools([add])

class MessagesState(TypedDict):
    messages: Annotated[list[AnyMessage], operator.add]

def llm_call(state: MessagesState):
    return {"messages": [model_with_tools.invoke(
        [SystemMessage(content="You do arithmetic.")] + state["messages"]
    )]}

def tool_node(state: MessagesState):
    result = []
    for call in state["messages"][-1].tool_calls:
        observation = tools_by_name[call["name"]].invoke(call["args"])
        result.append(ToolMessage(content=observation, tool_call_id=call["id"]))
    return {"messages": result}

def should_continue(state: MessagesState) -> Literal["tool_node", END]:
    return "tool_node" if state["messages"][-1].tool_calls else END

builder = StateGraph(MessagesState)
builder.add_node("llm_call", llm_call)
builder.add_node("tool_node", tool_node)
builder.add_edge(START, "llm_call")
builder.add_conditional_edges("llm_call", should_continue, ["tool_node", END])
builder.add_edge("tool_node", "llm_call")
agent = builder.compile()

That is considerably more code than the forty-line version for identical behaviour. The payoff arrives only when you need durable execution, interrupts or branching state. If your agent runs for eight seconds and answers a question, this is overkill and you should not feel clever for using it.

The Claude Agent SDK sits in a different category again: rather than composing an agent from parts, it hands you the whole harness behind Claude Code, including file editing, shell access and permission controls. It is the fastest route to an AI coding assistant or anything that needs to operate on a real repository. pip install claude-agent-sdk:

import anyio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock

options = ClaudeAgentOptions(
    system_prompt="You are a careful Python refactoring assistant.",
    allowed_tools=["Read", "Write", "Bash"],   # auto-approve these
    permission_mode="acceptEdits",
    cwd="/path/to/project",
    max_turns=10,
)

async def main():
    async for message in query(prompt="Add type hints to utils.py", options=options):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, TextBlock):
                    print(block.text)

anyio.run(main)

One thing worth understanding: allowed_tools is a permission allowlist, not an availability list. Listed tools are auto-approved; unlisted ones fall through to your permission mode rather than disappearing. To actually remove a capability, use disallowed_tools. This trips people up.

Our comparisons of Claude and ChatGPT cover the consumer-facing side of both platforms if you are choosing a model before choosing a framework.

5. Connecting to the wider world with MCP

Writing tools by hand is fine for three. It stops scaling around thirty, and it does not help when the capability you need already exists. The Model Context Protocol solves this: build a tool once as an MCP server, and any MCP-compatible client can use it. We covered the ecosystem in detail in what an MCP server is and the best ones in 2026.

The Python SDK reached v2 in 2026 and got considerably terser. A complete server:

from mcp.server import MCPServer

mcp = MCPServer("Demo")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

@mcp.resource("greeting://{name}")
def greeting(name: str) -> str:
    """Greet someone by name."""
    return f"Hello, {name}!"

No JSON Schema, no request parsing — the type hints are the schema. Install with pip install "mcp[cli]" and inspect it with uv run mcp dev server.py. Note that pip install mcp now resolves to 2.x; if you are on the older API, pin "mcp>=1.28,<2" until you migrate.

Wiring an existing MCP server into an agent is a few lines. In the OpenAI Agents SDK, launching one as a local subprocess:

import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStdio

async def main():
    async with MCPServerStdio(
        name="Filesystem Server",
        params={
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/files"],
        },
    ) as server:
        agent = Agent(
            name="Assistant",
            instructions="Use the files in the sample directory to answer questions.",
            mcp_servers=[server],
        )
        result = await Runner.run(agent, "List the files available to you.")
        print(result.final_output)

asyncio.run(main())

Two security notes that are not optional. MCP tools act with whatever credentials you give them, so connect only to servers you trust and use least-privilege tokens. And content returned by any tool — a web page, an inbound email, a third-party API — should be treated as untrusted input, because anyone who can influence it can attempt to embed instructions aimed at your model. Keep that content inside tool result blocks rather than splicing it into your system prompt, and require explicit approval for destructive operations.

6. The failure modes nobody advertises

Every one of these has cost somebody real money. None of them appear in launch demos.

Cost blowouts. The message history grows on every turn, and you resend all of it each time. A ten-step agent does not cost ten times a single call — it costs closer to the sum of an arithmetic series, because turn ten pays for the tokens of turns one through nine as well. A verbose tool returning 5,000 tokens gets re-billed on every subsequent step. Guard: cap iterations, trim or summarise tool outputs before appending them, enable prompt caching on the stable parts of your prompt, and set a hard spend limit at the API-key level rather than trusting your code. Track tokens per run in your logs from day one; the first time you see a run cost [Insert live content] current per-million-token input/output pricing for the models named in this article you will want the number to hand.

Infinite loops. Models get stuck. They call the same search with the same arguments, get the same unhelpful result, and try again — forever, or until your budget notices. Guard: the hard iteration cap in section two, plus a repeat detector. Hash each (tool_name, arguments) pair; if the same call fires three times, break out and return the partial result rather than continuing.

Tool-call hallucination. The model invents a tool that does not exist, or passes an argument in the wrong shape. In the forty-line agent this surfaces as a KeyError in HANDLERS[block.name], which the try/except converts into an error result the model can recover from. Guard: never dispatch on a name without checking it exists first, validate arguments against your schema before executing (Pydantic is enough), and return a helpful error listing the valid tool names rather than a stack trace. Strict schema enforcement is available on both major APIs if you need a stronger guarantee.

Context exhaustion. Long-running agents fill the context window and either error out or start forgetting the beginning of the task. Guard: both major providers now offer server-side context management that prunes or summarises older turns automatically; on Anthropic’s API this is context editing, and the client-side compaction option in the SDKs has been deprecated in its favour. If you are managing it yourself, summarise completed sub-tasks into a short note and drop the raw turns.

Silent wrongness. The least discussed and most damaging. The agent completes, returns a confident summary, and the underlying action never happened or happened incorrectly. Guard: log every tool call and result, assert on side effects rather than trusting the model’s narration, and require human approval for anything irreversible. Both the OpenAI Agents SDK and MCP support per-tool approval policies — use them on writes and deletes.

7. When not to build an agent at all

This is the section most guides skip, and it is the one most likely to save you a quarter.

If the steps are known in advance, write the steps. An agent’s value is deciding what to do next under uncertainty. If you already know it is always fetch, then transform, then email, that is a script with three function calls and one model call in the middle. It will be faster, cheaper, deterministic and testable. Anthropic’s own engineering guidance makes this point plainly: use the simplest thing that works, and add agentic complexity only when a workflow demonstrably cannot handle the task.

If one prompt does it, use one prompt. Summarising, classifying, extracting, rewriting — these need a single well-constructed call, not a loop. Wrapping them in an agent adds latency and cost and buys nothing.

If failure is expensive and unrecoverable, don’t. Irreversible financial transactions, production database writes, communications sent on someone’s behalf. Non-determinism is a feature when exploring and a liability when committing. Put a human in the loop or keep the agent read-only.

If you cannot describe success, you cannot evaluate it. Without a way to tell a good run from a bad one, you have no way to know whether your prompt change helped. Build the evaluation before the agent.

This brings us back to the thin-wrapper problem. Plenty of “agent” products are, technically, a system prompt plus a text box — and some of those are genuinely worth paying for, because the prompt encodes real domain expertise, the interface is good, and the integration work is done. The problem is not that they are thin. It is that the label makes it impossible to tell them apart from something that runs a twelve-step loop against your production systems, and the two carry very different risks. When you are evaluating, ask what tools it has, what it is permitted to do without asking, and what happens when it is wrong. The answers are more informative than the word “agent”.

Build the small loop. Watch it fail in the specific ways your problem produces. Add exactly the machinery those failures require — [Insert live content] current major version numbers for openai-agents and langgraph if you end up reaching for a framework. That order round the right way is most of the craft.

Frequently asked questions

What is an AI agent, exactly?

An AI agent is a program that loops: it calls a language model, the model requests an action, your code performs that action, and the result is fed back for the next decision. It has three components — a loop, a set of tools (ordinary functions described to the model as JSON Schema), and memory (the running message history). Unlike a single prompt, an agent decides its own sequence of steps rather than following one you specified in advance.

Do I need a framework to build an AI agent?

No. A functional agent is about forty lines of Python using only the vendor SDK — you call the model, check whether it asked for a tool, run the tool, append the result, and repeat until it answers in plain text. Frameworks such as the OpenAI Agents SDK, LangGraph and the Claude Agent SDK become worthwhile when you need durable state across sessions, human approval steps, multi-agent routing or built-in tracing. Build the raw loop first; you will understand every failure you hit afterwards.

What is the difference between an AI agent and a chatbot?

A chatbot generates text in response to text. An agent can act: it invokes tools that read files, query databases, call APIs or send messages, then uses the results to decide what to do next. The practical difference is side effects. A chatbot can be wrong; an agent can be wrong and then do something about it. That is why permission controls and approval steps matter far more for agents than for chat interfaces.

How much does it cost to run an AI agent?

More than people expect, because the full message history is resent on every turn. A ten-step agent does not cost ten single calls — closer to the cumulative sum, since step ten pays for the tokens of steps one to nine too. Verbose tool outputs are the usual culprit, as they are re-billed on each subsequent step. Cap iterations, trim tool outputs before appending them, enable prompt caching on stable prompt sections, and set a spend limit at the API-key level rather than relying on your own code to behave.

How do I stop my agent from looping forever?

Three guards. First, a hard iteration ceiling — write the loop as a bounded for statement rather than while True, and return a partial result when it is hit. Second, a repeat detector: hash each tool name plus its arguments and break out if the same call fires three times, which catches the common pattern of a model retrying an identical failing search. Third, a wall-clock timeout for anything running unattended. Frameworks expose a maximum-iterations setting, but it is often not enabled by default, so set it explicitly.

What is MCP and do I need it for my agent?

The Model Context Protocol is an open standard for exposing tools to AI models, so a tool built once works with any compatible client. You do not need it for a handful of custom functions — a plain schema is simpler. It becomes valuable when you want to reuse existing integrations rather than writing your own, when the same tools must work across multiple AI clients, or when you have enough tools that maintaining bespoke wiring is a burden. The Python SDK reached version 2 in 2026 and generates schemas from type hints.

Can I build an AI agent without coding?

Partly. No-code platforms let you assemble tool-using workflows visually, and for well-defined internal automations they work. The limits appear quickly: you inherit the platform’s error handling, cost controls and context management, and debugging a misbehaving agent through a visual editor is considerably harder than reading a forty-line loop. If the agent touches anything important, the ability to inspect and control the loop is worth the code.

When should I not build an AI agent?

When the steps are known in advance — that is a script with a model call in the middle, and it will be faster, cheaper and testable. When a single prompt does the job, as with summarising or classifying. When failure is expensive and irreversible, such as production database writes or financial transactions, unless a human approves each action. And when you have no way to distinguish a good run from a bad one, because without evaluation you cannot tell whether any change you make is an improvement.

Sources

On this page

Leave a Reply

About geminy.ai

An independent, free-to-read comparison site for generative AI platforms. We review and compare the major tools and point readers to them. We do not host, resell or broker AI models.

No affiliate links. No sponsored placements. No paid rankings.

Corrections and enquiries: bestmarketingtools.ai@gmail.com