PHP code example of tawshiqulislam / laravel-llm-failover
1. Go to this page and download the library: Download tawshiqulislam/laravel-llm-failover library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
tawshiqulislam / laravel-llm-failover example snippets
use TawshiqulIslam\LlmFailover\Contracts\LlmDriverInterface;
final class ChatResponseService
{
public function __construct(
private LlmDriverInterface $aiClient,
) {}
public function processReply(string $systemPrompt, array $history): string
{
// An empty model string uses the active driver's configured default.
$result = $this->aiClient->send('', $systemPrompt, $history);
if ($result['is_fallback']) {
logger()->warning($result['error']);
}
return $result['reply'];
}
}
$history = [
['role' => 'user', 'content' => 'Hello!'],
['role' => 'assistant', 'content' => 'How can I help?'],
['role' => 'user', 'content' => 'When do you open?'],
];
use TawshiqulIslam\LlmFailover\Facades\Llm;
// Walk the configured failover chain.
$result = Llm::send('', 'You are a helpful assistant.', $history);
// Call one provider directly without cross-provider failover.
$result = Llm::driver('anthropic')->send('', 'Be concise.', $history);
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use TawshiqulIslam\LlmFailover\Traits\HasChronologicalHistory;
final class Conversation extends Model
{
use HasChronologicalHistory;
public function messages(): HasMany
{
return $this->hasMany(Message::class);
}
}
use TawshiqulIslam\LlmFailover\Facades\Llm;
use TawshiqulIslam\LlmFailover\LlmManager;
use App\Llm\MistralDriver;
Llm::extend('mistral', function ($app) {
return new MistralDriver(
$app->make(LlmManager::class)->driverConfig('mistral'),
);
});