← Blog

AI Agent How To: Build One From First Principles

2026-09-22 · 5 min read · SubToAPI Team

Building an AI agent comes down to four things: a model that can reason, a loop that lets it act repeatedly, a set of tools it can call, and an API connection reliable enough to run in production. If you're searching "AI agent how to," you probably already know what an agent is conceptually — you want to know what actually goes into making one work, not just the marketing definition.

This article walks through the mechanics: the reasoning loop, tool definitions, state management, and the infrastructure decisions that separate a demo from something you'd ship.

What an AI Agent Actually Does

An AI agent is a program that uses a language model to decide what to do next, takes an action, observes the result, and repeats until it reaches a goal. That's it. There's no separate "agent brain" — it's a loop around an LLM call plus some code that executes whatever the model decides.

The loop looks like this in practice:

  1. Send the model a task and the tools it can use.
  2. The model responds with either a final answer or a request to call a tool.
  3. Your code executes that tool call (hit an API, query a database, run a script).
  4. You send the result back to the model as context.
  5. Repeat until the model produces a final answer.

Everything else — planning, memory, multi-agent coordination — is built on top of this basic cycle.

Step 1: Define the Task and Boundaries

Before writing any code, decide what the agent is actually allowed to do. Vague scope is the most common reason agent projects stall. "Answer customer questions" is too broad. "Look up order status from our orders API and reply with a formatted summary" is buildable.

Write down:

Step 2: Give It Tools, Not Just a Prompt

Tools are what turn a chatbot into an agent. A tool is a function the model can request — search the web, query a database, send an email, call an internal API — described in a schema the model understands.

A tool definition typically includes a name, a description, and a JSON schema for its parameters:

{
  "name": "get_order_status",
  "description": "Look up the current status of an order by ID",
  "input_schema": {
    "type": "object",
    "properties": {
      "order_id": { "type": "string" }
    },
    "required": ["order_id"]
  }
}

When the model decides it needs this information, it returns a tool-use block instead of plain text. Your code parses that, runs the actual function, and sends the result back. See /docs/tools for the exact request/response shape if you're building against the Claude API family.

Step 3: Build the Execution Loop

The loop is usually 20-40 lines of code. Here's the shape of it:

async function runAgent(task) {
  let messages = [{ role: "user", content: task }];

  while (true) {
    const response = await callModel(messages, tools);

    if (response.stop_reason === "tool_use") {
      const toolResult = await executeTool(response.tool_call);
      messages.push({ role: "assistant", content: response.content });
      messages.push({ role: "user", content: toolResult });
    } else {
      return response.content;
    }
  }
}

The important part isn't the syntax — it's the pattern: append everything to the conversation, let the model see its own past actions, and give it a stopping condition. Without a max iteration count or a clear success signal, loops can run indefinitely and burn through tokens.

Step 4: Add Memory Where It Matters

Most agents don't need a vector database or long-term memory system on day one. Start with:

Adding retrieval infrastructure before you need it is a common way agent projects get stuck in setup instead of shipping.

Step 5: Handle Errors and Runaway Loops

Production agents fail in specific, predictable ways: tool calls throw errors, the model asks for a tool that doesn't exist, or it loops without making progress. Guard against each:

Step 6: Connect to a Real API Layer

Everything above assumes you have a stable, authenticated way to call the model itself. If you're already using Claude through a subscription and want to wire it into code, tools, and a proper request loop without managing separate API billing, that's exactly what SubToAPI does — it turns your existing Claude access into an HTTPS API with application keys (sub_live_...), streaming, tool-use support, and usage metadata per key.

A basic call looks like this:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Get the order status tool ready"}],
    "tools": [{"name": "get_order_status", "description": "...", "input_schema": {}}]
  }'

Start with /docs/quickstart to get a key, check /docs/messages for the full request format, and /docs/streaming if your agent needs to stream partial output to a UI while it works. Plans start at €9/month for solo use, with team seats at €19 and €49 for higher-volume workloads — see /pricing for the breakdown.

Step 7: Test With Real Tasks, Not Just Happy Paths

Run the agent on inputs that are ambiguous, missing data, or outside scope. Watch what it does when a tool returns an error or an empty result. Most of the tuning work in agent development is prompt and tool-description refinement based on these failure cases, not architecture changes.

Questions

Do I need a framework to build an AI agent? No. The core loop is simple enough to write directly. Frameworks help with multi-agent orchestration or complex state, but for a single-purpose agent, plain code against the API is often easier to debug.

How is an AI agent different from a chatbot? A chatbot responds with text. An agent can take actions — calling tools, APIs, or functions — and uses the results of those actions to decide what to do next, often across multiple steps.

What's the minimum I need to start building one? A model API you can call programmatically, one or two well-defined tools, and a loop that sends messages, executes tool calls, and feeds results back until the task is done.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →