symfony/ai-cerebras-platform
Symfony AI bridge for the Cerebras inference platform. Adds a Cerebras connector to run chat completions and other inference requests through Symfony AI, with links to Cerebras API docs and contribution/issue tracking in the main Symfony AI repository.
Install Dependencies Add the package and Symfony AI to your Laravel project:
composer require symfony/ai-cerebras-platform symfony/ai
Configure API Credentials
Store your Cerebras API key in .env:
CEREBRAS_API_KEY=your_api_key_here
Bind the Client in Laravel
Create a service provider (e.g., CerebrasServiceProvider) to bind the Symfony client:
use Symfony\Component\AI\Client;
use Symfony\Component\AI\Cerebras\CerebrasClient;
public function register()
{
$this->app->singleton(CerebrasClient::class, function ($app) {
return new CerebrasClient($app['config']['cerebras.api_key']);
});
}
First Use Case: Chat Completion Inject the client into a controller or service and call the API:
use Symfony\Component\AI\Cerebras\CerebrasClient;
public function __construct(private CerebrasClient $cerebras)
{
}
public function generateResponse()
{
$response = $this->cerebras->chat('gpt-4', [
'messages' => [
['role' => 'user', 'content' => 'Hello, how are you?'],
],
]);
return $response->getContent();
}
config/cerebras.php (create if missing) for custom configurations.Leverage the Provider abstraction to dynamically route requests based on conditions (e.g., cost, latency):
use Symfony\Component\AI\Provider\ProviderInterface;
use Symfony\Component\AI\Cerebras\CerebrasClient;
class AiService
{
public function __construct(
private ProviderInterface $provider,
private CerebrasClient $cerebras
) {}
public function getBestProvider(string $model): ProviderInterface
{
if ($model === 'cerebras-heavy') {
return $this->cerebras;
}
return $this->provider;
}
}
Use Cerebras’ structured output support for deterministic AI responses:
$response = $this->cerebras->chat('gpt-4', [
'messages' => [['role' => 'user', 'content' => 'Extract data from this text: {text}']],
'response_format' => ['type' => 'json_schema', 'json_schema' => ['type' => 'object', 'properties' => ['key' => ['type' => 'string']]]],
]);
$data = json_decode($response->getContent(), true);
Handle semantic streaming with DeltaInterface for real-time features (e.g., Livewire):
use Symfony\Component\AI\Stream\StreamedResponse;
public function streamResponse()
{
$stream = $this->cerebras->streamChat('gpt-4', [
'messages' => [['role' => 'user', 'content' => 'Generate a story...']],
]);
return new StreamedResponse(
fn () => $stream->getContent(),
200,
['Content-Type' => 'text/event-stream']
);
}
Standardize Cerebras errors across providers using the shared trait:
use Symfony\Component\AI\Exception\InvalidArgumentException;
try {
$response = $this->cerebras->chat('invalid-model', []);
} catch (InvalidArgumentException $e) {
report($e); // Laravel's error reporting
return response()->json(['error' => 'Invalid model'], 400);
}
Facade for Cleaner Syntax Create a facade to simplify client access:
// app/Facades/Cerebras.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Cerebras extends Facade
{
protected static function getFacadeAccessor() { return 'cerebras.client'; }
}
Usage:
$response = Cerebras::chat('gpt-4', [...]);
Queue-Based Async Processing Offload heavy inference tasks to queues:
use Illuminate\Support\Facades\Queue;
Queue::push(function () {
$this->cerebras->chat('gpt-4', [...]);
});
Livewire/Echo Integration Stream responses to Livewire components:
// app/Http/Livewire/ChatComponent.php
public function updatedMessage()
{
$stream = $this->cerebras->streamChat('gpt-4', [
'messages' => [['role' => 'user', 'content' => $this->message]],
]);
foreach ($stream as $delta) {
$this->dispatch('append-message', delta: $delta->getContent());
}
}
Caching Responses Cache deterministic responses (e.g., FAQs) to reduce API calls:
$cacheKey = 'cerebras-faq-' . md5($prompt);
$response = Cache::remember($cacheKey, now()->addHours(1), function () use ($prompt) {
return $this->cerebras->chat('gpt-4', ['messages' => [['role' => 'user', 'content' => $prompt]]]);
});
Symfony vs. Laravel DI Conflicts
Provider interface expects a specific container structure.class CerebrasWrapper
{
public function __construct(private CerebrasClient $client) {}
public function __call($method, $args) {
return $this->client->$method(...$args);
}
}
Streaming in Synchronous Laravel
Symfony\Component\HttpFoundation\StreamedResponse and ensure your middleware supports chunked encoding:
$response = new StreamedResponse(
fn () => $this->cerebras->streamChat(...),
200,
['Content-Type' => 'text/event-stream']
);
return $response->setCallback(
fn () => $this->cerebras->streamChat(...)
);
Model Routing Complexity
public function getResponse(string $model, array $payload)
{
try {
return $this->cerebras->chat($model, $payload);
} catch (Exception $e) {
return $this->fallbackProvider->chat('gpt-3.5', $payload);
}
}
Structured Output Parsing
$content = $response->getContent();
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('Invalid JSON response from Cerebras');
}
API Key Management
env() and encrypt sensitive values:
$client = new CerebrasClient(config('services.cerebras.key'));
// Or with encryption:
$client = new CerebrasClient(decrypt(env('CEREBRAS_API_KEY')));
Enable Symfony AI Debugging
Add this to config/debug.php:
'ai' => env('APP_DEBUG', false),
Then check logs for detailed API calls:
tail -f storage/logs/laravel.log | grep "Cerebras"
Validate API Responses
Use dd() or dump() to inspect raw responses:
$response = $this->cerebras->chat(...);
dd($response->getContent(), $response->getStatusCode());
Mock Cerebras for Testing
Use Symfony’s MockClient in PHPUnit:
use Symfony\Component\AI\Client\MockClient;
$mockClient = new MockClient();
$mockClient->expects('chat')->andReturn(new Response('{"content":"Mocked response"}'));
$this->app->instance(Cerebras
How can I help you explore Laravel packages today?