The PHP ecosystem has taken a significant leap forward with the arrival of Symfony AI, a set of official components that allows you to integrate Large Language Models (LLMs) directly into your Symfony applications—without leaving the PHP environment or sacrificing the clean architecture we love.
Until recently, if you wanted to work with AI in a Symfony project, the most common approach was delegating that part to a Python or Node.js microservice. Symfony AI changes that: it offers a solid, native alternative for many real-world use cases. It doesn’t aim to replace the Python ecosystem (especially in research, fine-tuning, or highly advanced tasks), but it does allow you to build intelligent features inside your Symfony application while keeping everything in the same stack.
Important Note: At the time of publishing this article, Symfony AI is in an experimental state (latest stable version:
v0.6.0). This means the API may change and is not covered by Symfony’s backward compatibility promise. You can use it in production, but keep that caveat in mind.
1. What Is Symfony AI and What Problem Does It Solve?
Symfony AI is not just a wrapper around the OpenAI API. It is an abstraction layer designed around the Symfony philosophy: decoupling, extensibility, and deep integration with the Service Container.
Its core components are:
- Platform: a unified interface to connect to over 25 model providers (OpenAI, Anthropic, Google Gemini, Azure, Mistral, Ollama, etc.).
- Agent: the framework for creating agents that reason, use tools, and handle complex workflows.
- Chat: a high-level API to manage conversations with history.
- Store: an abstraction over vector databases to implement RAG.
- AI Bundle: the integration of all the above with Symfony’s service container.
Thanks to this, you can switch providers (for example, from OpenAI to Anthropic) simply by changing the configuration, without touching a single line of your business logic.
2. The Four Pillars in Detail
Platform – Connecting with Models
The Platform component handles communication with different AI providers. It offers a common interface (PlatformInterface) that abstracts away the differences between their individual APIs.
You can send it a MessageBag containing system and user messages, and receive a structured response. Furthermore, it supports streaming via Server-Sent Events, allowing you to display responses in real time to the user (a topic we will cover in depth in the next article).
Agent – The Logic Core
The Agent is the brain of the system. It receives messages, decides whether it needs to invoke any tools, runs the necessary cycles, and returns the final response. It is the most comprehensive component: supporting memory, input and output processors, subagents, tool fault tolerance, and much more.
Tools – Taking Action in Your Code
This is, in my opinion, one of the most powerful concepts in Symfony AI.
Tools are standard PHP classes decorated with the #[AsTool] attribute. The agent can call them automatically whenever it determines they are needed.
The best part is that Symfony AI automatically generates each tool’s JSON schema from parameter types and docblock comments. You don’t have to write cumbersome manual schemas or descriptions.
Store – Long-Term Memory
The Store component is an abstraction over vector databases (ChromaDB, Pinecone, Weaviate, pgvector, etc.). It is the foundational building block for implementing RAG (Retrieval-Augmented Generation): before answering, the agent retrieves the most relevant chunks from your own documentation or knowledge base and includes them in the conversation context.
3. When to Use Symfony AI (and When Not To)
As with any tool, it is important to know where it fits and where it doesn’t.
Cases where it works great:
- Conversational assistants integrated into an existing Symfony application.
- Features that need access to internal data (database, internal APIs) during the conversation.
- Semantic search or Q&A systems over internal documentation.
- Automated workflows where the LLM orchestrates actions across your own system.
Cases where it might not be the best choice:
- Research, fine-tuning, or model training (Python is still king there).
- Highly specific integrations with provider SDKs not yet covered by Symfony AI.
- Projects where API stability is mission-critical and you cannot afford potential breaking changes (remember the bundle is still experimental).
4. Practical Example: A Product Assistant
Let’s build a simple yet realistic assistant: one that can answer questions about products by querying real data from our application.
Step 1: Installation
composer require symfony/ai-bundle
Step 2: Configuration
# config/packages/ai.yaml
ai:
platform:
openai:
api_key: '%env(OPENAI_API_KEY)%'
agent:
default:
model: 'gpt-4o-mini'
The bundle automatically registers the default agent under the alias AgentInterface $defaultAgent.
Don’t have access to a paid API? No problem. Symfony AI supports several free or zero-cost options, and best of all, your application code doesn’t change at all. You only modify the provider configuration.
Option A: Ollama — Local Models at Zero Cost
Ollama lets you run models directly on your machine. It is ideal for local development: no API keys, no rate limits, and zero network latency.
# Bridge oficial
composer require symfony/ai-ollama-platform
# Descargar un modelo (fuera de Symfony)
ollama pull llama3.2
# config/packages/ai.yaml
ai:
platform:
ollama:
host_url: '%env(OLLAMA_HOST_URL)%'
agent:
default:
model: 'llama3.2'
# .env.local
OLLAMA_HOST_URL=http://localhost:11434
It requires a machine with enough RAM (a minimum of 8 GB is recommended for 7B models), but for development and learning, it’s fantastic.
Option B: Google Gemini — Generous Free Tier
Google Gemini provides a very usable free tier (gemini-1.5-flash allows around 1,500 free requests per day). No credit card required.
ai:
platform:
gemini:
api_key: '%env(GEMINI_API_KEY)%'
agent:
default:
model: 'gemini-1.5-flash'
You can get the key for free at aistudio.google.com.
Option C: OpenRouter
A unified proxy to many models. Useful for testing specific options, though its free tier tends to saturate quickly.
Option D: Groq — Blazing Fast and Free
If you are looking for the current best combination of speed + tool calling for free, Groq is hard to beat. It runs on specialized LPU chips.
ai:
platform:
generic:
groq:
base_url: 'https://api.groq.com/openai'
api_key: '%env(GROQ_API_KEY)%'
model_catalog: 'ai.platform.model_catalog.generic.fallback'
agent:
default:
platform: 'ai.platform.generic.groq'
model: 'llama-3.3-70b-versatile'
Note on the Model Catalog (Generic Bridge):
When using the generic bridge, Symfony AI attempts to validate the model against its internal catalog. If it doesn’t find it, it fails. The solution is to register a wildcard catalog:
# config/services.yaml
services:
ai.platform.model_catalog.generic.fallback:
class: Symfony\AI\Platform\Bridge\Generic\FallbackModelCatalog
Summary of Free and Paid Options:
| Option | Cost | Tool Calling | Best For |
|---|---|---|---|
| OpenAI (gpt-4o-mini) | Paid (~$0.15/1M tokens) | ✅ Yes | Production |
| Groq (llama-3.3-70b) | Free (LPU) | ✅ Yes | Development / Fast agents |
| Ollama (llama3.2) | Free (local) | ✅ Yes | Local and private development |
| Google Gemini | Free (up to daily limit) | ✅ Yes | Small projects |
Note on Tool Calling: Not all models handle it well. On Ollama and Groq, opt for models like
llama-3.3-70bormistral-nemo. Very small models often fail to format tool calls properly.
Step 3: Create a Tool
<?php
namespace App\AI\Tool;
use Symfony\AI\Agent\Toolbox\Attribute\AsTool;
#[AsTool(
name: 'product_price',
description: 'Returns the current price of a product given its SKU',
)]
final class ProductPriceTool
{
public function __construct(
private readonly ProductRepository $productRepository,
) {}
/**
* @param string $sku The product SKU identifier
*/
public function __invoke(string $sku): string
{
$product = $this->productRepository->findBySku($sku);
if ($product === null) {
return sprintf('No product found with SKU "%s".', $sku);
}
return sprintf(
'The product "%s" (SKU: %s) costs %.2f EUR.',
$product->getName(),
$sku,
$product->getPrice(),
);
}
}
Symfony automatically generates the JSON schema from the parameter type and docblock. You can inject any Symfony service (repositories, HTTP clients, etc.).
Step 4: Create the Chat Service
<?php
namespace App\AI;
use Symfony\AI\Agent\AgentInterface;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
final readonly class ProductChatService
{
public function __construct(
private AgentInterface $defaultAgent,
) {}
public function ask(string $userQuestion): string
{
$messages = new MessageBag(
Message::forSystem(
'You are a helpful assistant for an online store. ' .
'Answer questions about products concisely and accurately. ' .
'If you need to check a price or product details, use the available tools.'
),
Message::ofUser($userQuestion),
);
$result = $this->defaultAgent->call($messages);
return $result->getContent();
}
}
Step 5: Use It from a Controller
#[Route('/api/chat', methods: ['POST'])]
public function chat(Request $request, ProductChatService $chatService): JsonResponse
{
$body = json_decode($request->getContent(), true);
$question = $body['question'] ?? '';
if (empty($question)) {
return $this->json(['error' => 'Question is required'], 400);
}
$answer = $chatService->ask($question);
return $this->json(['answer' => $answer]);
}
5. What Happens Internally
When the user asks something like “How much does the product with SKU laptop-pro-1 cost?”, the flow is as follows:
- The
Agentsends the message to the model along with the schema of the available tools. - The model determines that it needs external information and replies requesting a tool call to
product_pricewithsku: "laptop-pro-1". - The
AgentProcessorrunsProductPriceTool::__invoke()and appends the result to the context. - The model generates the final response using that real data.
This cycle can repeat multiple times within a single request if necessary. The agent handles it automatically.
6. Observability and Testing
Symfony Profiler: The bundle adds a dedicated panel in the Profiler where you can inspect the prompts sent, the responses received, and token consumption. It’s an invaluable tool during development.
Testing: Symfony AI includes InMemoryPlatform, a mock implementation that lets you test your logic without making any real API calls:
use Symfony\AI\Platform\Test\InMemoryPlatform;
$platform = new InMemoryPlatform('The product costs 999.99 EUR.');
$agent = new Agent($platform, $model);
Wrapping Up: What We Built and What’s Next
Symfony AI fills an important gap in the PHP ecosystem: it gives us a structured, decoupled, and well-integrated way to incorporate artificial intelligence into Symfony applications.
It is not a silver bullet, but for conversational assistants, RAG, internal workflow automation, or any feature requiring the combination of LLMs with your data and business logic, it provides a solid foundation that is a pleasure to work with.
The example we explored in this article works as intended, but it has one clear limitation: it returns the complete response all at once. If the model takes several seconds, the user experience is far from ideal.
You can clone and test the full code of the example developed in this article in the following repository:
Example repository: https://github.com/jure-ve/symfony-ai-product-agent
In the next article, we’ll look at how to solve exactly that: we’ll build real-time chat with streaming via Server-Sent Events, a JavaScript frontend interface to consume the stream in the browser, and conversation history management using Symfony AI’s Chat component.