Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/phpaisdk/openrouter/llms.txt

Use this file to discover all available pages before exploring further.

OpenRouterTextModel implements the PHP AI SDK’s TextModelInterface. It builds chat completion requests using the shared ChatRequestBuilder from aisdk/openai-compatible, sends them to the /chat/completions endpoint, and parses the response via ChatResponseParser (for standard completions) or ChatStreamParser (for streaming). This keeps the OpenRouter integration thin and consistent with all other OpenAI-compatible providers in the SDK ecosystem. Namespace: AiSdk\OpenRouter\Models
File: src/Models/OpenRouterTextModel.php

Constructor

public function __construct(
    private readonly string $modelId,
    private readonly OpenRouterOptions $options,
    private readonly ?ModelRegistry $registry = null,
)
modelId
string
required
The OpenRouter model identifier passed at construction, e.g. 'openai/gpt-4o' or 'anthropic/claude-sonnet-4'. Returned verbatim by modelId().
options
OpenRouterOptions
required
The provider configuration, including API key, base URL, and extra headers. See OpenRouterOptions.
registry
ModelRegistry|null
default:"null"
An optional model registry for overriding capability definitions at runtime. When null, capability lookups fall through to the bundled resources/models.json catalog.
OpenRouterTextModel instances are not normally created directly. Use OpenRouter::model() or OpenRouterProvider::textModel() instead.

Methods

provider()

public function provider(): string
Returns the canonical provider identifier. Returns: string — always 'openrouter'.

modelId()

public function modelId(): string
Returns the model identifier supplied at construction. Returns: string — the model ID, e.g. 'openai/gpt-4o'.

capabilities()

public function capabilities(): array<int, Capability>
Resolves the full list of capabilities supported by this model. The lookup order is:
  1. The injected ModelRegistry, if one was provided.
  2. The bundled resources/models.json catalog.
Returns: array<int, Capability> — an array of Capability enum cases supported by the model.

capability()

public function capability(Capability $capability): CapabilitySupport
Returns the support level for a single capability. The resolution order is:
  1. Any capability override configured directly on the model instance.
  2. The injected ModelRegistry.
  3. The bundled resources/models.json catalog.
As a special case, if the capability is Capability::TextGeneration and the model is not found in the catalog at all, the method returns CapabilitySupport::supported(...) with reason 'unknown-model-fallback'. This ensures that arbitrary OpenRouter-routed models are assumed to support text generation unless explicitly marked otherwise.
capability
Capability
required
The Capability enum case to check, e.g. Capability::TextGeneration, Capability::Reasoning, or Capability::ImageInput.
Returns: CapabilitySupport — the support level for the requested capability.

generate()

public function generate(TextModelRequest $request): TextModelResponse
Sends a non-streaming POST request to the chat completions endpoint and returns a fully parsed response. Internally:
  1. ChatRequestBuilder::build() serialises $request into an OpenAI-compatible JSON body with stream: false.
  2. The body is POSTed to Url::joinPath($options->baseUrl, '/chat/completions') with the headers from $options->authHeaders().
  3. ChatResponseParser::parse() maps the JSON payload to a TextModelResponse.
request
TextModelRequest
required
The text generation request, including messages, system prompt, temperature, and any other generation parameters.
Returns: TextModelResponse — contains text, usage (input/output token counts), finishReason, and providerMetadata['openrouter'] with raw fields such as id and model.

stream()

public function stream(TextModelRequest $request): Generator
Sends a streaming POST request to the chat completions endpoint and yields parsed chunks as they arrive. Internally:
  1. ChatRequestBuilder::build() serialises $request with stream: true.
  2. The body is POSTed to Url::joinPath($options->baseUrl, '/chat/completions') via postStream().
  3. ChatStreamParser::parse() reads the server-sent events and yields delta objects.
request
TextModelRequest
required
The text generation request. Identical in structure to the request accepted by generate().
Returns: Generator — yields parsed stream chunk objects containing delta text and finish information.

Endpoint

All requests are sent to:
POST {baseUrl}/chat/completions
The default resolved URL is:
POST https://openrouter.ai/api/v1/chat/completions

Usage Example

<?php

use AiSdk\Generate;
use AiSdk\OpenRouter;

OpenRouter::create([
    'apiKey'  => 'or-...',
    'headers' => ['HTTP-Referer' => 'https://example.com'],
]);

// Standard (non-streaming) generation
$result = Generate::text('What is the capital of France?')
    ->model(OpenRouter::model('openai/gpt-4o'))
    ->run();

echo $result->text;
echo $result->usage->inputTokens;
echo $result->providerMetadata['openrouter']['model'];
<?php

use AiSdk\Generate;
use AiSdk\OpenRouter;

OpenRouter::create(['apiKey' => 'or-...']);

// Streaming generation — process tokens as they arrive
$stream = Generate::text('Tell me a short story.')
    ->model(OpenRouter::model('anthropic/claude-sonnet-4'))
    ->stream();

foreach ($stream as $chunk) {
    echo $chunk->delta;
}
For a broader introduction to text generation and streaming, see the Text Generation and Streaming usage guides.

Build docs developers (and LLMs) love