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 Ai Ml Api Platform Laravel Package

symfony/ai-ai-ml-api-platform

Symfony AI bridge for AiML API Platform, providing access to AiML API’s OpenAI-compatible text/LLM models. Includes links to authentication quickstart and API docs, and points to the main Symfony AI repo for issues and contributions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies Add the package and required Symfony components to your Laravel project:

    composer require symfony/ai symfony/ai-ai-ml-api-platform symfony/http-client
    
  2. Configure API Key Add your AiML API key to .env:

    AIML_API_KEY=your_api_key_here
    AIML_API_BASE_URI=https://api.aimlapi.com/v1
    
  3. Register Symfony Services Create a service provider to bridge Symfony’s AiClient with Laravel’s container:

    // app/Providers/AiServiceProvider.php
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Symfony\Component\AI\Client;
    use Symfony\Component\AI\Provider\AiMLProvider;
    
    class AiServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton('ai.client', function ($app) {
                return new Client([
                    'providers' => [
                        'aiml' => new AiMLProvider($app['config']['aiml.api_key']),
                    ],
                ]);
            });
        }
    }
    

    Register the provider in config/app.php:

    'providers' => [
        // ...
        App\Providers\AiServiceProvider::class,
    ],
    
  4. First Use Case: Chat Completion Create a facade or service to interact with the AI:

    // app/Services/AiFacade.php
    namespace App\Services;
    
    use Symfony\Component\AI\ClientInterface;
    
    class AiFacade
    {
        public function __construct(private ClientInterface $aiClient) {}
    
        public function chat(string $prompt): string
        {
            return $this->aiClient->getProvider('aiml')->chat([
                'model' => 'text-davinci-003',
                'messages' => [['role' => 'user', 'content' => $prompt]],
            ])['choices'][0]['message']['content'];
        }
    }
    

    Use it in a controller:

    // routes/web.php
    use App\Services\AiFacade;
    
    Route::get('/ai/chat', function (AiFacade $ai) {
        return $ai->chat("Hello, world!");
    });
    
  5. Test the Endpoint Visit /ai/chat to see the AI response. Verify the integration works with a simple prompt.


Implementation Patterns

Usage Patterns

1. Provider Abstraction

Leverage the package’s provider abstraction to switch between AI providers dynamically. Configure providers in config/aiml.php:

// config/aiml.php
return [
    'default_provider' => env('AIML_DEFAULT_PROVIDER', 'aiml'),
    'providers' => [
        'aiml' => [
            'api_key' => env('AIML_API_KEY'),
            'base_uri' => env('AIML_API_BASE_URI'),
        ],
        'openai' => [
            'api_key' => env('OPENAI_API_KEY'),
            'base_uri' => env('OPENAI_API_BASE_URI'),
        ],
    ],
];

Use the provider in your service:

public function chat(string $prompt, string $provider = null): string
{
    $providerName = $provider ?? config('aiml.default_provider');
    return $this->aiClient->getProvider($providerName)->chat([
        'model' => 'text-davinci-003',
        'messages' => [['role' => 'user', 'content' => $prompt]],
    ])['choices'][0]['message']['content'];
}

2. Embeddings for Search

Use embeddings to enable semantic search or recommendations:

public function generateEmbeddings(string $text): array
{
    return $this->aiClient->getProvider('aiml')->embeddings([
        'model' => 'text-embedding-ada-002',
        'input' => [$text],
    ])['data'][0]['embedding'];
}

Store embeddings in a vector database (e.g., Pinecone, Weaviate) for fast similarity searches.

3. Async AI Tasks with Queues

Adapt Symfony’s Messenger to Laravel’s Queues for background processing. Create a queueable job:

// app/Jobs/GenerateAiEmbeddings.php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Symfony\Component\AI\ClientInterface;

class GenerateAiEmbeddings implements ShouldQueue
{
    use Dispatchable, Queueable;

    public function __construct(
        public string $text,
        public string $queue = 'ai'
    ) {}

    public function handle(ClientInterface $aiClient)
    {
        $embeddings = $aiClient->getProvider('aiml')->embeddings([
            'model' => 'text-embedding-ada-002',
            'input' => [$this->text],
        ]);
        // Store or process embeddings...
    }
}

Dispatch the job from a controller or command:

GenerateAiEmbeddings::dispatch('Your text here')->onQueue('ai');

4. Middleware for API Key Management

Protect AI endpoints with middleware to validate API keys or enforce rate limits:

// app/Http/Middleware/ValidateAiApiKey.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ValidateAiApiKey
{
    public function handle(Request $request, Closure $next)
    {
        if (!config('aiml.api_key')) {
            abort(500, 'AiML API key not configured.');
        }
        return $next($request);
    }
}

Register the middleware in app/Http/Kernel.php:

protected $routeMiddleware = [
    // ...
    'validate.aiml.key' => \App\Http\Middleware\ValidateAiApiKey::class,
];

Apply it to routes:

Route::middleware(['validate.aiml.key'])->group(function () {
    Route::get('/ai/chat', [AiController::class, 'chat']);
});

5. Caching AI Responses

Cache frequent AI responses to reduce API calls and costs:

use Illuminate\Support\Facades\Cache;

public function chat(string $prompt): string
{
    $cacheKey = "ai_chat_{$prompt}";
    return Cache::remember($cacheKey, now()->addMinutes(5), function () use ($prompt) {
        return $this->aiClient->getProvider('aiml')->chat([
            'model' => 'text-davinci-003',
            'messages' => [['role' => 'user', 'content' => $prompt]],
        ])['choices'][0]['message']['content'];
    });
}

Workflows

1. Chatbot Integration

  • Workflow:
    1. User submits a message via a frontend form.
    2. Laravel controller receives the request and dispatches it to the AiFacade.
    3. AiFacade calls the AI provider and returns the response.
    4. Frontend displays the AI-generated response.
  • Example:
    // routes/web.php
    Route::post('/chat', [AiController::class, 'handleChat']);
    
    // app/Http/Controllers/AiController.php
    public function handleChat(Request $request, AiFacade $ai)
    {
        $prompt = $request->input('prompt');
        $response = $ai->chat($prompt);
        return response()->json(['response' => $response]);
    }
    

2. Dynamic Content Generation

  • Workflow:
    1. User requests dynamically generated content (e.g., blog post outline).
    2. Laravel service generates a prompt for the AI.
    3. AI generates the content, which is stored in the database.
    4. Content is displayed to the user.
  • Example:
    public function generateContent(string $topic): string
    {
        $prompt = "Write a detailed outline for a blog post about {$topic}.";
        return $this->aiClient->getProvider('aiml')->chat([
            'model' => 'text-davinci-003',
            'messages' => [['role' => 'user', 'content' => $prompt]],
            'max_tokens' => 500,
        ])['choices'][0]['message']['content'];
    }
    

3. Semantic Search

  • Workflow:
    1. User submits a search query.
    2. Laravel generates embeddings for the query using the AI.
    3. Vector database (e.g., Pinecone) returns similar items.
    4. Results are displayed to the user.
  • Example:
    public function search(string $query)
    {
        $embedding = $this->generateEmbeddings($query);
        $results = Pinecone::search($embedding,
    
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