40% off everything — use code SAVE40 at checkout · ends in …
Skip to content
phpguru.store

How to Build an AI Agent: A Step-by-Step Tutorial for 2026

By Prakash Panthi, Founder · Published September 29, 2026 · Updated September 29, 2026

Most "how to build an AI agent" tutorials either stay abstract or dump a framework on you. This one walks through what an agent actually is and the exact steps to build one that works — the same steps whether you use Python, JavaScript or PHP.

What an AI agent is

An AI agent is three things: a model that decides what to do, tools (functions you write) it can ask to use, and a loop — the model asks for a tool, your code runs it and returns the result, the model decides again, until the job is done. The model never runs anything itself; it only asks. That single fact is where all your safety and cost control lives.

Step 1: decide whether you need an agent

Ask four questions. Is the task multi-step and hard to specify in advance? Is the outcome worth the extra cost and latency? Is the model good at this kind of task? Can mistakes be caught and undone? If any answer is no, a single API call or a fixed workflow is the better tool. Agents are for open-ended jobs where the model genuinely needs to choose its next step.

Step 2: set up your environment

You need a model API key (kept in an environment variable, never in code), your language's official SDK, and a small test project. Make one plain API call first and read how many tokens it used — you'll want that number later.

Step 3: define your first tool

A tool has a name, a description and an input schema. The description matters most: say when to call the tool, not just what it does ("Call this whenever the customer mentions an order number"). Describe every input, use fixed lists (enums) for fixed choices, and turn on strict schema validation where your provider supports it.

Step 4: write the loop

  1. Send the task and the tool definitions.
  2. If the response asks for a tool, run it and send back the result tagged with the same call id.
  3. Append the full assistant message and all tool results, then call again.
  4. Stop when the model finishes — or when you hit your turn cap.

Handle every way a turn can end: finished, tool request, output cut off, paused, or declined for safety. Return tool errors as results so the model can recover, and never drop a result.

Step 5: add guardrails

Give every tool a policy: allow (read-only), ask (a human approves — money, emails, deletes) or deny. Anything not listed is denied. Cap turns, set a spend budget, and keep a kill switch. Treat text the agent reads — web pages, emails — as data, never as instructions.

Step 6: control cost

Agents re-send the whole conversation every turn, so cost grows fast. Use prompt caching for the stable prefix, the right model for each job, sensible effort settings, and log the cost of every run with a daily cap.

Step 7: host it

Agent runs take a while, so don't run them inside a web request. Put jobs in a queue table and process a few per run from a cron job — this works even on ordinary shared hosting. Move to a VPS when you need long live streaming.

Step 8: test before you change anything

Keep five to ten test cases — a normal request, an action that must be gated, an injection attempt, an off-topic message — and run them before every prompt, tool or model change.

A worked example

A support agent with three tools — find_order, check_stock and draft_reply — reads a customer message, looks up the order, checks stock and drafts a reply for a human to approve. It never sends anything itself. That pattern (read, look up, propose, human decides) is the shape of most useful business agents.

The code: a minimal agent in PHP

Here is the whole idea in working code, using the official Anthropic PHP SDK (composer require "anthropic-ai/sdk"). The same shape works in any language — a tool definition, then a loop that runs until the model stops asking for tools.

1. Define a tool

<?php
$tools = [[
    'name' => 'find_order',
    'description' => 'Look up one order by id. Call this whenever the customer mentions an order number.',
    'inputSchema' => [
        'type' => 'object',
        'properties' => ['order_id' => ['type' => 'integer', 'description' => 'Numeric order id']],
        'required' => ['order_id'],
        'additionalProperties' => false,
    ],
    'strict' => true,
]];

The description says when to use the tool; strict guarantees the input matches the schema.

2. Run the loop

<?php
$messages = [['role' => 'user', 'content' => 'Where is order 4821?']];
$call = fn($m) => $client->messages->create(
    model: 'claude-opus-5-5', maxTokens: 16000, tools: $tools, messages: $m,
);
$response = $call($messages);
$turns = 0;
while ($response->stopReason === 'tool_use' && ++$turns <= 10) {
    $results = [];
    foreach ($response->content as $block) {
        if ($block->type === 'tool_use') {
            $results[] = [
                'type' => 'tool_result',
                'toolUseID' => $block->id,
                'content' => find_order((int) $block->input['order_id']),
            ];
        }
    }
    $messages[] = ['role' => 'assistant', 'content' => $response->content];
    $messages[] = ['role' => 'user', 'content' => $results];
    $response = $call($messages);
}

Three details make this correct rather than a demo: the whole assistant message is appended (not just its text), every tool result goes back in one user message with its matching id, and the loop is capped at ten turns.

3. Read the answer

When the model stops calling tools, stopReason is end_turn and the text blocks hold the final answer. If it is max_tokens (cut off) or refusal, stop and handle it — never run a tool from a truncated turn.

Common mistakes when building your first agent

  • Vague tool descriptions. "Get order" tells the model nothing about when to use it.
  • Appending only the text. The tool request must stay in the history or the result makes no sense.
  • No turn cap. A loop that only ends when the model decides is a bill with no limit.
  • Letting it act unsupervised. Draft, don't send; queue refunds for a human.
  • Trusting what it reads. A web page or email can contain instructions — treat all tool results as data.
  • Keys in code. Use environment variables, always.

Frequently asked questions

Do I need a framework to build an AI agent?

No. An agent is a model, a few tools and a loop — about 40 lines of code. Frameworks and SDK helpers save typing later, but building the loop once yourself is the best way to understand what they do.

Which programming language is best for AI agents?

Whichever you already know. Python has the most tutorials, but official SDKs exist for Python, TypeScript, Java, Go, Ruby, C# and PHP, and the concepts are identical.

How much does it cost to run an AI agent?

It depends on the model and how many turns it takes. Each turn re-sends the conversation, so cost grows with length. Prompt caching, a sensible model choice and a turn cap keep typical runs to cents; log the cost of every run from day one.

Can an AI agent run on shared hosting?

Yes, if you queue the work: the web request saves a job, and a cron-driven worker processes a few jobs per run. Long live streaming needs a VPS.

Is it safe to let an agent take actions?

Only with guardrails: read-only tools can run freely, anything irreversible (payments, emails, deletes) should wait for a human, and every agent should have a spending cap and a kill switch.

Ready to build one properly? The Agentic AI Course takes you from your first tool call to a hosted, production-ready agent in 24 lessons — beginner to advanced. Lesson 1 is free.

Our Agentic AI Course: How to Build AI Agents, Beginner to Advanced (in PHP)

Includes the matching database file and email support — why that's worth it over a free download.

View Agentic AI Course: How to Build AI Agents, Beginner to Advanced (in PHP) →