Special Anniversary Black Friday: Get 30% off all training and 10% off all services Get a Quote


Building AI-Driven Features in Symfony

· Silas Joisten · 2 minutes to read
AI and Symfony

AI is transforming web development — and with php-llm/llm-chain, PHP developers can easily add powerful LLM features to Symfony apps. This guide shows you how to get started with chatbots, smart assistants, and more.

Why AI in Symfony?

AI is no longer a futuristic concept — it's part of today's tech stack. From chatbots to content enrichment and semantic search, AI-driven features are everywhere. Thanks to the php-llm/llm-chain library, integrating these capabilities into your Symfony project has never been easier.

Introduction

php-llm/llm-chain is a PHP-native library that allows you to interact with Large Language Models (LLMs) like:

It supports a wide variety of platforms (OpenAI, Azure, Replicate, etc.) and allows you to:

  • Generate content.

  • Call external tools (functions) with LLMs.

  • Embed and semantically search documents.

  • Chain multiple AI calls together with logic.

Symfony integration is provided via php-llm/llm-chain-bundle, which gives you automatic service registration, DI support, and config-driven setup.

Installing the Symfony Bundle

Install the package via Composer:

composer require php-llm/llm-chain-bundle

Configure your .env:

OPENAI_API_KEY=your-api-key-here

Configure the service in config/packages/llm_chain.yaml:

llm_chain:
  platform:
    openai:
      api_key: '%env(OPENAI_API_KEY)%'

  chain:
    default:
      model:
        name: 'gpt4o-mini'

Using AI in Your Symfony Service

Here’s a simple example of how to create a Symfony service that sends a message to an LLM and gets a response.

use PhpLlm\LlmChain\ChainInterface;
use PhpLlm\LlmChain\Model\Message\Message;
use PhpLlm\LlmChain\Model\Message\MessageBag;
use PhpLlm\LlmChain\Model\Response\ResponseInterface;

final class SmartAssistant
{
    public function __construct(
        private ChainInterface $chain
    ) {
    }

    public function ask(string $question): ResponseInterface
    {
        $messages = new MessageBag(
            Message::forSystem('You are a helpful assistant.'),
            Message::ofUser($question),
        );

        return $this->chain->call($messages);
    }
}

You can now use this service in any controller, console command, or background worker.

Tool Calling: Make the AI Interactive

Want your LLM to call real PHP functions? Annotate them by using #[AsTool] attribute:

use PhpLlm\LlmChain\Toolbox\Attribute\AsTool;

#[AsTool('current_time', 'Returns the current server time')]
final class ClockTool
{
    public function __invoke(): string
    {
        return (new \DateTimeImmutable())->format('Y-m-d H:i:s');
    }
}

The LLM can now decide on its own when to use this function during a conversation. Think of it like ChatGPT Plugins… but in PHP.

llm-chain also supports embeddings for semantic search. You can store vectors in providers like:

This is great for implementing Retrieval-Augmented Generation (RAG) — a technique where you fetch contextually relevant documents before asking the LLM a question.

Try It: Symfony Demo Project

Want to test this out? The php-llm/llm-chain team provides a demo Symfony application showing chatbot interaction and vector search:

php-llm/llm-chain-symfony-demo

Controlling Costs and Tokens

LLMs aren’t free, so stay efficient with:

  • Cache repeating responses

  • Using short prompts

  • Monitoring token usage via logs

  • Limiting your system prompts

Conclusion

With just a few lines of configuration and code, you can integrate powerful AI features into your Symfony app. Whether you want to automate tasks, answer questions, or enrich content — llm-chain is a solid tool to get started.

Symfony is ready for the AI age. Are you?

Ready to Build Smarter Symfony Apps?

Start building smarter Symfony apps today with llm-chain — AI-powered features are just a few lines of code away.

This might also interest you

Chart going up
Silas Joisten

Why Tests? Explained for Management

For business leaders: why testing matters for ROI, risk reduction, and agility explained in management language with numbers and real case studies.

Read more
Code happy in lights
Imen Ezzine

Code Review: Types, Organization, and Best Practices

Code review is an essential step in the software development cycle. It improves code quality, reduces bugs, and encourages knowledge sharing within the team. GitLab and GitHub, two of the most popular code management platforms, offer advanced features to facilitate this process. This article covers the various types of code reviews, how to organize them, and how to use templates and checklists to make PRs (pull requests) more efficient.

Read more
Many Lego figurines on a white table with hands playing with them
Alexandre Nesson

Scrum Guide Expansion Pack (2025): Key Insights You Need to Know

A new building block has been added to the Scrum Guide to enrich it! Does it offer real value, or is it just window dressing? Read on to find out in this article written by one of our experts.

Read more
The SensioLabs team celebrating the 20th anniversary of Symfony with balloons
Jules Daunay

The Story Continues: SensioLabs Celebrates Symfony's 20th Anniversary

Time flies, especially when you're busy shaping the future of development! The SensioLabs team has just reached a milestone with the anniversary of the Symfony framework. We marked the occasion at the office, but the party isn't over yet. The date is already set for an XXL celebration at SymfonyCon Amsterdam 2025, from November 27 to 28.

Read more
PHP 8.5 URI extension
Oskar Stark

PHP 8.5's New URI Extension: A Game-Changer for URL Parsing

PHP 8.5 introduces a powerful new URI extension that modernizes URL handling. With support for both RFC 3986 and WHATWG standards, the new Uri class provides immutable objects, fluent interfaces, and proper validation - addressing all the limitations of the legacy parse_url() function. This guide shows practical before/after examples and explains when to use each standard.

Read more
Open in new tab
Silas Joisten

The Tab Trap: Why Forcing New Tabs Is Bad UX

We’ve all done it — added target="_blank" to a link to “help users” stay on our site. But what feels like a harmless convenience often creates confusion, breaks accessibility, and introduces hidden security risks.

Read more
3 dog heads
Mathieu Santostefano

Bring Your Own HTTP client

Break free from rigid dependencies in your PHP SDKs. Learn how to use PSR-7, PSR-17, and PSR-18 standards along with php-http/discovery to allow users to bring their favorite HTTP client, whether it's Guzzle, Symfony HttpClient, or another. A must-read for PHP and Symfony developers.

Read more
Vegetables on a wooden board with a knife with a pan on top
Rémi Brière

Why Scrum Fails (and How to Fix It) - Part 2

Scrum is often seen as the obvious framework for structuring and energizing product development, especially digital products. However, its adoption doesn't automatically guarantee success. So, what does Scrum really enable? More importantly, what are the conditions necessary for its effectiveness? And, above all, what pitfalls should be avoided to ensure it becomes a real asset?

Read more
Blue sign on a building with several Now What? letters
Thibaut Chieux

How To Prioritize Messages When Building Asynchronous Applications With Symfony Messenger

Asynchronous processing offers benefits like decoupled processes and faster response times, but managing message priorities can become a challenge. When dealing with tasks ranging from password resets to complex exports, ensuring timely delivery of critical messages is essential. This article explores common asynchronous processing issues and provides solutions using Symfony Messenger, allowing you to optimize your application without extensive refactoring.

Read more
SensioLabs University Courses announcing the new level 3 Master training course now available
Jules Daunay

Master Symfony: Unlock Expert Skills with Our Training

Take your Symfony proficiency from good to great with the new Level 3 training course at SensioLabs! Master complex topics, optimize performance, and become a Symfony expert.

Read more
PHP 8.5
Oskar Stark

What's New in PHP 8.5: A Comprehensive Overview

PHP 8.5 will be released in November 2025 and brings several useful new features and improvements. This version focuses on developer experience enhancements, new utility functions, and better debugging capabilities.

Read more
Two images: on the left many cars stuck in a traffic jam with the sign "All directions" above, on the right a blue car moving forward alone on the highway with the sign "Service Subscriber" and a Symfony logo above
Steven Renaux

Symfony Lazy Services with Style: Boost DX using Service Subscribers

Boost your Symfony app's performance and developer experience! Learn how to use Service Subscribers and traits for lazy service loading to reduce eager instantiation, simplify dependencies, and create modular, maintainable code.

Read more
the surface of the earth seen from the space with city lights forming networks
Imen Ezzine

HTTP Verbs: Your Ultimate Guide

HTTP Verbs Explained: Learn the basics of GET, POST, PUT, DELETE, and more. This article explains how they work, their applications, and their security implications.

Read more
Poster of Guillaume Loulier presentation
Salsabile El-Khatouri

A Symfony Training at SensioLabs: Behind The Scenes

What does Symfony training at SensioLabs look like? Find out in this interview with Guillaume Loulier, a passionate developer and trainer, who tells us all about the official Symfony training courses.

Read more
Toy factory production line
Silas Joisten

Supercharging Symfony Testing with Zenstruck Foundry

Zenstruck Foundry has revolutionized the way we write tests in Symfony. In this post, you’ll learn how expressive factories, isolated test data, and a smoother developer experience helped us streamline our testing workflow and boost productivity.

Read more
Image