Download the PHP package tawshiqulislam/laravel-llm-failover without Composer

On this page you can find all versions of the php package tawshiqulislam/laravel-llm-failover. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-llm-failover

Laravel LLM Failover Gateway

Latest Version on Packagist Total Downloads

A resilient, provider-agnostic text-generation gateway for Laravel.

Laravel LLM Failover protects chat applications from upstream rate limits, overloads, timeouts, server errors, refusals, and empty responses. It tries each configured provider in order and returns one normalized response shape, regardless of which provider succeeds.

Features

Requirements

Laravel 13 itself requires PHP 8.3 or newer.

Laravel 10 and 11 are retained for backwards compatibility but no longer receive upstream security fixes. Use a currently supported Laravel release for production; the CI dependency audit runs on Laravel 12 and 13, while the older lines receive compatibility tests only.

Installation

Publish the configuration:

This creates config/llm-failover.php. Laravel package discovery registers the service provider and the Llm facade automatically.

Configuration

Single provider

When failover is disabled, LlmDriverInterface resolves directly to LLM_DEFAULT_DRIVER.

Production failover

Provider names are trimmed, lowercased, and deduplicated. An empty chain uses LLM_DEFAULT_DRIVER.

All environment options

LLM_HTTP_RETRIES is the number of retries after the initial attempt. A value of 2 allows at most three HTTP attempts per provider. Connection failures, 408, 429, every 5xx, and Anthropic 529 responses are retryable.

Gemini and OpenAI default to a temperature of 0.7. Set the relevant value to the literal null if the selected model does not accept sampling parameters:

Each driver config array also accepts timeout, connect_timeout, retries, and retry_delay; driver-specific values override the shared HTTP settings:

After changing .env values in a config-cached application, rebuild the cache:

Usage

Dependency injection

Injecting the interface is the recommended application-facing entry point. It resolves to the failover gateway when failover is enabled and to the default driver otherwise.

Conversation history must be chronological and contain at least one non-empty text message:

Recognized assistant aliases are assistant, model, ai, and bot. Other role values normalize to user. Blank messages are removed, and consecutive messages with the same normalized role are joined with a newline.

Facade

Model selection during failover

Only the first provider receives the model passed to send(). A different provider cannot generally use that model name, so every later provider uses its own configured default.

With LLM_FAILOVER_CHAIN=gemini,openai:

  1. Gemini receives the caller's model, or GEMINI_DEFAULT_MODEL when the model is empty.
  2. Gemini applies its configured retry policy to retryable failures.
  3. If Gemini still fails, OpenAI is called with OPENAI_DEFAULT_MODEL.
  4. If every provider fails, the gateway returns LLM_FALLBACK_REPLY.

Retryable responses, network failures, empty replies, safety blocks, and supported refusal responses cause failover. Missing API keys and non-retryable provider rejections are also skipped inside the gateway so another configured provider can answer.

Building Eloquent conversation history

Use HasChronologicalHistory on the model that owns a HasMany message relation:

Fetch the newest 20 messages and return them oldest-first:

The message limit must be at least 1. By default, the trait orders by the related model's id. It reads text from body, then content, and maps either of these common schemas:

Stored field User values Assistant values
direction inbound Any other non-null direction, normally outbound
role user, inbound, human, customer Any other value, normally assistant

When both fields exist, direction takes precedence.

For UUID primary keys, pass a monotonically increasing sequence column whenever possible:

The related primary key is used as a stable secondary sort when the chosen order column contains ties. That makes selection deterministic, but a random UUID cannot reconstruct the true creation order of rows with identical timestamps; use a sequence column if exact ordering matters.

Custom drivers

Register custom drivers from a service provider's boot() method:

Add the driver's config under llm-failover.drivers.mistral, then include mistral in LLM_FAILOVER_CHAIN. A custom driver must implement LlmDriverInterface and return the response shape below. Extending AbstractDriver provides the shared history normalization, HTTP retry configuration, response helpers, and fallback logging.

Response format

Every driver and the gateway implement the same contract:

Field Type Description
reply string Provider text, or the configured graceful fallback reply.
is_fallback bool true when no provider text was returned.
error string\|null A safe provider or aggregated failure description.
usage.input_tokens int Input tokens reported by the successful provider.
usage.output_tokens int Output tokens reported by the successful provider.
usage.cached_input_tokens int Cached input tokens reported by the provider.
model string The requested/configured model associated with the result.
driver string\|null Successful/direct driver name; null when the gateway exhausts the chain.

Fallback usage values are zero because not every failed provider returns comparable usage metadata. See Expected_Response_Schema.md for the focused schema reference.

Error behavior

Direct provider calls and gateway calls intentionally differ:

Condition Direct Llm::driver(...)->send() Gateway / injected interface
Network error, retryable status, empty reply, refusal Returns provider fallback Tries the next provider
Missing API key Throws MissingApiKeyException Tries the next provider
Non-retryable provider rejection Throws ProviderRequestException Tries the next provider
Unknown driver in the configured chain Throws UnsupportedDriverException Throws immediately
Empty or malformed conversation history Throws InvalidArgumentException Throws immediately
Every configured provider fails Not applicable Returns aggregate fallback

ProviderRequestException exposes driver(), status(), and responseBody(). Its normal exception message deliberately excludes the raw response body; inspect responseBody() explicitly and avoid sending it to end users or untrusted logs.

MissingApiKeyException and ProviderRequestException extend LlmFailoverException, which extends RuntimeException. UnsupportedDriverException extends InvalidArgumentException for backwards compatibility.

Provider APIs

The bundled drivers currently target:

Driver API
Gemini models.generateContent
OpenAI POST /v1/chat/completions
Anthropic POST /v1/messages

This v1 package supports text conversations only. Streaming, tool calls, images/audio, structured-output helpers, embeddings, and provider-native server-side fallbacks are outside the current interface.

Postman collection

Import postman/laravel-llm-failover.postman_collection.json into Postman, set one or more API-key collection variables, and run the matching requests. Placeholder-key guards stop a request before it is sent, and each request includes response assertions.

The collection calls providers directly. It validates provider credentials and payload compatibility, but it does not run Laravel or test the package's failover chain. See POSTMAN_COLLECTION.md for detailed instructions and Newman usage.

Never commit real API keys to the collection or an exported Postman environment. Live runs may incur provider charges.

Testing and quality checks

The PHPUnit suite uses Laravel HTTP fakes and SQLite in memory; no API credentials or network access are required. CI covers the compatible Laravel/PHP combinations and runs Composer validation, tests, and static analysis. Dependency auditing runs on the currently security-supported Laravel 12 and 13 jobs.

Security

Please report security issues privately to the maintainer email listed in composer.json rather than opening a public issue.

Contributing

Contributions are welcome. Please include tests and update the relevant documentation when behavior changes.

Useful contribution areas include additional providers, failover strategies, richer response types, and performance improvements. Run composer check before submitting a pull request.

License

The MIT License. See LICENSE.md.


All versions of laravel-llm-failover with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
guzzlehttp/guzzle Version ^7.15.1
illuminate/support Version ^10.0|^11.0|^12.0|^13.0
illuminate/http Version ^10.0|^11.0|^12.0|^13.0
illuminate/database Version ^10.0|^11.0|^12.0|^13.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package tawshiqulislam/laravel-llm-failover contains the following files

Loading the files please wait ...