PHP AI Agent: How to Build One Step by Step (With Code)
Build a PHP AI agent step by step with Neuron AI: tools, memory, structured output, RAG, guardrails

A production PHP AI agent does not need Python. Today's PHP frameworks give you everything an agent needs: tool calling, memory, structured output, retrieval and human approval, inside the app you already run.
A demo agent takes a few dozen lines. A production agent takes more: tools that only see the right customer's data, approval before money moves, a budget on runaway loops, memory that survives a restart, and tests.
The agent below is a real one: a returns and refunds assistant for an online store, built step by step in plain PHP with Neuron AI, plus the same agent in Laravel with the Laravel AI SDK.
Every code block was run on October 28, 2026, against the versions named in each step. The tests used the frameworks' fake AI providers, so they prove the tool loops, approvals and limits work, not the quality of the model's wording.
Key Takeaways
- A PHP AI agent is a loop: the model picks a tool, your PHP code runs it, and the result goes back to the model.
- Neuron AI works in any PHP 8.1+ app; the Laravel AI SDK is the first-party choice for Laravel 12 and 13.
- Scope every tool to the signed-in user, and require human approval for anything that moves money or data.
- Set a step budget. Neuron has none by default, and a per-tool cap alone does not stop a run.
- Archive a conversation after a forced stop, or the customer's next message will fail.
- Test with fake providers, so tool loops, approvals and limits are checked on every deploy for free.
What Is a PHP AI Agent?
The idea is the same in any language; our guide to LLM-powered autonomous agents covers the planning, reasoning and tool-use pieces in depth. In PHP terms, an agent has five parts:
- A model: the language model that reads the conversation and decides what to do next.
- Tools: PHP classes the model can call, such as looking up an order or issuing a refund.
- The loop: the framework sends the model's tool request to your code, then sends the result back, until the model answers.
- Memory: the saved conversation, so the agent remembers earlier messages from the same customer.
- Guardrails: limits on what tools can see and do, how long a run can go, and what needs a person's approval.
The framework handles the loop and the plumbing. You write the tools, the instructions and the guardrails, which is where the real work is.
Choosing a PHP AI Agent Framework
Five PHP projects are worth knowing in late 2026. The table compares them on what an agent needs, not on how many model providers they list.
Neuron AI is the most complete PHP AI agent framework outside a single web framework. It runs in plain PHP, Symfony or WordPress, and it ships tool approval with pause and resume, workflows and official test fakes. Version 4 changed much of its API, so check that any example you copy is written for 4.x.
The Laravel AI SDK is the natural pick for Laravel apps. It stores conversations in your database, supports approvals and fakes, and fits Laravel's queues and testing tools.
Symfony AI is promising but still in beta and marked experimental. Prism is a thin, provider-agnostic layer for Laravel, and LLPhant is strongest at retrieval. Neither has agent-level approval built in.
We use Neuron for the main build because it works in any PHP app and covers every step below. The Laravel version follows.
Build a PHP AI Agent With Neuron AI, Step by Step
The agent answers a store's returns and refund questions. It looks up the customer's orders, follows the store's written return policy and offers refunds, but a staff member must approve every refund before any money moves.

Step 1: Install Neuron AI and Set Up the Project
You need PHP 8.3 or later and Composer; we tested on PHP 8.4. Neuron itself supports PHP 8.1, but PHPUnit 12, used for the tests in step 9, needs 8.3. Install both:
composer require neuron-core/neuron-ai
composer require --dev phpunit/phpunitThe agent reads its settings from environment variables. Set them in your server config, or load a .env file with vlucas/phpdotenv. Use Dotenv::createUnsafeImmutable(__DIR__)->load(), because the usual createImmutable() does not fill getenv(), and the agent would see empty keys:
ANTHROPIC_API_KEY=your-anthropic-key
VOYAGE_API_KEY=your-voyage-key # embeddings for step 6
DB_DSN=mysql:host=127.0.0.1;dbname=shop
DB_USER=shop
DB_PASSWORD=change-me
AGENT_STORAGE=/var/app/storage/agent # conversations, paused runs, vectors
The tools need your database. A tiny helper keeps one PDO connection, and lets tests swap in an in-memory SQLite database:
<?php
declare(strict_types=1);
namespace App;
use PDO;
final class Database
{
private static ?PDO $pdo = null;
public static function pdo(): PDO
{
return self::$pdo ??= new PDO(
(string) getenv('DB_DSN'),
getenv('DB_USER') ?: null,
getenv('DB_PASSWORD') ?: null,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC],
);
}
public static function use(PDO $pdo): void
{
self::$pdo = $pdo;
}
}
Step 2: Connect a Model and Write the Instructions
An agent is a class. Its provider method names the model, and its instructions method tells the model who it is, what steps to follow and how to answer. Neuron's SystemPrompt helper keeps those three parts separate:
protected function provider(): AIProviderInterface
{
return new Anthropic(key: (string) getenv('ANTHROPIC_API_KEY'), model: 'claude-sonnet-5-5');
}
protected function instructions(): string
{
return (string) new SystemPrompt(
background: [
'You are the returns and refunds assistant for an online store.',
'You only discuss the signed-in customer\'s own orders.',
],
steps: [
'Look up the order with get_order before answering questions about it.',
'Answer policy questions only from the return policy context you are given.',
'Offer a refund only when the policy allows it, then call issue_refund.',
],
output: [
'Reply in two to four short sentences.',
'If you are unsure, say so and offer to pass the case to a person.',
],
);
}
We use Claude Sonnet 5.5, a strong tool-calling model, but any model with tool support works here. Neuron also ships providers for OpenAI, Gemini, Mistral, Ollama and others, so switching models means changing this one method, not the rest of the agent.
Write the steps as rules the model can follow. "Look up the order before answering" works better than "be helpful". The output rules keep replies short enough for a chat window.
Step 3: Give the Agent a Tool
A tool is a class with a name, a description, the inputs it accepts and an __invoke method that does the work. The model reads the name and description to decide when to call it:
<?php
declare(strict_types=1);
namespace App\Tools;
use App\Database;
use NeuronAI\Tools\PropertyType;
use NeuronAI\Tools\Tool;
use NeuronAI\Tools\ToolProperty;
class GetOrder extends Tool
{
protected string $name = 'get_order';
protected ?string $description = 'Look up one of the current customer\'s orders by its ID.';
public function __construct(private int $customerId) {}
protected function properties(): array
{
return [
new ToolProperty(name: 'order_id', type: PropertyType::INTEGER,
description: 'The order number', required: true),
];
}
public function __invoke(int $order_id): string
{
$stmt = Database::pdo()->prepare(
'SELECT id, status, total, delivered_at FROM orders WHERE id = ? AND customer_id = ?'
);
$stmt->execute([$order_id, $this->customerId]);
$order = $stmt->fetch();
return $order ? json_encode($order) : "No order {$order_id} for this customer.";
}
}
Notice the customer ID. The tool gets it from the agent, which gets it from your login session, so the query always filters by the signed-in customer. In our test, customer 8 asking about customer 7's order got "No order 1042 for this customer", whatever the model asked for.
The model only knows a tool through its name, description and inputs, so write them for the model:
- Name the action plainly. get_order and issue_refund say what happens; a name like helper2 leaves the model guessing.
- Say when to use it. "Look up one of the current customer's orders" tells the model both the purpose and the limit.
- Describe every input. "The order number" and "Refund amount in dollars" prevent mix-ups between IDs, cents and dollars.
- Return facts, not prose. The tool returns the order as JSON, and the model writes the sentence for the customer.
The tools expect an orders table and a refunds table. Our tests create them with these statements, which you can adapt to MySQL or PostgreSQL:
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INT, status TEXT, total REAL, delivered_at TEXT);
CREATE TABLE refunds (id INTEGER PRIMARY KEY, order_id INT, amount REAL, reason TEXT);
Then ask a question. The snippets in each step are parts of one SupportAgent class, shown complete at the end of this guide. In Neuron 4, chat() returns the agent's state, and the reply is its last message:
use App\SupportAgent;
use NeuronAI\Chat\Messages\UserMessage;
$state = SupportAgent::forCustomer(7)->chat(new UserMessage('Where is order 1042?'));
echo $state->getMessage()->getContent();
Step 4: Add Memory So Conversations Continue
Neuron 4 requires a thread ID before every chat, and the thread ID decides which conversation the agent loads. We use one thread per customer, set in a small factory method. The other lines in it are guardrails, which step 8 explains:
public static function forCustomer(int $customerId): static
{
$agent = static::make();
$agent->customerId = $customerId;
return $agent
->setThreadId("customer-{$customerId}") // one conversation per customer
->setMaxSteps(20) // hard stop for runaway loops
->toolMaxRuns(3) // each tool at most 3 times per turn
->setContextWindow(30_000) // trim old history past 30k tokens
->toolErrorHandler(fn (Throwable $e) => 'Tool error: ' . $e->getMessage());
}
By default, messages live in memory and vanish when the request ends. A message store saves them. Files are fine to start; Neuron also has SQL and Eloquent stores for production:
protected function messageStore(): MessageStoreInterface
{
return new FileMessageStore(self::storage('chats'));
}
In our test, a second request created a fresh agent object for the same customer, and the model received the full earlier exchange. That is what makes "as I said before" work in a chat that spans page loads.
Step 5: Return Structured Data, Not Just Text
Agents are often more useful when they return data your code can act on. Here the agent triages a new ticket into a category, an urgency and a summary, as a typed PHP object:
<?php
declare(strict_types=1);
namespace App;
use NeuronAI\StructuredOutput\SchemaProperty;
use NeuronAI\StructuredOutput\Validation\Rules\Enum;
use NeuronAI\StructuredOutput\Validation\Rules\Length;
use NeuronAI\StructuredOutput\Validation\Rules\NotBlank;
class TicketTriage
{
#[SchemaProperty(description: 'One of: return, refund, shipping, other', required: true)]
#[Enum(values: ['return', 'refund', 'shipping', 'other'])]
public string $category;
#[SchemaProperty(description: 'One of: low, normal, urgent', required: true)]
#[Enum(values: ['low', 'normal', 'urgent'])]
public string $urgency;
#[SchemaProperty(description: 'One-sentence summary for the support team', required: true)]
#[NotBlank]
#[Length(max: 200)]
public string $summary;
}
use App\SupportAgent;
use App\TicketTriage;
use NeuronAI\Chat\Messages\UserMessage;
$triage = SupportAgent::forCustomer(7)->structured(
new UserMessage('My blender arrived cracked and I want my money back today.'),
TicketTriage::class,
maxRetries: 2,
);
echo $triage->category; // "refund"
The validation attributes are enforced, not decoration. In our test, the first reply used a category outside the allowed list and a blank summary; Neuron rejected it, asked again and returned a valid object on the second try.
Step 6: Ground Answers in Your Return Policy
An agent should answer policy questions from your policy, not from what the model guesses. This is retrieval-augmented generation (RAG): the agent searches your documents and adds the relevant passages to the prompt. Our agentic RAG architecture covers bigger versions of the same idea.
In Neuron, the agent extends the RAG class instead of Agent, and adds two methods: one for the embeddings model that turns text into vectors, and one for the vector store that searches them:
class SupportAgent extends RAG
protected function embeddings(): EmbeddingsProviderInterface
{
return new VoyageEmbeddingsProvider(key: (string) getenv('VOYAGE_API_KEY'), model: 'voyage-3.5');
}
protected function vectorStore(): VectorStoreInterface
{
return new FileVectorStore(directory: self::storage('vectors'), topK: 4, name: 'return-policy');
}
The policy is a plain Markdown file. A short script indexes it with reindexBySource, so you can run it again whenever the policy changes:
# Return policy
Unused items can be returned within 30 days of delivery for a full refund to the original payment method.
Opened electronics can be returned within 14 days and are refunded minus a 10% restocking fee.
Final-sale items, gift cards and personalized products cannot be returned.
Refunds are issued within 5 business days after the return is approved.
If an item arrives damaged, the customer can get a full refund without returning it.
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use App\SupportAgent;
use NeuronAI\RAG\DataLoader\FileDataLoader;
// Run whenever the policy changes: old chunks from this file are replaced, not duplicated.
$documents = FileDataLoader::for(__DIR__ . '/../docs/return-policy.md')->getDocuments();
SupportAgent::make()->reindexBySource($documents);
echo 'Indexed ' . count($documents) . " policy chunks.\n";
In our test, asking how long a customer has to return unused items put the line "within 30 days of delivery" into the prompt the model received. The file vector store suits a small policy; for larger document sets, Neuron supports stores such as Qdrant, Pinecone, Elasticsearch and MariaDB.
Keep the Markdown file as the single source of truth. reindexBySource replaces the chunks that came from that file. In our test, running it twice left the same number of chunks, while a plain addDocuments() call added a second copy of every chunk.
Step 7: Require Human Approval for Refunds
This is the most important step. The refund tool checks its own inputs, so it refuses any amount above the order total, whatever the model asks for:
<?php
declare(strict_types=1);
namespace App\Tools;
use App\Database;
use InvalidArgumentException;
use NeuronAI\Tools\PropertyType;
use NeuronAI\Tools\Tool;
use NeuronAI\Tools\ToolProperty;
class IssueRefund extends Tool
{
protected string $name = 'issue_refund';
protected ?string $description = 'Refund all or part of an order. A staff member must approve every refund.';
public function __construct(private int $customerId) {}
protected function properties(): array
{
return [
new ToolProperty(name: 'order_id', type: PropertyType::INTEGER,
description: 'The order number', required: true),
new ToolProperty(name: 'amount', type: PropertyType::NUMBER,
description: 'Refund amount in dollars', required: true),
new ToolProperty(name: 'reason', type: PropertyType::STRING,
description: 'Why the customer is owed a refund', required: true),
];
}
public function __invoke(int $order_id, float $amount, string $reason): string
{
$db = Database::pdo();
$stmt = $db->prepare('SELECT total FROM orders WHERE id = ? AND customer_id = ?');
$stmt->execute([$order_id, $this->customerId]);
$total = $stmt->fetchColumn();
if ($total === false || $amount <= 0 || $amount > (float) $total) {
throw new InvalidArgumentException("Refund of {$amount} is not allowed for order {$order_id}.");
}
$db->prepare('INSERT INTO refunds (order_id, amount, reason) VALUES (?, ?, ?)')
->execute([$order_id, $amount, $reason]);
return "Refund of \${$amount} issued for order {$order_id}.";
}
}
The example stores amounts as floats to stay short. In production, store money as integer cents or a DECIMAL column.
Then the agent registers it with requireApproval(). Before the tool runs, Neuron pauses the run and saves it, and the customer request ends:
protected function tools(): array
{
return [
new GetOrder($this->customerId),
(new IssueRefund($this->customerId))->requireApproval(),
];
}
Why not just ask the customer to confirm in the chat? Because the model controls that conversation, and a customer can argue with a model. An approval step sits outside the model entirely: the tool cannot run until a person with staff access says yes.
A paused run must survive until a staff member decides, possibly hours later and on another server. So the agent saves runs with a persistence class, alongside the message store from step 4:
protected function persistence(): PersistenceInterface
{
return new FilePersistence(self::storage('runs'));
}
A small controller ties it together. The customer side reports that a refund is under review; the staff side lists pending refunds and submits a decision keyed by the tool call ID:
<?php
declare(strict_types=1);
namespace App\Http;
use App\SupportAgent;
use Closure;
use NeuronAI\Agent\Interrupt\Action;
use NeuronAI\Chat\Messages\UserMessage;
use NeuronAI\Exceptions\WorkflowException;
class SupportController
{
// Tests pass a factory that swaps in fake providers; production uses the real agent.
public function __construct(private ?Closure $makeAgent = null) {}
private function agent(int $customerId): SupportAgent
{
return $this->makeAgent ? ($this->makeAgent)($customerId) : SupportAgent::forCustomer($customerId);
}
// Customer side: send a message, get an answer or an "awaiting approval" status.
public function chat(int $customerId, string $message): array
{
$agent = $this->agent($customerId);
try {
$state = $agent->chat(new UserMessage($message));
} catch (WorkflowException $e) { // step budget hit: stop and hand off
error_log('[support-agent] ' . $e->getMessage());
$agent->archiveConversation();
return ['status' => 'handoff', 'reply' => 'I am passing this to a team member, who will reply soon.'];
}
if ($state->isInterrupted()) {
return ['status' => 'awaiting_approval',
'reply' => 'A team member is reviewing your refund. We will confirm shortly.'];
}
return ['status' => 'answered', 'reply' => $state->getMessage()?->getContent()];
}
// Staff side: list refunds waiting for a decision for one customer.
public function pending(int $customerId): array
{
return array_map(fn (Action $action) => [
'id' => $action->id, // the tool call ID to decide on
'tool' => $action->name,
'inputs' => $action->inputs, // order_id, amount, reason
], $this->agent($customerId)->pendingApprovals());
}
// Staff side: approve or reject, keyed by tool call ID, then let the agent finish.
public function decide(int $customerId, array $decisions): array
{
$state = $this->agent($customerId)->submitApprovalDecisions($decisions)->run();
return ['status' => $state->isInterrupted() ? 'awaiting_approval' : 'answered',
'reply' => $state->getMessage()?->getContent()];
}
}
In our test, the refund request paused with zero refunds recorded. A new agent object, as in a separate staff request, listed the pending refund, approved it, and only then was one refund recorded. A rejected refund recorded nothing, and the staff note reached the model so it could explain the decision.
Step 8: Add Guardrails Before Anything Else Ships
A model can loop: call a tool, misread the result and call it again, spending money each time. Neuron has controls for this, but its overall step budget is off by default. The forCustomer() method from step 4 sets four limits: a 20-step budget, at most three runs per tool, a 30,000-token context window and a tool error handler.
We tested each limit with a fake model that called the same tool 40 times in a row:
Two results matter most: first, the per-tool cap does not stop a run: Neuron tells the model the tool ran too many times, and the model can carry on. The step budget is the real stop: in our test it ended a loop of 40 queued tool calls after 8 model calls, by throwing a WorkflowException.
Second, a run stopped mid-loop leaves the saved conversation half-finished. In our test, the customer's next message then failed with an "Invalid message sequence" error. The fix is to archive the conversation when you hand off, which the controller does with this method:
public function archiveConversation(): void
{
$store = $this->messageStore();
$store->archive($this->getThreadId(), count($store->loadActive($this->getThreadId())));
}
Archived messages stay on disk for your support team, and the customer's next message starts a clean conversation. With that in place, the same test sent a new message after the handoff and got a normal answer.
Step 9: Test the Agent Without Paying for Model Calls
Neuron ships fakes for tests. FakeAIProvider replays the model responses you queue, including tool calls, so you can test the approval flow end to end with no API key and no cost:
<?php
declare(strict_types=1);
namespace Tests;
use App\Database;
use App\Http\SupportController;
use App\SupportAgent;
use NeuronAI\Chat\Messages\AssistantMessage;
use NeuronAI\Chat\Messages\ToolCallMessage;
use NeuronAI\RAG\VectorStore\MemoryVectorStore;
use NeuronAI\Testing\FakeAIProvider;
use NeuronAI\Testing\FakeEmbeddingsProvider;
use NeuronAI\Tools\ToolCall;
use PDO;
use PHPUnit\Framework\TestCase;
class SupportAgentTest extends TestCase
{
private FakeAIProvider $ai;
private SupportController $controller;
protected function setUp(): void
{
putenv('AGENT_STORAGE=' . sys_get_temp_dir() . '/agent-test-' . uniqid());
$pdo = new PDO('sqlite::memory:', options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);
$pdo->exec('CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INT, status TEXT, total REAL, delivered_at TEXT)');
$pdo->exec('CREATE TABLE refunds (id INTEGER PRIMARY KEY, order_id INT, amount REAL, reason TEXT)');
$pdo->exec("INSERT INTO orders VALUES (1042, 7, 'delivered', 89.00, '2026-10-20')");
Database::use($pdo);
$this->ai = new FakeAIProvider();
$this->controller = new SupportController(fn (int $id) => SupportAgent::forCustomer($id)
->setAiProvider($this->ai)
->setEmbeddingsProvider(new FakeEmbeddingsProvider())
->setVectorStore(new MemoryVectorStore()));
}
public function test_refund_waits_for_staff_approval(): void
{
$this->ai->addResponses(
new ToolCallMessage(null, [new ToolCall('issue_refund', 'call_1',
['order_id' => 1042, 'amount' => 20, 'reason' => 'Arrived damaged'])]),
new AssistantMessage('Your $20 refund for order 1042 is on its way.'),
);
$reply = $this->controller->chat(7, 'My order 1042 arrived damaged. Can I get $20 back?');
$this->assertSame('awaiting_approval', $reply['status']);
$this->assertSame(0, $this->refundCount()); // nothing paid yet
$pending = $this->controller->pending(7);
$this->assertSame('issue_refund', $pending[0]['tool']);
$reply = $this->controller->decide(7, [$pending[0]['id'] => 'approve']);
$this->assertSame('answered', $reply['status']);
$this->assertSame(1, $this->refundCount()); // paid after approval
}
private function refundCount(): int
{
return (int) Database::pdo()->query('SELECT COUNT(*) FROM refunds')->fetchColumn();
}
}
The controller accepts an optional factory, so the test can hand it an agent wired to fakes while production code uses the real one. Our full suite has nine tests like this and runs in under a second. Each one checks a behavior you would otherwise only find in production:
- A customer cannot see another customer's order, whatever the model asks for.
- A second request continues the same conversation.
- An invalid triage reply is retried until it passes validation.
- The return policy reaches the prompt when a customer asks about returns.
- A refund pauses, and only an approval records it; a rejection records nothing.
- A refund above the order total becomes a tool error, not a payment.
- A runaway loop hands off to a person, and the next message still works.
Step 10: Serve It Over HTTP
The endpoint stays thin. It takes the customer ID from the session, never from the request, checks the input and passes it to the controller:
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use App\Http\SupportController;
session_start();
header('Content-Type: application/json');
// The customer comes from your login session, never from the request body.
$customerId = (int) ($_SESSION['customer_id'] ?? 0);
if ($customerId === 0) {
http_response_code(401);
exit(json_encode(['error' => 'Sign in first.']));
}
$input = json_decode(file_get_contents('php://input') ?: '', true) ?? [];
$message = trim((string) ($input['message'] ?? ''));
if ($message === '' || mb_strlen($message) > 2000) {
http_response_code(422);
exit(json_encode(['error' => 'Send a message of 1 to 2,000 characters.']));
}
echo json_encode((new SupportController())->chat($customerId, $message));
Our test confirmed a 401 without a session and a 422 for an empty message. Staff endpoints for pending() and decide() follow the same pattern behind your admin login. The same structure works inside WordPress; our guide to custom WordPress chatbots shows how a chat front end connects to the AI behind it.
Most teams add streaming and queues next. For replies that appear word by word, Neuron's stream() method returns the answer in chunks you can forward to the browser. For slow, multi-tool tasks, run the agent from a queue worker and notify the customer when it finishes, so no web request waits on the model.
For reference, here is the complete agent class with every step in place:
<?php
declare(strict_types=1);
namespace App;
use App\Tools\GetOrder;
use App\Tools\IssueRefund;
use NeuronAI\Agent\SystemPrompt;
use NeuronAI\Chat\History\FileMessageStore;
use NeuronAI\Chat\History\MessageStoreInterface;
use NeuronAI\Providers\AIProviderInterface;
use NeuronAI\Providers\Anthropic\Anthropic;
use NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface;
use NeuronAI\RAG\Embeddings\VoyageEmbeddingsProvider;
use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\FileVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;
use NeuronAI\Workflow\Persistence\FilePersistence;
use NeuronAI\Workflow\Persistence\PersistenceInterface;
use Throwable;
class SupportAgent extends RAG
{
private int $customerId = 0;
public static function forCustomer(int $customerId): static
{
$agent = static::make();
$agent->customerId = $customerId;
return $agent
->setThreadId("customer-{$customerId}") // one conversation per customer
->setMaxSteps(20) // hard stop for runaway loops
->toolMaxRuns(3) // each tool at most 3 times per turn
->setContextWindow(30_000) // trim old history past 30k tokens
->toolErrorHandler(fn (Throwable $e) => 'Tool error: ' . $e->getMessage());
}
// After a handoff, archive the thread so the next message starts clean (archived messages stay on disk).
public function archiveConversation(): void
{
$store = $this->messageStore();
$store->archive($this->getThreadId(), count($store->loadActive($this->getThreadId())));
}
protected function provider(): AIProviderInterface
{
return new Anthropic(key: (string) getenv('ANTHROPIC_API_KEY'), model: 'claude-sonnet-5-5');
}
protected function instructions(): string
{
return (string) new SystemPrompt(
background: [
'You are the returns and refunds assistant for an online store.',
'You only discuss the signed-in customer\'s own orders.',
],
steps: [
'Look up the order with get_order before answering questions about it.',
'Answer policy questions only from the return policy context you are given.',
'Offer a refund only when the policy allows it, then call issue_refund.',
],
output: [
'Reply in two to four short sentences.',
'If you are unsure, say so and offer to pass the case to a person.',
],
);
}
protected function tools(): array
{
return [
new GetOrder($this->customerId),
(new IssueRefund($this->customerId))->requireApproval(),
];
}
protected function messageStore(): MessageStoreInterface
{
return new FileMessageStore(self::storage('chats'));
}
protected function persistence(): PersistenceInterface
{
return new FilePersistence(self::storage('runs'));
}
protected function embeddings(): EmbeddingsProviderInterface
{
return new VoyageEmbeddingsProvider(key: (string) getenv('VOYAGE_API_KEY'), model: 'voyage-3.5');
}
protected function vectorStore(): VectorStoreInterface
{
return new FileVectorStore(directory: self::storage('vectors'), topK: 4, name: 'return-policy');
}
private static function storage(string $dir): string
{
$path = rtrim((string) getenv('AGENT_STORAGE'), '/') . "/{$dir}";
is_dir($path) || mkdir($path, 0775, true);
return $path;
}
}
The Same PHP AI Agent in Laravel
In a Laravel app, the Laravel AI SDK gives you the same agent with less setup, because conversations live in your database and testing fakes are built in. Install it, publish its migrations and migrate:
composer require laravel/ai
php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
php artisan migrateTools are classes with a description, a handle method and a schema. The order lookup is scoped to the customer, as in Neuron:
<?php
namespace App\Ai\Tools;
use App\Models\User;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\DB;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
class LookupOrder implements Tool
{
public function __construct(private User $customer) {}
public function description(): string
{
return 'Look up one of the current customer\'s orders by its ID.';
}
public function handle(Request $request): string
{
$order = DB::table('orders')
->where('id', $request['order_id'])
->where('customer_id', $this->customer->id)
->first(['id', 'status', 'total', 'delivered_at']);
return $order ? json_encode($order) : 'No such order for this customer.';
}
public function schema(JsonSchema $schema): array
{
return ['order_id' => $schema->integer()->required()];
}
}
// The refund tool implements the Approvable contract, which makes it pause for a person by default:
<?php
namespace App\Ai\Tools;
use App\Models\User;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\DB;
use Laravel\Ai\Concerns\InteractsWithApprovals;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
class RefundOrder implements Approvable, Tool
{
use InteractsWithApprovals; // approvable tools pause for a person by default
public function __construct(private User $customer) {}
public function description(): string
{
return 'Refund all or part of an order. A staff member must approve every refund.';
}
public function handle(Request $request): string
{
$total = DB::table('orders')->where('id', $request['order_id'])
->where('customer_id', $this->customer->id)->value('total');
if ($total === null || $request['amount'] <= 0 || $request['amount'] > $total) {
return "Refund of {$request['amount']} is not allowed for order {$request['order_id']}.";
}
DB::table('refunds')->insert([
'order_id' => $request['order_id'], 'amount' => $request['amount'], 'reason' => $request['reason'],
]);
return "Refund of \${$request['amount']} issued for order {$request['order_id']}.";
}
public function schema(JsonSchema $schema): array
{
return [
'order_id' => $schema->integer()->required(),
'amount' => $schema->number()->required(),
'reason' => $schema->string()->required(),
];
}
}
The agent uses the RemembersConversations trait for memory and caps its loop with the MaxSteps attribute:
<?php
namespace App\Ai\Agents;
use App\Ai\Tools\LookupOrder;
use App\Ai\Tools\RefundOrder;
use App\Models\User;
use Laravel\Ai\Attributes\MaxSteps;
use Laravel\Ai\Attributes\Model;
use Laravel\Ai\Attributes\Provider;
use Laravel\Ai\Concerns\RemembersConversations;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\Conversational;
use Laravel\Ai\Contracts\HasTools;
use Laravel\Ai\Enums\Lab;
use Laravel\Ai\Promptable;
#[Provider(Lab::Anthropic)]
#[Model('claude-sonnet-5-5')]
#[MaxSteps(8)]
class ReturnsAgent implements Agent, Conversational, HasTools
{
use Promptable, RemembersConversations;
public function __construct(private User $customer) {}
public function instructions(): string
{
return 'You are the returns and refunds assistant for an online store. '
.'Look up orders with LookupOrder before answering. Refund only when the return policy allows it.';
}
public function tools(): iterable
{
return [new LookupOrder($this->customer), new RefundOrder($this->customer)];
}
}
//A refund request pauses and returns its pending approvals. Staff resume it later by continuing the conversation with a decision for each tool call:
use App\Ai\Agents\ReturnsAgent;
use Laravel\Ai\Approvals\Decision;
use Laravel\Ai\Approvals\Decisions;
// Customer turn (in a controller)
$user = $request->user();
$response = (new ReturnsAgent($user))->forUser($user)->prompt('Order 1042 arrived damaged. Can I get $20 back?');
if ($response->hasPendingApprovals()) {
// save $response->conversationId and show the refund in your staff queue
}
// Staff decision, in a later request
$approval = collect($response->pendingApprovals)->first();
$final = (new ReturnsAgent($user))
->continue($response->conversationId, as: $user)
->prompt(Decisions::from([$approval->id => Decision::approve()]));
Tests use the agent's own fake, with no HTTP calls at all:
ReturnsAgent::fake(['Order 1042 was delivered on October 20.']);
$response = (new ReturnsAgent($user))->forUser($user)->prompt('Where is order 1042?');
ReturnsAgent::assertPrompted('Where is order 1042?');
One cost detail we found while testing: RemembersConversations makes an extra model call to write a title for each new conversation, using the provider's cheapest model. If you do not show titles, turn it off by adding 'conversations' => ['generate_title' => false] to config/ai.php.
Pick this version when your app already runs on Laravel 12 or 13. You get database-backed conversations, Laravel's queues and its testing tools without extra wiring, and the approval flow works the same way as in the Neuron build.
Before Your PHP AI Agent Goes Live
Run through this list before real customers use the agent. Each item maps to code in this guide:
Plan for cost and visibility too. Every tool call is another round trip to the model, so the step budget is also a cost budget. In our test, a budget of 20 steps stopped a runaway loop after 8 model calls; the budget counts workflow steps, not model calls. The context window setting trims old history past 30,000 tokens, so long conversations do not grow the bill without limit.
For visibility, Neuron emits events for every model call and tool call. Subscribe a listener, such as its built-in LogListener, to send them to your logs, or connect an APM tool so you can trace why the agent did what it did.
Then test with real keys on a staging copy of your data. Fakes prove the plumbing; only real runs show whether the model follows your instructions and policy closely enough.
Guardrails Make a PHP AI Agent Ready for Customers
Writing the agent class itself is now quick. A framework like Neuron AI or the Laravel AI SDK gives you tools, memory, retrieval and approvals in the language your team already writes.
The work that takes time is everything around the model: tools that only see the right data, approval before money moves, a budget on every run, a clean handoff when things go wrong, and tests that prove it. That is the work we do for PHP teams.
Need a PHP AI Agent That Holds Up in Production?
We build AI agents for PHP teams with the parts demos skip: scoped tools, approval steps, step budgets, durable memory and tests, inside the app you already run.
• Agents in Neuron AI, the Laravel AI SDK or a Python service, whichever fits
• Human approval for every action that moves money or data
• Step budgets, tool limits and clean handoffs to your team
• Test suites with fake providers, so every deploy is checked
Frequently Asked Questions
Can you build AI agents in PHP without Python?
Yes. Neuron AI, the Laravel AI SDK and Symfony AI run entirely in PHP, with tool calling, memory and structured output. Python only becomes worth it when you need its specific libraries or an existing Python agent.
What is the best PHP AI agent framework?
For Laravel apps, the Laravel AI SDK. For any other PHP app, Neuron AI, which adds tool approval, workflows and test fakes. Symfony AI is promising but still in beta.
Does Neuron AI work outside Laravel?
Yes. Neuron AI is framework-agnostic and runs in plain PHP 8.1+, Symfony, WordPress or any Composer project. A separate Laravel package adds Laravel-specific helpers.
Can a PHP AI agent use MCP servers?
Yes. Neuron's MCP connector loads tools from any MCP server, and the Laravel AI SDK supports MCP tools too.
Can I run a PHP AI agent with a local model?
Yes. Neuron, the Laravel AI SDK and Prism support Ollama, so the agent can run against a model on your own hardware. Expect weaker tool calling from small local models than from frontier models.
