Download the PHP package ferdiunal/laravel-ai-router without Composer

On this page you can find all versions of the php package ferdiunal/laravel-ai-router. 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-ai-router

Laravel AI Router

English | Türkçe

Laravel AI Router is a Laravel AI SDK text provider that routes prompts through locally managed provider keys, available-model caches, fallback metadata, rate-limit windows, and usage analytics. It is designed for applications that want one Laravel AI provider name (laravel-ai-router) while using multiple OpenAI-compatible providers and multiple labeled API keys behind a local routing layer.

The package stores its own operational state in a dedicated package database connection by default. The default storage target is database/laravel-ai-router.sqlite, which keeps provider keys, model cache rows, fallback routing rows, rate-limit counters, usage records, runtime custom provider definitions, and package settings out of the host application's main tables.

What this is / what this is not

Laravel AI Router is a Laravel AI SDK text-provider router. It is not a standalone OpenAI-compatible HTTP proxy and it does not expose /v1/chat/completions or /v1/models routes. Host applications call it through Laravel AI (ai()->using('laravel-ai-router', 'auto')), and the package routes those calls to configured provider keys.

Built-in routable providers in this release are limited to adapters that are implemented and covered by tests:

Provider Adapter
Google AI Studio Native Gemini generateContent / streamGenerateContent
Cohere OpenAI-compatible compatibility API
Groq OpenAI-compatible
Cerebras OpenAI-compatible
SambaNova OpenAI-compatible
NVIDIA NIM OpenAI-compatible, seeded disabled by default
Mistral OpenAI-compatible
OpenRouter OpenAI-compatible
GitHub Models OpenAI-compatible
Cloudflare Workers AI Account-scoped OpenAI-compatible Workers AI endpoint
Zhipu AI OpenAI-compatible
Ollama Cloud OpenAI-compatible
Kilo Gateway OpenAI-compatible, anonymous placeholder key supported
Pollinations OpenAI-compatible, anonymous placeholder key supported
LLM7 OpenAI-compatible, anonymous placeholder key supported

Google AI Studio uses Google API-key query authentication. Cloudflare Workers AI asks for the account ID separately from the API token; the token is encrypted as the provider key and the account ID is stored as credential metadata so the adapter can build account-scoped Workers AI URLs without packing both values into one secret.

Free-tier and anonymous providers can change limits, model availability, authentication behavior, or terms of service without notice. Treat free-tier routing as development/prototype infrastructure unless you have reviewed each upstream provider's terms, quota, and SLA posture for your production use case.

Features

Requirements

The package is a Laravel package and is auto-discovered through the service provider declared in composer.json.

Installation

The install command performs the package setup in this order:

  1. Creates the configured SQLite file when the package connection targets SQLite storage.
  2. Runs the package-owned internal migrations against the configured package connection.
  3. Seeds the curated model catalog and fallback ordering rows.
  4. Applies safe SQLite PRAGMA optimizations when enabled and applicable.
  5. Starts the provider-key setup wizard in an interactive console.

By default, no migration file has to be published into the host application's database/migrations directory. The package migrations are internal package migrations and are executed by laravel-ai-router:install against the package connection.

Configuration

Publish the package config only when you need to override defaults:

Register the provider in config/ai.php:

The package config keeps auto as the default text model:

Package database connection

The default package connection name is laravel-ai-router. When this connection name is used, the service provider registers a dedicated SQLite connection backed by database/laravel-ai-router.sqlite unless you override the SQLite path.

Use LARAVEL_AI_ROUTER_DB_CONNECTION only when you intentionally want package-owned state to live on an existing host connection. The value laravel-ai-router means the package's default dedicated SQLite connection.

Provider Key Management

Provider keys are identified by provider + label. This allows multiple keys for the same provider, for example openrouter / Primary, openrouter / Backup, or groq / Team.

laravel-ai-router:provider:add uses Laravel Prompts to collect:

  1. Provider platform.
  2. Provider-specific credential metadata when required, for example Cloudflare account ID.
  3. API key or API token.
  4. Provider-key label.
  5. Optional multi-select of cached available models that should participate in auto / random_provider routing.

The raw API key is encrypted before persistence and is never rendered in command output. Lists and prompts show masked credentials only.

Use laravel-ai-router:provider:sync for operational health checks. It requires an explicit target (--all, --provider=openrouter, or --key-id=1), validates the stored credential, optionally refreshes the provider model cache, reports selected auto-model counts, and includes a local_estimate quota snapshot from package-owned rate/token windows. Default table output is model-level: each selected auto-routing model gets its own row with blocked status, RPM/RPD/TPM/TPD remaining limits, and cooldown. Add --no-refresh-models to validate credentials and local quota without model discovery, --fail-on-invalid for CI/ops checks, and --json for stable secret-free automation output with the same model quota data nested under quota.models. The command never prints raw API keys, bearer tokens, or composed credentials.

Cloudflare Workers AI stores account_id separately in credential_metadata while encrypting only the API token in the key field. During routing and model discovery the package composes the adapter-facing account_id:api_token credential internally, then sends only the token as the upstream bearer credential. Legacy account_id:api_token input is still split into separate storage fields when adding a key.

Runtime Custom OpenAI-compatible Providers

Runtime custom providers let you add OpenAI-compatible gateways, proxies, or providers without changing package code.

A runtime provider definition contains:

Security constraints are enforced before persistence and before request dispatch:

You can also define static custom providers in config:

When a routable OpenAI-compatible provider returns model IDs from its /models endpoint, Laravel AI Router can cache those model IDs by provider + label and create runtime model/fallback rows so they can participate in exact model routing.

For OpenAI-compatible gateways that do not provide a compatible /models endpoint, disable live model discovery and declare the routable chat models explicitly. You can set those fields while adding the provider definition or update them later:

Declared model rows are cached with source definition when provider keys are refreshed. Exact model routing can use declared models. For auto / random_provider, either include auto_enabled: true in declared model JSON metadata or select the cached rows later with php artisan laravel-ai-router:provider:models; simple comma-separated IDs remain exact-routeable but are not auto-selected by default.

Model Cache and Auto Routing Selection

Provider model caches are scoped by provider key. A cache row stores the provider platform, provider label, model ID, display name, context window, rate limits, token limits, free-tier marker, tool support marker, source, and refresh timestamp.

Refresh and inspect the cache with:

The command can refresh the selected key's cache, list cached available models, and edit which rows are selected for auto / random_provider routing. Model listing and auto selection expose only rows that match all of these constraints:

Live model discovery is provider-agnostic for routable providers: valid /models rows are cached even when their IDs do not end in :free. Free-tier status is stored as metadata (is_free); NVIDIA NIM live rows are marked as free credit-backed models (free + credits-based), while other non-free live rows default to the credits-based budget label. Exact live model IDs are routeable directly, even when the cache row is not selected for auto. Automatic routing is narrower than cache visibility: newly refreshed rows are selected for auto only when they match the provider adapter's chat contract and the package's provider-specific safe policy. Google AI Studio auto selection is limited to stable Gemini generateContent models (gemini-2.5-flash, gemini-2.5-flash-lite); embeddings, media, live/Interactions, and unprobed preview/pro models stay cached for visibility but are not auto-selected. Cloudflare Workers AI auto selection is limited to the conservative Workers AI chat-completions baseline until additional models are verified by a live probe. Review each upstream provider's quota and billing terms before using key-backed providers in production.

The package config default remains auto. The random_provider strategy first randomizes selected provider keys and then randomizes the selected models inside the chosen provider, so a provider with many selected rows does not automatically outweigh a provider with one selected row. The legacy random strategy is still available when you explicitly want model-row weighted fallback-list shuffling; priority and balanced_random are also preserved.

Programmatic model access:

Prompt Usage

Before sending prompts, run the install/setup flow and add at least one enabled provider key:

Laravel AI Router can be called in two ways:

  1. The package convenience helper: ai()->using(...)->prompt(...)->asText().
  2. Native Laravel AI agents: classes that implement Laravel\Ai\Contracts\Agent and use Laravel\Ai\Promptable.

Quick Tinker usage with the ai() helper

The package ships a global ai() helper for Tinker and small application call sites. It returns Laravel AI Router's convenience helper, not Laravel AI SDK's facade.

auto lets Laravel AI Router choose from the provider-key/model cache rows selected for automatic routing. By default the auto chain uses routing.auto_strategy=random_provider: it shuffles selected provider keys first, then shuffles selected models within the chosen provider while still enforcing disabled/invalid-key skips, model-cache compatibility, tool support, cooldowns, and rate/token-limit checks. Set LARAVEL_AI_ROUTER_AUTO_STRATEGY=priority for deterministic fallback order, random for legacy model-row weighted fallback-list shuffling, or balanced_random to shuffle only the configured top fallback pool (LARAVEL_AI_ROUTER_RANDOM_POOL_SIZE, bounded by LARAVEL_AI_ROUTER_RANDOM_PRIORITY_WINDOW). Exact model calls can still route to a cached model ID that was not selected for auto, as long as the provider key/cache/model is healthy.

You can also route an exact cached model ID:

When you need the full Laravel AI response instead of only text, call response():

The helper also exposes the underlying Laravel AI manager when you need low-level SDK access:

Unknown method calls on ai() are proxied to the underlying Laravel\Ai\AiManager, so ai()->textProvider('laravel-ai-router') also works.

Native Laravel AI agent usage

For production code, a named agent class is usually easier to test and reuse:

You can still override provider/model per call:

Failover usage through Laravel AI provider arrays:

Retryable rate-limit, temporary overload, timeout, and insufficient-credit conditions are mapped to Laravel AI failover-compatible exception types where applicable.

Function Tools

Laravel AI Router supports non-streaming OpenAI-compatible tool calls. Tools are regular Laravel AI Tool classes; the router maps their schema to OpenAI-compatible tools, executes requested calls locally, and sends tool result messages back to the selected provider.

Streaming tool calls are intentionally not supported yet. Use prompt() / asText() / response() for tool workflows. Calling stream() with tools fails before opening the upstream stream.

Define a tool

name() is optional in the Tool contract, but recommended. If it is missing, Laravel AI derives the tool name from the class basename.

Use tools with the ai() helper

Use tools with a named agent

Streaming Usage

Laravel AI Router supports text streaming through Laravel AI stream events:

The same behavior is available through named agents:

Structured Output Usage

Laravel AI Router supports Laravel AI structured output for non-streaming text requests. The package sends JSON-mode style options upstream and maps valid JSON content back into Laravel AI structured response objects.

Laravel AI SDK Capability Matrix

Capability Status Notes
Text generation Supported Returns Laravel AI TextResponse or StructuredTextResponse, including usage and metadata.
Text streaming Supported Converts OpenAI-compatible SSE chunks into Laravel AI StreamStart, TextStart, TextDelta, TextEnd, and StreamEnd events.
Structured output Supported Sends JSON-mode style options and maps valid JSON content into Laravel AI structured response types.
Function tools Supported for non-streaming Executes OpenAI-compatible tools / tool_calls loops and sends tool result messages back to the provider.
Streaming tools Not supported Fails before opening the upstream stream with a clear LogicException.
Failover Supported Retries eligible internal provider keys up to routing.max_attempts, then maps rate limits, insufficient credit/quota, timeout, and overload errors to Laravel AI failover exception types. auto defaults to provider-first random rotation across selected cached provider-key/model rows; priority, legacy model-row random, and bounded balanced_random remain available without bypassing key/cache/limit eligibility checks.
Images, audio, transcription, embeddings, reranking, files, stores Not supported The package advertises only the text provider contract and throws explicit capability errors for unsupported methods.

Usage Analytics

Display usage analytics with:

Tracked fields include:

Usage rows are stored in package-owned storage and can be used to inspect provider reliability, model distribution, latency, token volume, and error trends.

Retention and pruning

Laravel AI Router keeps usage rows for LARAVEL_AI_ROUTER_USAGE_RETENTION_DAYS days by default and rate-window/cooldown rows for LARAVEL_AI_ROUTER_RATE_WINDOW_RETENTION_DAYS days by default. Prune old package storage rows with:

Use --vacuum only when you explicitly want SQLite to compact the package database after pruning:

SQLite Optimization and Package Storage

When the package connection uses SQLite and optimization is enabled, the package applies bounded PRAGMA settings:

Relevant config shape:

Internal migrations are idempotent enough to tolerate existing package tables on the package connection. They do not need to be published into host application migrations.

Security Model

Upgrade Notes

Earlier versions exposed publishable migration stubs for host application migrations. The current install flow keeps package-owned migrations internal and executes them through laravel-ai-router:install against the package connection.

If you previously published package migration stubs into the host application's database/migrations directory and stored Laravel AI Router data in host tables, the new install command will not automatically move that data into the dedicated package database. To preserve existing provider keys, usage rows, model cache rows, or settings:

  1. Back up the host database.
  2. Install or update the package.
  3. Run php artisan laravel-ai-router:install to prepare the package storage.
  4. Write and run a one-off migration or command that copies the old host rows into the package connection tables.
  5. Verify provider-key encryption, model cache freshness, and usage analytics after the migration.

Development and Validation

composer ci runs formatting checks, PHPStan analysis, and the full Pest test suite.

Troubleshooting

The package SQLite database file is missing

Run:

If you use a custom path, verify LARAVEL_AI_ROUTER_SQLITE_DATABASE points to a writable location and that the parent directory can be created by the application user.

A provider key is marked invalid

Authentication failures during model refresh or routed requests mark the selected key invalid. Add a new key or re-enable/update the key after verifying the credential with the provider.

Cached models are not shown

laravel-ai-router:provider:models exposes only routable, enabled, non-invalid, non-expired cache rows for the selected provider key. Refresh the selected key's cache and verify the provider adapter is implemented.

Streaming tools fail before the provider stream opens

Streaming tool calls are intentionally unsupported. Use non-streaming text generation when tools are required.

A custom provider base URL is rejected

Ensure the URL uses public HTTPS, has no credentials/query/fragment, does not point to localhost or private/reserved networks, and resolves only to public IP addresses.


All versions of laravel-ai-router with dependencies

PHP Build Version
Package Version
Requires php Version ^8.4
illuminate/console Version ^13.0
illuminate/contracts Version ^13.0
illuminate/database Version ^13.0
illuminate/http Version ^13.0
illuminate/support Version ^13.0
laravel/ai Version ^0.7
laravel/prompts Version ^0.3.6
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 ferdiunal/laravel-ai-router contains the following files

Loading the files please wait ...