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.

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 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


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 userLocation parameter 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 allowedDomains and excludedDomains simultaneously.
  • Parallel, Firecrawl, and Perplexity: Treat allowedDomains and excludedDomains as mutually exclusive. The SDK throws a ValidationException if 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, allowedDomains restricts URL retrieval to only those specific domains, while blockedDomains explicitly 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 web plugin 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 xSearch is 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 configuring xSearch inside OpenRouterWebSearchTool or web plugins. Existing requests using withXSearchFilter() 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 rateLimit and requestId) is extracted automatically by the SDK from the HTTP response headers (X-RateLimit-* and X-Generation-Id). Because of this, $metadata->requestId duplicates 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

PHP Build Version
Package Version
Requires php Version ^8.2
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
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 michaelfrank-dev/openrouter-php contains the following files

Loading the files please wait ...