Download the PHP package michaelfrank-dev/openrouter-php without Composer
On this page you can find all versions of the php package michaelfrank-dev/openrouter-php. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download michaelfrank-dev/openrouter-php
More information about michaelfrank-dev/openrouter-php
Files in michaelfrank-dev/openrouter-php
Package openrouter-php
Short Description Unofficial, PSR-compliant PHP SDK for the OpenRouter API
License MIT
Homepage https://github.com/michaelfrank-dev/openrouter-php
Informations about the package openrouter-php
OpenRouter PHP SDK
[!WARNING] This is an unofficial, community-maintained PHP SDK for the OpenRouter API. It is not maintained by OpenRouter.
A framework-agnostic, strictly typed PHP SDK for the OpenRouter API. Fully compliant with PSR-12 coding standards, leveraging PSR-18 HTTP Client and PSR-17 HTTP Factory standards for interoperability.
[!NOTE] This SDK does not yet have all OpenRouter endpoints and options implemented. Currently implemented features and endpoints include:
- Chat Completions: Standard completions (
completions) and real-time SSE streaming (streamCompletions).- Provider Routing & Fallbacks: Model fallbacks, provider sorting (price, throughput, latency), percentile cutoffs, and max pricing.
- Server-Side Tools: Model-driven Web Search (
OpenRouterWebSearchTool), Web Fetch (OpenRouterWebFetchTool), Image Generation (OpenRouterImageGenerationTool), and SpaceXAI X Search (SpaceXXSearchTool).- Routing-Level Grounding & Filters: Model-agnostic web search options (
WebSearchOptions) and X/Twitter search filtering (XSearchFilter).- Client-Side Tool Calling: Function definitions (
ToolDefinition) and multi-turn tool message handling.- Models & Endpoints Discovery: Listing and querying models (
models), image generation models catalog (imageModels), and per-endpoint capabilities & pricing (imageModelEndpoints).- Text Embeddings: Generating vector embeddings (
embeddings).- Document Reranking: Scoring and reordering documents based on search queries (
rerank).- Audio (Speech & Transcriptions): Text-to-speech synthesis with direct file export (
speech) and audio file transcription (transcriptions).- Image Generation: Standalone text-to-image generation (
images) and streaming generation events (streamImages).- Account & Generation Analytics: Checking credit balance (
credits) and looking up generation stats by ID (generation).- Response Metadata & Rate Limits: Automatic extraction of request IDs and rate limit headers (
X-RateLimit-*).
Features
- Pure PSR-18 / PSR-17 Dependency Injection
- Static analysis typing (PHPStan level 9, Psalm level 1)
- Request-side extensible wrappers (no hardcoded enums for API-extensible keys)
- Immutable option and request configurations
- Fully supports completions, streaming, embeddings, reranking, speech, transcriptions, image generation, and key checking
- OpenRouter-native features: routing preferences, fallback models, server tools (Web Search & Fetch)
- Strict client-side request validation (e.g., verifying mutually exclusive search engine constraints)
- Built-in Response Metadata & Rate limit tracking
Installation
Install the package via Composer:
Make sure you have a PSR-18 HTTP client (like Guzzle) and PSR-17 factories installed:
Usage Examples
[!TIP] For local development and testing, create a dedicated API key with a low credit/spending limit in your OpenRouter Key Settings to limit financial exposure.
Initialization via Discovery
Provider Sort by Price
Latency/Throughput Constraints and Max Price
Fallback / Multi-model Routing
Filtering and Querying Models list
Server-Side Tools (Web Search, Fetch & Image Generation)
OpenRouter supports server-side tools that allow the model to interact directly with web content.
[!NOTE] Key Difference between Server-Side Tools (6a) and Routing Options (6b):
- Server-Side Tools (6a) are agentic. The model decides dynamically during generation if and when it needs to run a web search or fetch a URL, constructing the query or URL based on context.
- Routing-Level Grounding & Filters (6b) are pre-configured. They pre-inject search context before the model starts generating, or apply static platform-wide filters (like X/Twitter filtering constraints for Grok) without requiring tool-calling logic from the model.
Web Search Server Tool
Pass OpenRouterWebSearchTool to give the model real-time search capabilities. It supports customizable parameters for engines like Exa, Parallel, Perplexity, or native provider search:
[!NOTE] The
userLocationparameter only geographically biases the search engine results (currently supported by native provider search). It does not inject location context into the model's reasoning.[!IMPORTANT] Domain Filtering Engine Compatibility:
- Exa: Supports specifying both
allowedDomainsandexcludedDomainssimultaneously.- Parallel, Firecrawl, and Perplexity: Treat
allowedDomainsandexcludedDomainsas mutually exclusive. The SDK throws aValidationExceptionif you attempt to specify both in the same request.- Native: Support depends on the specific provider (many native provider search models do not support domain filtering).
Web Fetch Server Tool
Pass OpenRouterWebFetchTool to fetch the contents of a specific URL directly during completion:
[!NOTE] For the Web Fetch tool,
allowedDomainsrestricts URL retrieval to only those specific domains, whileblockedDomainsexplicitly rejects matching URLs. Both parameters can be defined simultaneously to establish precise boundary controls.
Image Generation Server Tool
Pass OpenRouterImageGenerationTool to allow any supported model to dynamically generate images during completion:
Model-Agnostic Web Search Options & Filters (Routing Level)
For native provider grounding/web search context size control:
X/Twitter Search with SpaceXAI Grok Models
To enable X/Twitter search for SpaceXAI Grok models, configure xSearch on OpenRouterWebSearchTool. You can enable X Search with no filters (using true or new XSearchFilter()), or specify filters (allowedXHandles, excludedXHandles, fromDate, toDate) to limit which posts are fetched:
On the Responses API (or completions), you can also pass SpaceXAI's native tool directly:
[!NOTE] If you use the
webplugin instead of server tools, the same configuration goes on the plugin:plugins: [['id' => 'web', 'x_search' => XSearchFilter::enabled()]].[!WARNING] SpaceXAI Pricing & Top-Level Filter Deprecation:
- Default behavior: Web Search requests only perform web search unless
xSearchis explicitly configured. You are not charged for X Search if it is not enabled.- Pricing: X Search is billed at $5 per 1,000 posts fetched and $10 per 1,000 user profiles fetched (filters limit fetched posts, which limits cost).
- Deprecation: The top-level
withXSearchFilter()option is deprecated by OpenRouter in favor of configuringxSearchinsideOpenRouterWebSearchToolor web plugins. Existing requests usingwithXSearchFilter()remain supported for backwards compatibility.
Streaming Response Chunks (Guzzle Example)
To stream completions, pass a non-buffering client (configured with 'stream' => true in Guzzle) to the factory:
Text Embeddings
Reranking Documents
Text-to-Speech (Audio Synthesis)
Speech-to-Text (Transcriptions)
Image Generation
Client-Side Tool Calling (Fictional Weather Tool)
Accessing Response Metadata & Rate Limits
[!NOTE] Response metadata (like
rateLimitandrequestId) is extracted automatically by the SDK from the HTTP response headers (X-RateLimit-*andX-Generation-Id). Because of this,$metadata->requestIdduplicates the main$response->id(which is returned in the JSON body payload). The SDK captures both for consistency across all endpoint responses.
Checking Credit Balance & Generation Stats
Image Generation Models & Endpoints Discovery
You can discover available image models and their per-endpoint details (supported parameters, billing lines, passthrough capabilities):
Error Handling
All custom exceptions thrown by the SDK implement the MichaelFrank\OpenRouter\Exceptions\OpenRouterException interface. You can catch specific exceptions to handle different failure modes:
| Exception | Description | Helper Methods |
|---|---|---|
ValidationException |
Thrown if client inputs or request configurations fail validation. | None |
ConfigurationException |
Thrown for configuration issues (e.g. non-HTTPS URI in production). | None |
NetworkException |
Thrown when a PSR-18 network/communication error occurs. | getPrevious() (returns underlying PSR-18 client exception) |
ApiRequestException |
Thrown when the OpenRouter server returns an HTTP status code >= 400. |
getStatusCode(), getResponseBody(), getMetadata() |
ApiResponseException |
Thrown when the response payload is malformed or contains an in-body error. | getResponseBody(), getMetadata() |
Handling Errors & Extracting Metadata Example:
Running Quality Pipeline Locally
Or individual checks:
All versions of openrouter-php with dependencies
ext-json Version *
psr/http-client Version ^1.0
psr/http-factory Version ^1.0
psr/http-message Version ^1.0||^2.0
php-http/discovery Version ^1.19