Weave Code
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

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle:

    composer require symfony/ai-bundle
    

    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)%'
    
  3. First Use Case: Simple Chat Agent Create a controller to interact with the platform:

    use Symfony\AI\Agent\AgentInterface;
    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.
  • tests/ for integration patterns (e.g., AgentFactoryTest).

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 Provider abstraction to route requests to the correct platform:
    $provider = $this->container->get('ai.platform_provider');
    $response = $provider->get('anthropic')->chat([$message]);
    

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']
    

3. Vector Store Integration

  • Local Stores: Use SQLite for development:
    ai:
        stores:
            documents:
                type: 'sqlite'
                path: '%kernel.project_dir%/var/vector_store.sqlite'
    
  • Hybrid Retrieval: Combine keyword and vector search:
    $query = new Query('Symfony AI', [
        'filter' => ['category' => 'framework'],
    ]);
    $results = $store->search($query, 5);
    

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
    
  • Token Tracking: Monitor usage in the DataCollector:
    $this->container->get('ai.data_collector')->collectTokens($agent, $response);
    

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']
    

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

  • No BC Guarantee: Avoid using unstable APIs (e.g., StoreFactory may change). Workaround: Pin to a specific version (e.g., v0.8.0) and monitor Symfony AI issues.

2. 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'
    

3. 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 (e.g., MariaDB requires type: 'mariadb' with cosine enabled).

4. 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.

5. 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);
        }
    }
    

6. 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());
    

7. 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

1. **Profiler Deep

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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor