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.
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
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
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,
],
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!");
});
Test the Endpoint
Visit /ai/chat to see the AI response. Verify the integration works with a simple prompt.
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'];
}
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.
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');
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']);
});
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'];
});
}
AiFacade.AiFacade calls the AI provider and returns the response.// 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]);
}
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'];
}
public function search(string $query)
{
$embedding = $this->generateEmbeddings($query);
$results = Pinecone::search($embedding,
How can I help you explore Laravel packages today?