<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
unlikelysource / simplified-openrouter-php-sdk example snippets
use OpenRouter\Client;
use OpenRouter\DTO\ChatMessage;
// Reads OPENROUTER_API_KEY from the environment if not passed explicitly.
$client = new Client(apiKey: 'sk-or-...');
$response = $client->chat->create([
'model' => 'openai/gpt-4o-mini',
'messages' => [
ChatMessage::system('You are a helpful assistant.'),
ChatMessage::user('Say hello in three languages.'),
],
]);
echo $response->getContent();
$stream = $client->chat->createStreamed([
'model' => 'openai/gpt-4o-mini',
'messages' => [ChatMessage::user('Count to 5.')],
]);
foreach ($stream as $chunk) {
echo $chunk->getContentDelta();
}
use OpenRouter\DTO\InputReference;
// Image generation; tries each model in order. input_references is optional (likeness/style images).
$img = $client->images->generateWithFallback(
['qwen/qwen-image-3-pro', 'qwen/qwen-image-3'],
['prompt' => 'A lighthouse at dawn', 'size' => '1024x1024',
'input_references' => [InputReference::imageFromFile('ref.png')]],
);
file_put_contents('out.png', $img->first()->bytes());
echo $img->model; // the model that actually answered
// Text-to-speech with a cloned voice (reference clip + its exact transcript).
$speech = $client->speech->createWithFallback(
['fish-audio/s2.1-pro-free:free', 'fish-audio/s2.1-pro'],
['input' => 'Hello there.', 'input_references' => InputReference::voice('me.wav', 'exact words spoken in me.wav')],
);
$speech->save('hello.mp3');
use OpenRouter\Client;
use OpenRouter\Http\RetryConfig;
$client = new Client(
apiKey: 'sk-or-...',
baseUrl: 'https://openrouter.ai/api/v1', // e.g. https://eu.openrouter.ai/api/v1 for EU in-region routing
httpReferer: 'https://myapp.example', // sent as HTTP-Referer, used for OpenRouter app rankings
title: 'My App', // sent as X-Title
timeoutSeconds: 60.0,
retryConfig: new RetryConfig(maxAttempts: 4, initialIntervalMs: 500, maxIntervalMs: 60000),
);
$retryConfig = new RetryConfig(
maxAttempts: 3,
sleeper: function (int $ms): void {
$wake = microtime(true) + $ms / 1000;
while (microtime(true) < $wake) {
\Fiber::suspend(); // let the scheduler run other requests meanwhile
}
},
);
use OpenRouter\Exceptions\ApiException;
try {
$client->chat->create(['model' => 'openai/gpt-4o', 'messages' => [...]]);
} catch (ApiException $e) {
echo $e->getStatusCode(); // e.g. 429
echo $e->getMessage(); // the API's error message
echo $e->getMetadata(); // provider-specific error metadata, if any
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.