Yes, you can build AI agents in PHP. The most direct route is a framework package, and Laravel ships a first-party AI SDK built for this job. You can also call a model provider’s HTTP API yourself or use a framework-neutral library. Whichever route you pick, an agent works the same way: a model, instructions, and tools your code controls.
Key takeaways
- An AI agent is a model, instructions, and tools, run in a loop until it can answer.
- PHP developers can call provider APIs directly, use a framework-neutral library, or use a framework package.
- Tool input must be validated and scoped to the current user before it touches your database.
- Background jobs keep slow model calls out of the web request.
- Faked provider responses let PHPUnit and Pest tests run without live API calls.
What is an AI agent?
An AI agent is a language model that can ask your code to do things. It reads a prompt and may request one of your PHP functions. Your code runs it and returns the result. The model repeats this until it can answer.
Four terms come up in every agent project:
- Instructions: The system prompt that sets the agent’s role and limits.
- Tool calling: The model asks your code to run a named function with arguments it fills in.
- Structured output: The reply is forced into a fixed schema, such as JSON with set fields.
- Provider: The company hosting the model, such as OpenAI, Anthropic, or Google.
Why use an SDK instead of raw API calls?
An SDK runs the tool-call loop and parses responses for you. Hand-rolled HTTP clients tie you to one provider’s request format. They also break when a provider changes how it formats tool calls. Your code fills up with parsing logic that has nothing to do with your product.
A good SDK gives you one API across providers, so switching models is a config change, not a rewrite. Developers coming from TypeScript will know this idea from the Vercel AI SDK.
Three ways to build an agent in PHP
The right approach depends on the stack you run. For most teams, a framework package gets you to a working agent with the least code.
- Use a framework package. If you run Laravel, start with its AI SDK. It wraps several model providers behind one API and plugs into Laravel’s service container, config, and queues. Your agents reuse the auth, database, and job setup you already have, and switching providers is a config change. Symfony teams have a comparable option in Symfony AI, a set of components with a dedicated Agent component, currently marked experimental.
- Use a framework-neutral library. Community packages, such as
openai-php/client, wrap one or more provider APIs for any PHP project. Setup is a Composer install. Provider support, tool-calling features, and release pace depend on each maintainer. Pick this for plain PHP projects or frameworks without an official AI package. - Call the provider’s HTTP API directly. You send requests with Guzzle or any HTTP client and write the tool-call loop yourself. You get full control and no extra dependencies. You also own every line of parsing, and switching providers means rewriting that code. Pick this when you need one provider, a small feature, or behavior no library supports.
Whichever you pick, check the package’s current docs before you start. AI libraries in PHP are young, and method names change between releases.
How to build your first agent
The steps are the same in any PHP project. The example is a support assistant that answers order questions from a MySQL orders table.
- Store your API key in the environment. Put it in
.envor your server’s environment, never in code or Git. A key pushed to a public repository gets scraped, and you pay for whatever it runs up. - Write the instructions. Keep them short and specific: “You answer order questions for a store. Be brief. Never guess an order status.”
- Describe a tool. Give the model a name, a one-line description, and a JSON schema for the arguments.
- Write the tool handler. This PHP function receives the model’s arguments, validates them, and runs the query.
- Run the loop. Send the prompt and tool list, run any tool the model requests, return the result, and repeat until the model answers. An SDK handles this step for you.
A tool definition is a plain array of name, description, and schema:
$tools = [[
'name' => 'order_status',
'description' => 'Look up the status of one order by ID.',
'input_schema' => [ // key name varies by provider
'type' => 'object',
'properties' => ['order_id' => ['type' => 'integer']],
'required' => ['order_id'],
],
]];
The model reads the description to decide when to call the tool. It then fills in order_id from the user’s question.
The handler validates the argument and scopes the query to the signed-in user:
function orderStatus(array $args, int $userId, PDO $db): string
{
$orderId = filter_var($args['order_id'] ?? null, FILTER_VALIDATE_INT);
if ($orderId === false) {
return 'Invalid order ID.';
}
$stmt = $db->prepare(
'SELECT id, status FROM orders WHERE id = ? AND user_id = ?'
);
$stmt->execute([$orderId, $userId]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);
return $order
? "Order {$order['id']}: {$order['status']}"
: 'No matching order.';
}
Ask “Where is order 1042?” and the model requests order_status with order_id: 1042. Your code returns the status, and the model writes the answer.
Why every tool call needs scoping
The user_id = ? condition is the check that matters most. Without it, any user can ask for any order ID and read another customer’s data. Your code supplies the user ID from the session, never from the model.
Prompt injection makes this urgent. A user can type text that pushes the model to request data it shouldn’t see. The model can’t enforce permissions, so your tool handlers must.
Treat model output like user input:
- Validate every argument against the type and range you expect.
- Return only the fields the answer needs, not whole database rows.
- Validate structured output against its schema before you store or act on it.
- Give tools read-only access unless a write is the tool’s whole purpose.
Running agents in production
- Control cost. Providers bill by tokens, and every tool call adds tokens to the conversation. Cap the number of steps per run so a tool loop can’t spin indefinitely. Keep tool output small, set a spend limit in your provider dashboard, and log token use per request.
- Move model calls to background jobs. A model call can take several seconds, and a multi-step agent run takes longer. Running it inside a web request ties up a worker and risks timeouts. Push it to a queue instead: Laravel queues, Symfony Messenger, or a standalone worker. Queues also give you retries and rate limits in one place.
- Log what the agent did. Record each prompt, tool call, and tool result. When an agent gives a wrong answer, the log shows whether the model, the tool, or the data caused it.
- Test without a live provider. Fake the provider’s response in your PHPUnit or Pest tests. The test then checks your tool handlers and routes with no network calls and no spend. Mock the HTTP client if you call the API directly; most SDKs and libraries ship a fake or testing helper.
Frequently asked questions
Can I build an AI agent in plain PHP without a framework?
Yes. Call the provider’s HTTP API with any HTTP client, or use a framework-neutral library. You write the tool-call loop yourself or let the library run it.
How much does it cost to run an AI agent?
Cost depends on the provider and model. Providers bill by tokens, and each tool call adds tokens to the conversation. Small tool output, a cap on steps per run, and a provider spend limit keep the bill predictable.
Can I use Laravel’s AI SDK in Symfony or plain PHP?
No. It relies on Laravel’s service container, config, and queues. In Symfony, look at the Symfony AI components. In plain PHP, use a framework-neutral library or the provider’s API.
How do I stream agent responses to a React or Vue front end?
Streaming sends the reply in chunks as the model produces it. Return a streamed response from your PHP route, then read it in the browser with fetch or EventSource. Check your SDK’s docs for its streaming methods.
Which PHP version do I need?
Each package sets its own minimum. For example, symfony/ai-agent requires PHP 8.2 or later. Check the package’s Composer requirements before you install.
Next step
Pick the approach that matches your stack; on Laravel, that means starting with its AI SDK. Build one agent with one scoped tool, and write a test that fakes the provider response before you connect a live key.

Ryan Goose, a seasoned PHP developer and tech enthusiast, brings a wealth of knowledge in web technologies. With a passion for coding and a knack for simplifying complex concepts, Ryan’s articles are a treasure trove for both budding and experienced PHP developers.

