Symfony AI in Practice (III): Real Streaming with SSE and Nested Tools Management

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

Nothing kills user experience in an AI application faster than having to wait.

You send your prompt, the screen stays blank, and several agonizing seconds pass until suddenly the entire response pops up all at once. It is frustrating.

In the previous article, we built a conversational assistant that maintained history and could use tools. However, the user still had to wait for the model to generate the entire response (including tool execution) before seeing a single word on screen.

In this third part, we are going to fix that once and for all: we will implement real-time streaming using Server-Sent Events (SSE).

Important note: Symfony AI is still in preview (v0.7.0). The API, class names, and behavior may change significantly before a stable release. The code you see here reflects the current state of the component, and I will update it as it evolves. Always consult the official documentation before using it in production.

1. The Backend: StreamedResponse and SSE

The idea is quite simple: instead of computing the entire response and sending it all at once, we open an HTTP channel that stays alive and write to it as the model generates text.

Symfony makes this easy with the StreamedResponse class. Instead of returning a standard Response, we pass it a callback that writes directly to the output buffer while the model works.

The Chat Controller

// src/Controller/ProductChatController.php

public function chat(Request $request, ProductChatService $chatService): Response
{
    $body = json_decode($request->getContent(), true);
    $question = trim(strip_tags($body['question'] ?? ''));

    $response = new StreamedResponse(function () use ($chatService, $question) {
        try {
            $chatService->streamAsk($question, function (string $token) {
                // Enviamos cada trozo en formato SSE
                echo "data: " . json_encode(['text' => $token], JSON_THROW_ON_ERROR) . "\n\n";
                ob_flush();
                flush();
            });

            // Indicamos al cliente que el stream ha terminado
            echo "data: [DONE]\n\n";
            ob_flush();
            flush();
        } catch (\Throwable $e) {
            echo "data: " . json_encode(['error' => 'Error: ' . $e->getMessage()]) . "\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'); // Muy importante
    $response->headers->set('Connection', 'keep-alive');

    return $response;
}

Why X-Accel-Buffering: no?
By default, Nginx accumulates response chunks in its internal buffer to optimize bandwidth. In a streaming context, this is counterproductive: tokens would arrive in batches rather than one by one, breaking the real-time feel. This header tells Nginx to disable buffering for this specific response.

2. The Service: Consuming the Symfony AI Stream

The core of the solution lives in ProductChatService. Here, we invoke the agent with the option stream => true.

The Challenge of Nested Tools

Think of the stream as a conveyor belt of tokens. When the model decides it needs to run a tool (such as searching for products), the belt does not abruptly stop. Internally, Symfony AI creates a new “belt” that captures the tool’s output and merges it with the original one.

From our code, this entire process is transparent. The framework handles the recursion for us.

Technically, $result->getContent() returns a generator that, via yield from, chains all streams (initial, tool execution, and final response) into a single linear sequence of Delta objects.

// 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);
    $result = $this->defaultAgent->call($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 !== '') { // Importante: !== '' en lugar de empty()
                $fullAnswer .= $content;
                $onChunk($content);
            }
        }
    }

    // Fallback por si el modelo no generó texto (ej. error silencioso tras una Tool)
    if (trim($fullAnswer) === '') {
        $fullAnswer = 'Lo siento, hubo un problema procesando tu solicitud.';
        $onChunk($fullAnswer);
    }

    $history[] = ['role' => 'assistant', 'content' => $fullAnswer];
    // Guardamos solo los últimos 10 mensajes
    $session->set('chat_history', array_slice($history, -10));
}

3. The Frontend: ReadableStream and Professional UX

On the client side, we can no longer use a traditional fetch that waits for the entire response to complete. Now we read the response body in real time using body.getReader().

Why not use EventSource?

The native EventSource API is designed for SSE, but it only supports GET requests. Since we need to send the prompt via POST (along with potential conversation history), we implement our own SSE parser using fetch. The additional complexity is minimal, and the control we gain is well worth it.

Processing the Stream in Vanilla JavaScript

// templates/chat/demo.html.twig

async function sendMessage() {
    const text = inputPrompt.value.trim();
    if (!text) return;

    // ... lógica de UI (spinner, deshabilitar input, etc.)

    const response = await fetch('/api/chat', { ... });

    // Limpiamos el indicador de carga en cuanto llega el primer chunk
    aiBubble.innerHTML = '';

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        let boundary = buffer.indexOf('\n\n');

        while (boundary !== -1) {
            const chunk = buffer.slice(0, boundary);
            buffer = buffer.slice(boundary + 2);

            if (chunk.startsWith('data: ')) {
                const dataStr = chunk.slice(6);
                if (dataStr === '[DONE]') break;

                try {
                    const data = JSON.parse(dataStr);
                    if (data.text) {
                        aiBubble.innerHTML += escapeHTML(data.text).replace(/\n/g, '<br>');
                        chatContainer.scrollTop = chatContainer.scrollHeight;
                    }
                } catch (e) {}
            }
            boundary = buffer.indexOf('\n\n');
        }
    }
}

Loading Indicator (Typing Indicator)

To keep everything feeling responsive, we display an animated spinner right after sending the message. This spinner disappears automatically as soon as the first actual token arrives:

.typing-indicator span {
    height: 8px;
    width: 8px;
    background: #555;
    display: inline-block;
    border-radius: 50%;
    animation: bounce 1.3s infinite;
}

@keyframes bounce {
    0%, 60%, 100% { transform: translateY(0); }
    30%           { transform: translateY(-4px); }
}

4. Choose Your Model Wisely: Size Isn’t Everything

During development, we tested several models available on Groq to find the best balance between speed, cost, and real tool-calling capabilities.

Real-World Comparison

ModelBehavior with ToolsResult
Qwen 2.5 (32B)Excellent. Respects pagination, context, and is very accurateWINNER
Llama 3.3 (70B)Inconsistent. Hallucinates formats and gets stuck in loopsDiscarded
GPT-OSS (20B)Acceptable, but less accurate with paginationAlternative

Why Did Qwen 2.5 (32B) Win?

Even though Llama 3.3 is considerably larger (70B), it proved much less disciplined with Symfony AI’s tool system. In multiple tests, it attempted to write function calls directly into the output text rather than using the proper channel, causing internal code leaks to the user (a severe bug in production).

Qwen 2.5 (32B), on the other hand, handles the tool API remarkably well. It was the only model that correctly managed pagination (showing only 3 products and offering to show more in the next turn) without losing the context of the conversation.

Additionally, it features an impressive proactive self-correction capability: if it detected that it had only inspected the first page of results, it automatically invoked the tool again to check subsequent pages without the user having to ask. That level of reasoning, paired with a very natural use of Markdown, made it the clear choice.

Practical takeaway: In AI agents, what matters most is not how many parameters a model has, but how well it is optimized for Tool Use. That is the difference between a chat that merely looks smart and one that actually functions as a solid application.

5. Lessons Learned

Here are the “gotchas” that cost us time and will hopefully save yours:

  1. The Nginx buffer: The X-Accel-Buffering: no header is not optional. Without it, streaming works flawlessly locally, but fails silently in production.
  2. The danger of empty() in PHP: empty("0") evaluates to true. If your AI responds with numbers (such as “0 products found”), that response can vanish. Always use strict comparisons (!== '').
  3. Stream recursion is transparent: Symfony AI handles the tool → response cycle internally. You do not need manual loops; running a foreach over getContent() already yields the clean, final sequence.
  4. Clean the history: Make sure to store only the assistant’s final text. Avoid persisting tool calls or intermediate fragments that the model might have emitted.

If you want to see how everything fits together in a real project, check out the full repository: https://github.com/jure-ve/symfony-ai-product-agent

There you will find the complete implementation of the controller, service, frontend, and agent configuration.

Are We Done Here?

Almost. Implementing true streaming with Symfony AI turns out to be much cleaner than it seems once you understand how the framework handles nested tools. The service remains elegant: just a single foreach over the tokens.

But that is not the end of the story.

The most important lesson from this entire series has not been technical, but architectural: choosing the right model is just as crucial as writing good code. A model poorly aligned with Tool Use can dismantle an otherwise spotless architecture. And that is something no tutorial tells you until you experience it firsthand in your own tests.

Are you testing Symfony AI in any projects? Which models have worked best (or worst) for you with tools? Do you have any questions about the implementation?

Let me know in the comments. I’m very interested to hear what combinations other developers are using—often, the best questions become the topic for the next article in the series.


This article is part of the Symfony AI in Practice series. If you landed directly here, I recommend starting with the first article. All sample code for this series can be found in the symfony-ai-product-agent repository.