Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ai Bundle Laravel Package

symfony/ai-bundle

Symfony AI Bundle integrates the Symfony AI components into your Symfony application, providing ready-made configuration and service wiring for building AI-powered features. It is experimental and not covered by Symfony's backward compatibility promise.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle (v0.15):

    composer require symfony/ai-bundle:^0.15
    

    Enable in config/bundles.php:

    return [
        // ...
        Symfony\AI\Bundle\AiBundle::class => ['all' => true],
    ];
    
  2. Configure a Platform (config/packages/ai.yaml):

    ai:
        platforms:
            openai:
                client: 'ai.platform.openai'
                model: 'gpt-4'
                api_key: '%env(OPENAI_API_KEY)%'
    

    v0.15 adds Hub API model resolution with a model class per task. Explicit model values still work and are safer when you need deterministic behavior; use Hub/task-based resolution when you want the bundle to resolve models for a task.

  3. First Use Case: Simple Chat Agent

    use Symfony\AI\Agent\AgentFactoryInterface;
    
    class ChatController
    {
        public function __construct(
            private AgentFactoryInterface $agentFactory
        ) {}
    
        public function chat(string $message): string
        {
            $agent = $this->agentFactory->createAgent('chat', [
                'model' => 'gpt-4',
                'platform' => 'openai',
                'tools' => [],
                'systemPrompt' => 'You are a helpful assistant.',
            ]);
    
            $response = $agent->chat([$message]);
            return $response->getContent();
        }
    }
    
  4. Route the Controller:

    # config/routes.yaml
    chat:
        path: /chat
        controller: App\Controller\ChatController::chat
    

Where to Look First

  • Documentation for configuration reference.
  • config/packages/ai.yaml for platform/store setup.
  • src/Agent/ for custom agent logic.
  • src/Bridge/Decision/ for decision types moved out of the TypeSafe bridge in v0.15.
  • tests/ for integration patterns, including new profiler serialization regression tests for nested results.

Implementation Patterns

Core Workflows

1. Platform Integration

  • Declarative Configuration: Define platforms in ai.yaml with client aliases and models.
    ai:
        platforms:
            anthropic:
                client: 'ai.platform.anthropic'
                model: 'claude-3'
                api_key: '%env(ANTHROPIC_API_KEY)%'
    
  • Dynamic Routing: Use the Provider abstraction to route requests to the correct platform:
    $provider = $this->container->get('ai.platform_provider');
    $response = $provider->get('anthropic')->chat([$message]);
    
  • Argument Aliases: v0.15 registers aliases for platform arguments for all platforms, improving # argument injection consistency. If you previously added manual aliases, verify them against the new defaults.

2. Agent Development

  • Attribute-Based Tools: Annotate methods with #[AsTool] for automatic registration:
    use Symfony\AI\Agent\Attribute\AsTool;
    
    class MyTools {
        #[AsTool(name: 'fetch_weather', description: 'Fetches weather data')]
        public function fetchWeather(string $location): string {
            return "Weather in $location: Sunny";
        }
    }
    
  • Processor Chains: Extend agent behavior with input/output processors:
    use Symfony\AI\Agent\InputProcessorInterface;
    
    class SanitizeInputProcessor implements InputProcessorInterface {
        public function process(array $input): array {
            return array_map('htmlspecialchars', $input);
        }
    }
    
    Register in services.yaml:
    services:
        App\Agent\SanitizeInputProcessor:
            tags: ['ai.agent.input_processor']
    
  • MCP Tools in Long-Running Workers: v0.15 refreshes the MCP tool list on kernel.reset. If you run long-lived workers, ensure the kernel is reset between jobs so tool changes are picked up.

3. Vector Store Integration

  • Local Stores: Use SQLite for development:
    ai:
        stores:
            documents:
                type: 'sqlite'
                path: '%kernel.project_dir%/var/vector_store.sqlite'
    
  • Vector Size and Index Setup: v0.15 adds setup_options to configure vector size, and index creation uses the store’s similarity and distance operator class:
    ai:
        stores:
            documents:
                type: 'postgres'
                setup_options:
                    vector_size: 1536
    
  • Hybrid Retrieval: Combine keyword and vector search:
    $query = new Query('Symfony AI', [
        'filter' => ['category' => 'framework'],
    ]);
    $results = $store->search($query, 5);
    
  • SurrealDB: v0.15 adds SurrealDB 3 support and fixes MongoDB/SurrealDB message store autowiring aliases. Re-check custom aliases if you previously worked around those bugs.

4. Security Integration

  • Tool Authorization: Restrict tools via Symfony’s security system:
    use Symfony\AI\Agent\Attribute\IsGrantedTool;
    
    class AdminTools {
        #[IsGrantedTool('ROLE_ADMIN')]
        #[AsTool(name: 'delete_user')]
        public function deleteUser(int $userId): bool {
            // ...
        }
    }
    

5. Debugging and Profiling

  • Profiler Data: View AI interactions in the Symfony Profiler:
    $agent->chat([$message]); // Logs to /_profiler/ai
    
  • Nested Multi-Part Results: v0.15 fixes profiler failures when serializing nested multi-part results. Upgrade if you were seeing profiler exceptions or incomplete payloads.
  • Token Tracking: Monitor usage in the DataCollector:
    $this->container->get('ai.data_collector')->collectTokens($agent, $response);
    

6. Setup Command Options

  • v0.15 allows setup options to be passed to the setup command. Use this to align store index creation with your embedding configuration:
    php bin/console ai:setup --help
    
    Then pass the appropriate vector size / setup options for your store.

Integration Tips

Symfony Ecosystem

  • HttpClient: Use ScopingHttpClient for platform-specific API keys:
    ai:
        platforms:
            openai:
                client: 'ai.platform.openai'
                http_client: 'ai.http_client.openai'
    
    Configure in config/packages/http_client.yaml:
    http_clients:
        ai.openai:
            base_uri: 'https://api.openai.com/v1'
            auth_bearer: '%env(OPENAI_API_KEY)%'
    

Custom Platforms

  • Bridge Creation: Extend PlatformBridgeInterface for unsupported providers:
    use Symfony\AI\Platform\PlatformBridgeInterface;
    
    class CustomPlatformBridge implements PlatformBridgeInterface {
        public function chat(array $messages, array $options): string {
            // Custom logic
        }
    }
    
    Register in services.yaml:
    services:
        App\AI\CustomPlatformBridge:
            tags: ['ai.platform_bridge']
    

Decision Types

  • v0.15 moves decision types out of the TypeSafe bridge into a dedicated Decision bridge. Update imports if you use them:
    // Before v0.15
    use Symfony\AI\Bridge\TypeSafe\...;
    
    // v0.15+
    use Symfony\AI\Bridge\Decision\...;
    
    Check your composer.json to ensure you depend on the correct bridge package if you use decision types directly.

Hub API Model Resolution

  • v0.15 adds Hub API model resolution with a model class per task. This is useful for task-driven model selection, but it can introduce network/credential dependencies. For tests or deterministic production behavior, pin explicit model names or cache resolved models.

Testing

  • Mock Platforms: Use MockPlatform for unit tests:
    use Symfony\AI\Platform\MockPlatform;
    
    $mockPlatform = new MockPlatform();
    $mockPlatform->expects($this)->chat([$message])->willReturn('Mocked response');
    $this->container->set('ai.platform.openai', $mockPlatform);
    

Performance

  • Caching: Enable prompt caching for repeated queries:
    ai:
        platforms:
            openai:
                cache: true
    
  • Streaming: Use StreamingResponse for real-time interactions:
    $response = $agent->chat([$message], ['stream' => true]);
    foreach ($response->getDeltas() as $delta) {
        echo $delta->getContent();
    }
    

Gotchas and Tips

Pitfalls

1. Experimental Features and Version Pinning

  • No BC Guarantee: AI bundle APIs are still evolving. Pin to a known version and review changelogs before upgrading. Workaround: Use ^0.15 after testing, and monitor Symfony AI issues.

2. Decision Bridge Move

  • Namespace Change: v0.15 moves decision types from the TypeSafe bridge into the Decision bridge. If you import decision types directly, update imports and bridge dependencies. Workaround: Search for Symfony\AI\Bridge\TypeSafe references and migrate them to Symfony\AI\Bridge\Decision.

3. Vector Index Configuration

  • Vector Size Must Match Embeddings: setup_options.vector_size must match your embedding model dimensions. Changing it after an index exists usually requires recreating/reindexing the store. Workaround: Set vector size at project setup, and document it alongside the embedding model choice.
  • Similarity/Distance Operator: v0.15 creates the vector index using the store’s similarity and distance operator class. A mismatched store configuration can produce wrong search results or setup errors. Workaround: Verify the store type and distance/similarity settings before running ai:setup or reindexing.

4. MCP Tool Refresh

  • Kernel Reset Required: The MCP tool list refreshes on kernel.reset. Long-running workers that do not reset the kernel may keep stale tools. Workaround: Ensure workers reset the kernel between jobs, or restart workers after changing MCP tools.

5. Platform Argument Aliases

  • New Defaults May Conflict: v0.15 registers aliases for platform arguments for all platforms. If you added custom aliases, check for duplicates or overrides. Workaround: Remove unnecessary manual aliases and rely on the bundle defaults where possible.

6. MongoDB and SurrealDB Message Store Aliases

  • Autowiring Alias Fixes: v0.15 fixes MongoDB and SurrealDB message store autowiring aliases. Custom aliases created as workarounds may now conflict. Workaround: Review custom service aliases after upgrading and remove obsolete workarounds.

7. Service Naming Conflicts

  • Duplicate Services: If multiple bundles define ai.platform.openai, the last one wins. Workaround: Use explicit aliases in services.yaml:
    services:
        ai.platform.openai: '@ai.platform.openai_custom'
    

8. Vector Store Quirks

  • SQLite Limits: SQLite-Vec has size constraints (~100MB per table). Workaround: Use type: 'memory' for testing or upgrade to PostgreSQL.
  • Distance Metrics: Not all stores support cosine similarity the same way. Check store-specific configuration before relying on similarity search results.

9. Security Misconfigurations

  • Open Tools: Tools without #[IsGrantedTool] are accessible to all users. Workaround: Always annotate tools or use #[IsGrantedTool('IS_AUTHENTICATED_FULLY')] as a default.

10. Token Leaks

  • Sensitive Data: Prompts or responses may expose PII if not sanitized. Workaround: Use OutputProcessorInterface to redact data:
    class RedactPIIProcessor implements OutputProcessorInterface {
        public function process(string $content): string {
            return preg_replace('/\b\d{3}-\d{2}-\d{4}\b/', '[REDACTED]', $content);
        }
    }
    

11. Profiler Serialization

  • Nested Multi-Part Results: Older versions could fail to serialize nested multi-part results in the profiler. v0.15 fixes this and adds regression coverage. Workaround: Upgrade to v0.15 if you see profiler errors when inspecting tool calls or multi-part responses.

12. Hub API Model Resolution

  • External Dependency: Resolving models from the Hub API can depend on network access and credentials. Workaround: Pin explicit model names in production or cache resolved model metadata for deterministic deployments.

13. Streaming Issues

  • Generator Lifecycle: Lazy iterators (e.g., RewindableGenerator) may break streaming. Workaround: Convert to arrays or use iterator_to_array():
    $deltas = iterator_to_array($response->getDeltas());
    

14. Compiler Pass Errors

  • Circular Dependencies: Custom CompilerPass may fail if services depend on each other. Workaround: Use onLoad() to defer registration:
    public function process(ContainerBuilder $container) {
        $container->setCompilerPass(new MyCompilerPass(), PassConfig::TYPE_OPTIMIZE);
    }
    

Debugging Tips

  • Profiler: Check /_profiler/ai for request/response payloads, tool calls, and token usage.
  • Setup Command: Run php bin/console ai:setup --help to see available setup options, especially vector size configuration.
  • Cache: Clear the container cache after changing ai.yaml or service aliases.
  • Aliases: Use debug:container to verify platform, store, and bridge aliases after upgrading to v0.15.
  • Workers: If MCP tools or long-lived services behave stale, reset the kernel or restart workers.
  • Tests: Prefer explicit model names and MockPlatform in tests to avoid Hub API/network dependencies.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core