In the previous article, we built a basic agent that could only do one thing: check a product’s price given its SKU. It was useful, but very limited.
In this second part, we turn it into a real conversational assistant: it can now search products by category, maintain conversation context, and respond naturally in Spanish, just as if it were helping a real customer.
The main changes compared to the first part are:
- Three coordinated tools: text/category search, price lookup by SKU, and listing available categories.
- Persistent conversation history across requests, backed by Symfony’s HTTP session.
- Expanded catalog with 20 products across 4 categories, featuring normalized slug-based search.
- Full chat interface built 100% with Vanilla JS and Twig, without frontend frameworks.
All updated code is available in the project repository.
Update to v0.7.0: While preparing this article, Symfony released version 0.7.0 of the AI Bundle. I updated the entire project and we benefited from several key fixes:
- Generic Bridge fix (
#1876): fixes factory arguments for the generic platform. If you were using Groq (or other compatible providers) via the generic bridge in v0.6.0 and ran into initialization errors, this fix resolves it without changing your configuration.- Profiler improvements (
#1894,#1748): the AI panel no longer breaks when the response isn’t plain text, and duplicate entries in the tool list are gone. Much more reliable for debugging during development.- Ollama streaming fix (
#1827): switches internal protocol from SSE to NDJSON, fixing streaming issues with Ollama (the free local alternative we recommended in part one).Remember that Symfony AI remains experimental without backwards compatibility guarantees. Always check the official documentation before upgrading.
Note: This article builds on top of the code from the previous article. Here I only show the most relevant snippets for the changes and additions. The complete code is in the repository.
About streaming: In the first part, we promised a real-time chat with Server-Sent Events. We eventually decided to dedicate this article to solidifying conversational foundations (history, multiple tools, and a decent UI) to avoid cramming too much at once. Real streaming will take center stage in the next article.
1. From One Tool to Three: Coordinating Tools
The Single-Tool Agent Problem
The agent from part one had a clear limitation: it could only respond if the user knew the product’s exact SKU. Common questions like “what laptops do you have?” or “which headphones do you recommend?” left it completely speechless, unable to answer.
To solve this, we added two new tools and improved the existing one.
The Three Tools
ProductSearchTool: Searches products by category (using the slug) and returns paginated results. We limit it to 3 products per page so model responses don’t run endlessly. The page parameter allows the agent to request more results in subsequent turns if needed.
#[AsTool(
name: 'search',
description: 'Searches products by category slug. Returns up to 3 products per page.',
)]
final class ProductSearchTool
{
/**
* @param string $category Category slug (e.g. "telefono", "portatil")
* @param string $page Page number for pagination (default: "1")
*/
public function __invoke(string $category, string $page = '1'): string
{
$pageInt = max(1, (int) $page);
$products = $this->productRepository->searchByCategory(
$category, 3, ($pageInt - 1) * 3
);
if (empty($products)) {
return sprintf('No se encontraron productos en "%s" (pág %d).', $category, $pageInt);
}
$result = sprintf('Categoría "%s" — Página %d:' . "\n", $category, $pageInt);
foreach ($products as $product) {
$result .= sprintf("- %s (SKU: %s) — %.2f EUR\n",
$product->getName(), $product->getSku(), $product->getPrice()
);
}
return $result;
}
}
ProductPriceTool: The same pricing tool from the previous article, but now with the short name price so the prompt can reference it easily.
ProductCategoryTool: Returns the list of available category slugs. It’s key: the agent must use it first to know which categories it can query before attempting a search.
#[AsTool(
name: 'categories',
description: 'Returns the list of available product categories in the store.',
)]
final class ProductCategoryTool
{
public function __invoke(string $_ = ''): string
{
$categories = $this->productRepository->getCategories();
return 'The available product categories are: ' . implode(', ', $categories);
}
}
Registering the Tools
Thanks to autoconfiguration (default behavior), classes with #[AsTool] are registered automatically. If you want to bind them explicitly to a specific agent, you can do so in config/packages/ai.yaml:
ai:
agent:
default:
platform: 'ai.platform.generic.groq'
model: 'llama-3.3-70b-versatile'
tools:
services:
- { service: 'App\AI\Tool\ProductSearchTool' }
- { service: 'App\AI\Tool\ProductPriceTool' }
- { service: 'App\AI\Tool\ProductCategoryTool' }
The System Prompt: More Important Than It Looks
When moving from one tool to three, the model needs much clearer instructions to decide which one to use at any given moment. A good system prompt makes a massive difference.
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."
)
This short and direct prompt works much better than endless prompts full of “don’t do this” rules that usually confuse models. It includes semantic synonym mapping and clear anti-hallucination rules, drastically cutting down errors.
2. Conversation History with HTTP Sessions
The Problem
Before, each call to the /api/chat endpoint was stateless. The agent didn’t remember anything it had said before:
Usuario: "¿Qué portátiles tienes?"
Agente: [busca y devuelve 3 portátiles]
Usuario: "¿Cuál es el más barato de los que me has dicho?"
Agente: [sin contexto → no sabe a cuáles se refiere]
The Solution: Session + MessageBag
We use Symfony’s native session to store the history as a plain array and reconstruct it on each request as a full MessageBag:
final class ProductChatService
{
public function ask(string $userQuestion): string
{
$session = $this->requestStack->getSession();
$history = $session->get('chat_history', []);
$history[] = ['role' => 'user', 'content' => $userQuestion];
$result = $this->defaultAgent->call($this->buildMessageBag($history));
$answer = (string) $result->getContent();
// Guard contra fugas de tool calls o JSON corrupto
if (preg_match('/^[a-z_]+\{/i', trim($answer)) || preg_match('/function=/', trim($answer)) || empty(trim($answer))) {
$answer = 'Lo siento, no pude obtener la información correctamente. ¿Puedes reformular tu pregunta?';
}
$history[] = ['role' => 'assistant', 'content' => $answer];
$session->set('chat_history', array_slice($history, -10));
return $answer;
}
private function buildMessageBag(array $history): MessageBag
{
$messages = [Message::forSystem("You are a helpful online store assistant...")];
foreach ($history as $msg) {
$messages[] = match ($msg['role']) {
'user' => Message::ofUser($msg['content']),
'assistant' => Message::ofAssistant($msg['content']),
default => null,
};
}
return new MessageBag(...array_filter($messages));
}
}
We added a small regex guard to prevent leaked JSON or failed tool calls from polluting the visible response to the user. In the controller, we also have a general catch block returning friendly messages if an error occurs.
We limit history to the last 10 messages for practical reasons: beyond that, token consumption shoots up.
With this in place, the agent can now maintain coherent conversations:
Usuario: "¿Qué portátiles tienes por menos de 1000€?"
Agente: [devuelve Ultrabook Zen 13 y Portátil Estudiante]
Usuario: "¿Cuál es el más barato?"
Agente: [con contexto → "La más barata es la Portátil Estudiante a 599€"]
3. Catalog and Search Improvements
We expanded the catalog to 20 real products spread across 4 categories: smartphones, laptops, headphones, and smartwatches.
The most important technical improvement is category normalization. Each product now has a category field with its slug (portatil, telefono, etc.). This enables exact searches and eliminates ambiguity.
public function searchByCategory(string $category, int $limit = 3, int $offset = 0): array
{
$search = $this->normalize($category);
$matches = array_filter($this->products, function (Product $p) use ($search) {
return $this->normalize($p->getCategory()) === $search;
});
return array_slice(array_values($matches), $offset, $limit);
}
private function normalize(string $text): string
{
return str_replace(
['á', 'é', 'í', 'ó', 'ú', 'ü', 'ñ'],
['a', 'e', 'i', 'o', 'u', 'u', 'n'],
mb_strtolower(trim($text))
);
}
The agent receives valid slugs via ProductCategoryTool and uses them directly in ProductSearchTool. Much cleaner and more reliable.
4. Chat Interface with Vanilla JS
The Twig Template
The entire frontend lives in a single Twig file. No React, no Vue, no npm, no bundlers:
{# templates/chat/demo.html.twig #}
{% extends 'base.html.twig' %}
{% block body %}
<div class="chat-container">
<div class="chat-header">Asistente de Productos</div>
<div class="chat-messages" id="chat">
<div class="message ai">¡Hola! Soy tu asistente de tienda. ¿En qué puedo ayudarte?</div>
</div>
<div class="chat-input">
<input type="text" id="prompt" placeholder="Escribe tu pregunta...">
<button id="btn-send">Enviar</button>
</div>
</div>
{% endblock %}
The Client-Side JavaScript
The flow is standard, but with a few important details: UI locking to prevent duplicate messages, a progressive typing effect, and basic XSS protection.
async function sendMessage() {
const text = inputPrompt.value.trim();
if (!text) return;
addMessageBubble(text, 'user');
inputPrompt.value = '';
btnSend.disabled = true;
inputPrompt.disabled = true;
const aiBubble = addMessageBubble('⏳ Pensando...', 'ai');
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question: text }),
});
const data = await response.json();
if (!response.ok) {
aiBubble.innerHTML = `<span class="error">${escapeHTML(data.error)}</span>`;
return;
}
await typeWriter(aiBubble, data.answer);
} catch {
aiBubble.innerHTML = '<span class="error">No se pudo conectar con el servidor.</span>';
} finally {
btnSend.disabled = false;
inputPrompt.disabled = false;
}
}
async function typeWriter(element, text) {
let current = '';
for (const word of text.split(' ')) {
current += word + ' ';
element.innerHTML = escapeHTML(current).replace(/\n/g, '<br>');
chatContainer.scrollTop = chatContainer.scrollHeight;
await new Promise(r => setTimeout(r, 30));
}
}
function escapeHTML(str) {
const p = document.createElement('p');
p.textContent = str;
return p.innerHTML;
}
Important: The typing effect is purely visual. The server still returns the entire response at once. The “thinking…” indicator is displayed throughout the model’s generation. Real streaming (token by token) will be covered in the next article.
5. Resulting Architecture
graph TD
%% Estilos
classDef fe fill:#1a237e,stroke:#fff,color:#fff,stroke-width:2px;
classDef logic fill:#0d47a1,stroke:#fff,color:#fff,stroke-width:1px;
classDef agent fill:#4a148c,stroke:#fff,color:#fff,stroke-width:2px;
classDef tool fill:#263238,stroke:#fff,color:#fff,stroke-width:1px;
classDef repo fill:#004d40,stroke:#fff,color:#fff,stroke-width:2px;
%% Nodos
FE[Frontend Vanilla JS]:::fe
PC[ProductChatController]:::logic
PS[ProductChatService]:::logic
AI[AgentInterface Groq-Llama]:::agent
T1[search]:::tool
T2[price]:::tool
T3[categories]:::tool
PR[(ProductRepository)]:::repo
%% Flujos
FE --> PC
PC --> PS
PS --> AI
AI --> T1
AI --> T2
AI --> T3
T1 --> PR
T2 --> PR
T3 --> PR
6. Summary of Changes Compared to the Previous Article
| Aspect | Article 1 | Article 2 |
|---|---|---|
| Tools | 1 (price) | 3 (search, price, categories) |
| History | None | HTTP session, last 10 messages |
| Search | Exact SKU only | Normalized category (slugs) + pagination |
| Frontend | None | Chat UI with Vanilla JS and typing effect |
| Catalog | 4 products | 20 products across 4 categories |
| System prompt | 2 lines | Detailed instructions + anti-hallucination rules |
| Robustness | Basic | Guard against JSON leaks + error handling |
7. What’s New in v0.7.0 Affecting This Project
Besides the fixes mentioned in the introduction, version 0.7.0 brings other interesting improvements:
- Tool argument validation with Symfony Validator (
#1681). You can now add constraints directly to__invoke()parameters, and the framework takes care of validating them before running the tool. - Streaming in the Chat component (
#1583and#1759): improved support and typedDeltaInterfaceobjects. This will make our lives much easier in the next article.
Where We Stand and Next Steps
With what we’ve covered in this article, we now have a fairly complete conversational assistant: it orchestrates multiple tools, remembers conversation context, and offers a clean UI built with native Symfony tools and pure JavaScript.
It’s a realistic example of how to start integrating AI into PHP/Symfony applications without unnecessary bloat while retaining full control over your code.
The big UX improvement is still pending: true streaming. In the next article, we’ll focus exclusively on implementing Server-Sent Events so responses appear token by token, eliminating that annoying initial delay.
Thanks to the upgrade to v0.7.0 and the new capabilities in the Chat component, that implementation should end up much cleaner and more robust.
The repository is public and you can spin it up in minutes. If you have questions, improvements, or want to see any extra features, drop a comment. In the next article, we’ll dive straight into streaming.
Let’s keep coding.