Andrei Pall

Linux Software Engineering

How to integrate Symfony 8 with Ollama using Symfony AI

The recommended way to integrate Symfony 8 with Ollama using Symfony AI is to use the official Symfony AI Bundle together with the Ollama Platform bridge.

This eliminates the need to manually implement HTTP requests to the Ollama REST API and provides a foundation for chatbots, AI agents, structured responses, embeddings and Retrieval-Augmented Generation (RAG).

1. Architecture

2. Install Ollama

On Linux:

curl -fsSL https://ollama.com/install.sh | sh

Download a language model:

ollama pull qwen2.5:7b

Test the model:

ollama run qwen2.5:7b

Verify that the Ollama REST API is accessible:

curl http://localhost:11434/api/tags

Alternatively, if you prefer Docker:

docker run -d \
  --name ollama \
  --restart unless-stopped \
  -p 127.0.0.1:11434:11434 \
  -v ollama_data:/root/.ollama \
  ollama/ollama

Download the model inside the container:

docker exec -it ollama ollama pull qwen2.5:7b

3. Install Symfony AI packages

Inside your Symfony 8 project, execute:

composer require symfony/ai-bundle
composer require symfony/ai-ollama-platform

The packages have the following responsibilities:

Package Responsibility
symfony/ai-bundle Integration with Symfony’s dependency injection and configuration system
symfony/ai-platform Common interface for AI model providers
symfony/ai-ollama-platform Communication with Ollama
symfony/ai-agent Higher-level AI agents and tool integration
symfony/ai-chat Conversation management

Composer installs the required dependencies automatically.

4. Configure environment variables

Add the following variables to .env.local:

OLLAMA_HOST_URL=http://127.0.0.1:11434
OLLAMA_MODEL=qwen2.5:7b

If Ollama is running on a dedicated server, replace 127.0.0.1 with the server’s private IP address.

If both Symfony and Ollama are running in Docker containers on the same network:

OLLAMA_HOST_URL=http://ollama:11434
OLLAMA_MODEL=qwen2.5:7b

5. Configure Symfony AI Bundle

Create or modify config/packages/ai.yaml:

ai:
    platform:
        ollama:
            endpoint: '%env(OLLAMA_HOST_URL)%'
            model_catalog:
                cache: true

    agent:
        default:
            platform: 'ai.platform.ollama'
            model: '%env(OLLAMA_MODEL)%'

This configuration registers the Ollama platform and a default AI agent.

The model catalog cache avoids repeatedly requesting model metadata from Ollama.

image

symfony.com

Verify the configuration:

php bin/console debug:config ai

Verify that the services are registered:

php bin/console debug:container ai.platform.ollama
php bin/console debug:container ai.agent.default

You can also test Ollama directly using Symfony’s built-in console command:

php bin/console ai:platform:invoke ollama qwen2.5:7b "What is Symfony?"

Or start an interactive conversation with the configured agent:

php bin/console ai:agent:call default

You should verify that these commands work before implementing the controllers and services.

6. Using the Platform component

The Platform component is the lower-level abstraction used to communicate with AI models. It is suitable for operations such as text generation, translation, summarization and classification.

Create an AI service

src/Service/OllamaService.php

<?php

namespace App\Service;

use Symfony\AI\Platform\PlatformInterface;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

final readonly class OllamaService
{
    public function __construct(
        #[Autowire(service: 'ai.platform.ollama')]
        private PlatformInterface $platform,

        #[Autowire('%env(OLLAMA_MODEL)%')]
        private string $model
    ) {
    }

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

        $result = $this->platform->invoke(
            $this->model,
            $messages
        );

        return $result->asText();
    }
}

The PlatformInterface abstracts provider-specific API communication, allowing you to change AI providers without rewriting most of your application logic.

image

Platform Component (Symfony Docs)

Explanation

Component Description
PlatformInterface Common interface for AI providers
MessageBag Container for messages sent to the model
Message::forSystem() Defines the model’s instructions
Message::ofUser() Creates a user message
Message::ofAssistant() Creates a previous assistant message
invoke() Executes the AI model
asText() Returns the generated text

Create a REST API controller

src/Controller/AiController.php

<?php

namespace App\Controller;

use App\Service\OllamaService;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/api/ai')]
final class AiController extends AbstractController
{
    #[Route('/generate', name: 'ai_generate', methods: ['POST'])]
    public function generate(
        Request $request,
        OllamaService $ollamaService,
        LoggerInterface $logger
    ): JsonResponse {
        $prompt = trim(
            $request->getPayload()->getString('prompt')
        );

        if ($prompt === '') {
            return $this->json([
                'error' => 'Prompt is required.'
            ], 400);
        }

        if (mb_strlen($prompt) > 10000) {
            return $this->json([
                'error' => 'Prompt is too long.'
            ], 400);
        }

        try {
            $response = $ollamaService->generate($prompt);

            return $this->json([
                'response' => $response
            ]);
        } catch (\Exception $e) {
            $logger->error('AI generation failed.', [
                'exception' => $e
            ]);

            return $this->json([
                'error' => 'AI service is unavailable.'
            ], 502);
        }
    }
}

Test the REST API

curl -X POST http://localhost:8000/api/ai/generate \
  -H "Content-Type: application/json" \
  -d '{"prompt":"Explain dependency injection in PHP."}'

Example response:

{
    "response": "Dependency injection is a design pattern in which dependencies are provided to an object rather than created by the object itself."
}

7. Using the Agent component

The Agent component is a higher-level abstraction built on top of the Platform component.

It is particularly useful when implementing AI assistants that need to interact with application services, tools or databases.

Create an agent service

Because the default agent was configured in ai.yaml, you can inject it directly.

src/Service/AiAgentService.php

<?php

namespace App\Service;

use Symfony\AI\Agent\AgentInterface;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

final readonly class AiAgentService
{
    public function __construct(
        #[Autowire(service: 'ai.agent.default')]
        private AgentInterface $agent
    ) {
    }

    public function ask(string $prompt): string
    {
        $messages = new MessageBag(
            Message::ofUser($prompt)
        );

        return $this->agent
            ->call($messages)
            ->asText();
    }
}

Unlike the Platform approach, you do not need to specify the model every time. The agent already knows which platform and model to use.

Configure a system prompt

You can centrally configure the agent’s behaviour in config/packages/ai.yaml:

ai:
    platform:
        ollama:
            endpoint: '%env(OLLAMA_HOST_URL)%'
            model_catalog:
                cache: true

    agent:
        default:
            platform: 'ai.platform.ollama'
            model: '%env(OLLAMA_MODEL)%'
            prompt:
                text: |
                    You are a helpful AI assistant.
                    Provide accurate and concise answers.
                    If you do not know the answer, say so.

All requests handled by this agent will use the configured instructions.

8. Configure multiple AI agents

You can configure multiple agents for different functionalities within the same Symfony application.

For example, install another model specialized in programming:

ollama pull qwen2.5-coder:7b

Then configure three agents:

# config/packages/ai.yaml

ai:
    platform:
        ollama:
            endpoint: '%env(OLLAMA_HOST_URL)%'
            model_catalog:
                cache: true

    agent:
        default:
            platform: 'ai.platform.ollama'
            model: 'qwen2.5:7b'
            prompt:
                text: 'You are a helpful AI assistant.'

        programmer:
            platform: 'ai.platform.ollama'
            model: 'qwen2.5-coder:7b'
            prompt:
                text: |
                    You are an experienced software developer.
                    Provide secure and maintainable code.
                    Explain your code with examples.

        translator:
            platform: 'ai.platform.ollama'
            model: 'qwen2.5:7b'
            prompt:
                text: |
                    Translate the supplied text into Dutch.
                    Preserve the original meaning.
                    Return only the translated text.

Inject the agents into your service:

<?php

namespace App\Service;

use Symfony\AI\Agent\AgentInterface;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

final readonly class AiService
{
    public function __construct(
        #[Autowire(service: 'ai.agent.programmer')]
        private AgentInterface $programmer,

        #[Autowire(service: 'ai.agent.translator')]
        private AgentInterface $translator
    ) {
    }

    public function generateCode(string $prompt): string
    {
        return $this->programmer->call(
            new MessageBag(
                Message::ofUser($prompt)
            )
        )->asText();
    }

    public function translate(string $text): string
    {
        return $this->translator->call(
            new MessageBag(
                Message::ofUser($text)
            )
        )->asText();
    }
}

This architecture makes it possible to define separate AI behaviours without creating separate Ollama installations.

9. Implement conversational AI with history

To implement a chatbot, you need to supply previous conversation messages with every request unless you configure a persistent message store.

Create src/Service/ChatService.php:

<?php

namespace App\Service;

use Symfony\AI\Agent\AgentInterface;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

final readonly class ChatService
{
    public function __construct(
        #[Autowire(service: 'ai.agent.default')]
        private AgentInterface $agent
    ) {
    }

    public function chat(
        string $prompt,
        SessionInterface $session
    ): string {
        $history = $session->get('ai_chat_history', []);

        $messages = new MessageBag();

        foreach ($history as $message) {
            if ($message['role'] === 'user') {
                $messages->add(
                    Message::ofUser($message['content'])
                );
            } elseif ($message['role'] === 'assistant') {
                $messages->add(
                    Message::ofAssistant($message['content'])
                );
            }
        }

        $messages->add(
            Message::ofUser($prompt)
        );

        $answer = $this->agent
            ->call($messages)
            ->asText();

        $history[] = [
            'role' => 'user',
            'content' => $prompt
        ];

        $history[] = [
            'role' => 'assistant',
            'content' => $answer
        ];

        // Keep only the last 20 messages.
        $session->set(
            'ai_chat_history',
            array_slice($history, -20)
        );

        return $answer;
    }

    public function clear(SessionInterface $session): void
    {
        $session->remove('ai_chat_history');
    }
}

Chat controller

src/Controller/ChatController.php

<?php

namespace App\Controller;

use App\Service\ChatService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/api/chat')]
final class ChatController extends AbstractController
{
    #[Route('', methods: ['POST'])]
    public function chat(
        Request $request,
        ChatService $chatService
    ): JsonResponse {
        $prompt = trim(
            $request->getPayload()->getString('prompt')
        );

        if ($prompt === '' || mb_strlen($prompt) > 10000) {
            return $this->json([
                'error' => 'Invalid prompt.'
            ], 400);
        }

        $answer = $chatService->chat(
            $prompt,
            $request->getSession()
        );

        return $this->json([
            'response' => $answer
        ]);
    }

    #[Route('/clear', methods: ['POST'])]
    public function clear(
        Request $request,
        ChatService $chatService
    ): JsonResponse {
        $chatService->clear(
            $request->getSession()
        );

        return $this->json([
            'success' => true
        ]);
    }
}

The conversation history will be stored in the user’s Symfony session.

Example conversation

What is Doctrine ORM?

Doctrine ORM is a PHP library that maps database tables to PHP objects and simplifies database operations.

How can I install it?

To install Doctrine ORM in your Symfony project, execute:

composer require symfony/orm-pack

The model understands what “it” refers to because previous messages are included in the request.

For a production application with persistent conversations, consider Symfony AI’s message stores or Doctrine ORM instead of PHP sessions. Limit conversation history by token count as well as message count.

10. Stream AI responses in real time

Instead of waiting for Ollama to generate the entire response, Symfony AI allows you to stream the text incrementally.

This provides a user experience similar to ChatGPT.

Add a streaming method to OllamaService

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

    $result = $this->platform->invoke(
        $this->model,
        $messages,
        [
            'stream' => true
        ]
    );

    yield from $result->asTextStream();
}

Symfony AI converts provider-specific streaming responses into a common interface.

image

Platform Component (Symfony Docs)

Streaming controller

<?php

namespace App\Controller;

use App\Service\OllamaService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route;

final class AiStreamController extends AbstractController
{
    #[Route('/api/ai/stream', methods: ['POST'])]
    public function stream(
        Request $request,
        OllamaService $ollamaService
    ): StreamedResponse {
        $prompt = trim(
            $request->getPayload()->getString('prompt')
        );

        if ($prompt === '' || mb_strlen($prompt) > 10000) {
            throw new BadRequestHttpException('Invalid prompt.');
        }

        return new StreamedResponse(
            function () use ($ollamaService, $prompt) {
                foreach ($ollamaService->stream($prompt) as $text) {
                    echo $text;

                    if (ob_get_level() > 0) {
                        ob_flush();
                    }

                    flush();
                }
            },
            200,
            [
                'Content-Type' => 'text/plain; charset=UTF-8',
                'Cache-Control' => 'no-cache',
                'X-Accel-Buffering' => 'no'
            ]
        );
    }
}

HTML frontend

<textarea id="prompt" class="form-control"></textarea>

<button id="send" class="btn btn-primary mt-3">
    Send
</button>

<div id="response" style="white-space: pre-wrap;"></div>

JavaScript frontend

document.getElementById("send").addEventListener("click", async () => {

    const prompt = document.getElementById("prompt").value;
    const output = document.getElementById("response");
    const button = document.getElementById("send");

    output.textContent = "";
    button.disabled = true;

    try {
        const response = await fetch("/api/ai/stream", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ prompt })
        });

        if (!response.ok || !response.body) {
            throw new Error("Request failed");
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();

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

            if (done) {
                break;
            }

            output.textContent += decoder.decode(value, {
                stream: true
            });
        }

        output.textContent += decoder.decode();

    } catch (error) {
        output.textContent += "\nUnable to generate response.";
    } finally {
        button.disabled = false;
    }
});

Using textContent instead of innerHTML prevents generated HTML from being executed in the browser.

If Symfony is running behind Nginx and PHP-FPM, ensure that response buffering does not interfere with streaming.

11. Implement AI tools (function calling)

One of the most powerful features of Symfony AI is the possibility of allowing an AI agent to execute predefined PHP methods.

For example, an AI agent could retrieve information from a database, search Apache Solr or retrieve information from an internal REST API.

This requires an Ollama model that supports tool calling.

Create a tool

src/Ai/Tool/CompanyInformation.php

<?php

namespace App\Ai\Tool;

use Symfony\AI\Agent\Toolbox\Attribute\AsTool;

#[AsTool(
    name: 'get_company_information',
    description: 'Returns information about the company.'
)]
final class CompanyInformation
{
    public function __invoke(): array
    {
        return [
            'name' => 'Example Company',
            'country' => 'Netherlands',
            'services' => [
                'Web archiving',
                'Digital preservation',
                'Search'
            ]
        ];
    }
}

Register the tool with an agent

ai:
    platform:
        ollama:
            endpoint: '%env(OLLAMA_HOST_URL)%'

    agent:
        default:
            platform: 'ai.platform.ollama'
            model: '%env(OLLAMA_MODEL)%'

            prompt:
                text: |
                    You are a company assistant.
                    Use the available tools to retrieve
                    accurate company information.
                include_tools: true

            tools:
                - 'App\Ai\Tool\CompanyInformation'

The existing AiAgentService can now handle questions that require company information.

The tool is executed by Symfony, not by Ollama. Ollama requests the tool invocation, and the Symfony AI Agent handles its execution.

Always enforce authorization and validate tool arguments in PHP. Never give an AI agent unrestricted access to SQL queries, shell commands or privileged operations.

12. Configure HTTP timeouts

Local AI models can take considerable time to generate answers, especially when running without a GPU.

Configure a dedicated scoped HTTP client:

config/packages/framework.yaml

framework:
    http_client:
        scoped_clients:
            ollama.client:
                base_uri: '%env(OLLAMA_HOST_URL)%'
                timeout: 120
                max_duration: 300

Use it in the AI configuration:

config/packages/ai.yaml

ai:
    platform:
        ollama:
            endpoint: '%env(OLLAMA_HOST_URL)%'
            http_client: 'ollama.client'
            model_catalog:
                cache: true

    agent:
        default:
            platform: 'ai.platform.ollama'
            model: '%env(OLLAMA_MODEL)%'
Parameter Description
timeout Maximum permitted period of network inactivity
max_duration Maximum total HTTP request duration
model_catalog.cache Caches model metadata

You may also need to adjust the following Nginx settings if you use PHP-FPM:

fastcgi_read_timeout 300s;
fastcgi_send_timeout 300s;

And review the PHP-FPM pool configuration:

request_terminate_timeout = 330s

For very long AI tasks, using Symfony Messenger for background processing is preferable to continuously increasing request timeouts.

13. Recommended directory structure

For a Symfony 8 application with multiple AI functionalities, I recommend the following directory structure:

symfony-project/
├── config/
│   └── packages/
│       ├── ai.yaml
│       ├── framework.yaml
│       └── security.yaml
│
├── src/
│   ├── Ai/
│   │   ├── Tool/
│   │   │   ├── CompanyInformation.php
│   │   │   └── SolrSearch.php
│   │   └── Processor/
│   │
│   ├── Controller/
│   │   ├── AiController.php
│   │   ├── AiStreamController.php
│   │   └── ChatController.php
│   │
│   ├── Service/
│   │   ├── OllamaService.php
│   │   ├── AiAgentService.php
│   │   └── ChatService.php
│   │
│   ├── Entity/
│   ├── Repository/
│   ├── Message/
│   └── MessageHandler/
│
├── tests/
│   ├── Unit/
│   └── Functional/
│
├── templates/
├── .env
└── .env.local

14. Symfony AI components

Symfony AI is composed of multiple packages that you can use depending on your requirements.

Component Purpose
Platform Communicate with AI models
Agent Execute AI workflows and tools
Chat Manage conversational interactions
Store Store and retrieve vectorized documents
Bundle Integrate AI components with Symfony
Platform bridges Connect to Ollama, OpenAI, Gemini and other providers
Store bridges Connect to supported vector storage systems

15. Platform vs Agent

Feature Platform Agent
Text generation Yes Yes
Conversation messages Yes Yes
Streaming Yes Yes
System instructions Yes Yes
Model abstraction Yes Yes
Central agent configuration No Yes
Automatic tool execution No Yes
Input/output processors Not at agent level Yes
Embeddings Yes Not its primary purpose
Complexity Low Moderate

My recommendation for Symfony 8 is to use both components, depending on the operation:

  • PlatformInterface for text generation, summarization, classification, translation and embeddings.
  • AgentInterface for chatbots, AI assistants, function calling and more complex AI workflows.
  • Symfony Messenger for background AI processing.
  • Doctrine or message stores for persistent conversation history.
  • Symfony Security and RateLimiter for protecting AI endpoints.

For production, also keep Ollama on a private network, restrict concurrent requests, prevent unauthorized tool execution and treat AI-generated content as untrusted data.

Official documentation

Documentation Link
Symfony AI Documentation
Symfony AI Bundle Documentation
Platform Component Documentation
Agent Component Documentation
Ollama Platform Bridge Package
Symfony AI source code GitHub
Ollama Documentation

Implementation notes: I selected Qwen 2.5 as an example model, assumed a locally hosted Ollama installation, and used session-based storage for the chatbot example. I checked the Symfony AI documentation, but have not executed these examples in your application. Symfony AI packages are versioned separately from Symfony 8, so check the installed package versions and configuration reference when implementing this integration.

Newer >>