When working with experimental tools like Symfony AI, the pace of evolution is both an advantage and a challenge. Between versions v0.9.0 and v0.12.0, the component not only refined its API signatures and internal architecture, but also introduced essential tools for building truly resilient agents prepared for real-world unpredictability.
In previous articles, we built an e-commerce assistant with Vanilla JS and real SSE streaming with nested Tools. However, when an external provider experiences downtime, a model is deprecated from a catalog, or the conversation exceeds the context window, a generic catch (\Throwable $e) block is not enough to deliver a solid user experience.
In this article, before moving on to Series II, we cover:
- The change audit and safe upgrade to Symfony AI
v0.12.0. - Protection against in-place mutations when managing
MessageBag. - Granular exception handling (
ExceedContextSizeException,ModelNotFoundException,ServerException) for automatic recovery. - The importance of model choice for instruction following and pagination, and how to avoid prompt bloat.
Reminder: Symfony AI is in active development (currently at
v0.12.0). While the core contracts are mature, upgrading iteratively through phased releases lets you adopt resilience improvements without breaking existing code.
Resulting Architecture
Before diving into the details, here is the final state of the architecture after the migration:
flowchart TD
A["Usuario / Frontend JS"] -->|POST /api/chat SSE| B[ProductChatController]
subgraph Controller [Controlador y Resiliencia]
direction TB
B -->|Captura| E1[ExceedContextSizeException]
B -->|Captura| E2[ModelNotFoundException]
B -->|Captura| E3[ServerException]
end
B --> C[ProductChatService]
C -->|clona MessageBag| D["AgentInterface (v0.12.0)"]
D <-->|chat/completions| G["Groq API (GPT OSS 120B)"]
D -->|Tool calls| Tools
subgraph Tools ["Herramientas #[AsTool]"]
direction TB
T1[ProductSearchTool]
T2[ProductPriceTool]
T3[ProductCategoryTool]
end
Tools --> R[ProductRepository]
D -->|TextDelta SSE| B
B --> A
1. What Changed Between Symfony AI v0.9 and v0.12
Since these are minor version jumps in an experimental component, it is vital to review architectural changes in the agent lifecycle. These three changes are the most likely to break existing code:
A. In-Place Mutation of MessageBag (Since v0.10)
In earlier versions, the agent’s internal processors cloned the message bag. Starting in v0.10, the agent mutates the MessageBag in-place to inject tool calls (ToolCallMessage) and intermediate responses. If our service reuses the instance or inspects it later, we must be mindful of this behavior.
B. Automatic Tool Iteration Limit (maxToolCalls: 50)
Before v0.10, if a model entered a hallucination loop invoking tools indefinitely, the PHP process would run until timing out. Now it is capped by default at 50 iterations, throwing an exception if exceeded.
C. Flexibility in the AgentInterface::call() Signature (v0.12)
The signature was expanded to accept string|MessageBag|UserMessage, allowing simple agents to be invoked directly with text ($agent->call('Hello')), while retaining full compatibility when passing a structured MessageBag with history.
2. Protecting the Conversational Service (ProductChatService)
In our service, we build the conversation history from the Symfony session and convert it into a MessageBag.
To prevent the agent’s internal execution from altering the message object we just structured, we apply an explicit defensive practice: clone the MessageBag when invoking call(). Without cloning, the agent would mutate the original instance in-place, potentially corrupting the history you just built or leaking internal tool-call lifecycle messages into user messages in subsequent iterations.
// src/AI/ProductChatService.php
public function streamAsk(string $userQuestion, \Closure $onChunk): void
{
$session = $this->requestStack->getSession();
$history = $session->get('chat_history', []);
$history[] = ['role' => 'user', 'content' => $userQuestion];
$messages = $this->buildMessageBag($history);
// Invocamos el stream protegiendo el MessageBag original contra mutaciones
$result = $this->defaultAgent->call(clone $messages, ['stream' => true]);
$stream = $result->getContent();
$fullAnswer = '';
foreach ($stream as $delta) {
if ($delta instanceof \Symfony\AI\Platform\Result\Stream\Delta\TextDelta) {
$content = $delta->getText();
if ($content !== '') {
$fullAnswer .= $content;
$onChunk($content);
}
}
}
// Guardas de seguridad e inserción en historial...
$history[] = ['role' => 'assistant', 'content' => $fullAnswer];
// Mantenemos solo los últimos 10 mensajes (sliding window)
if (count($history) > 10) {
$history = array_slice($history, -10);
}
$session->set('chat_history', $history);
}
3. Controller Resilience with Granular Exceptions
One of the biggest improvements in Symfony AI v0.10+ is the typed exception hierarchy under the Symfony\AI\Platform\Exception namespace.
Instead of catching a blind error, we can now react based on the failure type:
// src/Controller/ProductChatController.php
namespace App\Controller;
use App\AI\ProductChatService;
use Symfony\AI\Platform\Exception\ExceedContextSizeException;
use Symfony\AI\Platform\Exception\ModelNotFoundException;
use Symfony\AI\Platform\Exception\ServerException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Attribute\Route;
class ProductChatController extends AbstractController
{
#[Route('/api/chat', methods: ['POST'])]
public function chat(Request $request, ProductChatService $chatService): Response
{
$body = json_decode($request->getContent(), true);
$question = trim(strip_tags($body['question'] ?? ''));
if (empty($question)) {
return $this->json(['error' => 'Question is required'], 400);
}
$response = new StreamedResponse(function () use ($chatService, $question, $request) {
try {
$chatService->streamAsk($question, function (string $token) {
echo "data: " . json_encode(['text' => $token], JSON_THROW_ON_ERROR) . "\n\n";
ob_flush();
flush();
});
echo "data: [DONE]\n\n";
ob_flush();
flush();
} catch (ExceedContextSizeException $e) {
// 1. Contexto saturado: purgamos la sesión para desbloquear al usuario
error_log("AI CONTEXT ERROR: " . $e->getMessage());
$request->getSession()->remove('chat_history');
echo "data: " . json_encode([
'error' => 'El historial es muy largo. Se ha reiniciado la conversación, por favor intenta de nuevo.'
]) . "\n\n";
ob_flush();
flush();
} catch (ModelNotFoundException $e) {
// 2. Modelo no disponible o retirado del catálogo
error_log("AI MODEL ERROR: " . $e->getMessage());
echo "data: " . json_encode([
'error' => 'El modelo de IA configurado no está disponible en este momento.'
]) . "\n\n";
ob_flush();
flush();
} catch (ServerException $e) {
// 3. Error 5xx transitorio del proveedor (Groq, OpenAI, etc.)
error_log("AI SERVER ERROR: " . $e->getMessage());
echo "data: " . json_encode([
'error' => 'El servicio de IA está temporalmente saturado. Intenta de nuevo en unos segundos.'
]) . "\n\n";
ob_flush();
flush();
} catch (\Throwable $e) {
// 4. Última línea de defensa
error_log("AI ERROR: " . $e->getMessage() . "\n" . $e->getTraceAsString());
$errorMsg = "Error inesperado: " . $e->getMessage();
echo "data: " . json_encode(['error' => $errorMsg]) . "\n\n";
ob_flush();
flush();
}
});
$response->headers->set('Content-Type', 'text/event-stream');
$response->headers->set('Cache-Control', 'no-cache');
$response->headers->set('X-Accel-Buffering', 'no');
$response->headers->set('Connection', 'keep-alive');
return $response;
}
}
What Do We Gain from This?
- Automatic session recovery: If a user sends massive inputs that exceed token limits (
ExceedContextSizeException), the session is automatically reset on the backend without trapping the user in an unrecoverable error loop. - Diagnostic clarity: We distinguish between transient infrastructure failures (503/504 via
ServerException) and configuration issues or model unavailability (ModelNotFoundException).
4. Production Lessons: Model Size vs. Prompt Engineering
During migration testing, we faced a common dilemma: why does a model sometimes skip categories, ignore pagination limits, or answer off-topic questions?
The Experiment with Smaller Models
When testing smaller models (such as ~27B parameter models), we observed two frequent behaviors:
- Unpaginated dumps: When asked for “all products,” instead of calling
categoriesfirst and awaiting instructions, it ran searches and dumped all results, bypassing the 3-items-per-page rule. - Topic drift (Off-topic): It answered general knowledge or geography questions instead of focusing on the store.
The Stay on Topic Rule
To correct topic drift, we tightened the System Prompt guidelines:
Message::forSystem(
"You are a helpful online store assistant. Reply ONLY in Spanish.\n\n" .
"AVAILABLE TOOLS:\n" .
"- 'categories': list available types.\n" .
"- 'search': lists products by category. Pass exact slug (telefono, portatil, auriculares, reloj). Page defaults to '1' ('2' for more).\n" .
"- 'price': gets the price of an SKU.\n\n" .
"RULES:\n" .
"1. Map user synonyms to exact slugs (e.g., 'laptops'->'portatil', 'relojes'->'reloj' or 'celulares'->'telefono').\n" .
"2. NO HALLUCINATION: DO NOT invoke unlisted tools (like order/checkout). Never invent products or SKUs.\n" .
"3. NO SALES: You cannot process orders or take payments; decline gracefully.\n" .
"4. STAY ON TOPIC: Only answer questions about the store, its products and categories. For unrelated questions, politely redirect the user to the store's offerings."
The Balance: Avoid Prompt Bloat
It is tempting to add dozens of rules to the prompt to patch every flaw in a smaller model. However, in tool-calling architectures, the model’s instruction-following capability is decisive.
When switching to a model with stronger reasoning capabilities on Groq, such as GPT OSS 120B (openai/gpt-oss-120b), the agent executed the workflow with pinpoint precision:
# config/packages/ai.yaml
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'
supports_completions: true
supports_embeddings: true
completions_path: '/v1/chat/completions'
embeddings_path: '/v1/embeddings'
agent:
default:
platform: 'ai.platform.generic.groq'
model: 'openai/gpt-oss-120b'
tools:
services:
- { service: 'App\AI\Tool\ProductSearchTool' }
- { service: 'App\AI\Tool\ProductPriceTool' }
- { service: 'App\AI\Tool\ProductCategoryTool' }
Observed Results:
- OK – General inquiry -> Queries
categoriesand displays the 4 available categories. - OK – Product listing request -> Displays exactly 3 products (Page 1) and prompts for Page 2.
- OK – “Page 2” request -> Fetches remaining items using real pagination.
- OK – Contextual deduction -> Identifies the cheapest product by analyzing the catalog.
- OK – Graceful rejection -> Declines purchase orders and off-topic questions.
What Benefits Did the Upgrade Bring?
Migrating to Symfony AI v0.12.0 shows that the framework is steadily maturing:
- Typed exceptions let you replace brittle error handling with an automatic recovery experience for edge cases like context overflow or provider outages.
- Decoupled tools via
#[AsTool]remain the strongest and most elegant foundation: the tools did not require a single line of modification during the entire migration. - Choosing the right model for Tool Calling reduces prompt complexity and ensures business rules (pagination, language, limits) are fulfilled deterministically.
In the next series, we will explore advanced features: Structured Output with typed DTOs, deep debugging with the Symfony AI Profiler, and Provider Failover strategies.
Keep coding.