PHP code example of unlikelysource / simplified-openrouter-php-sdk

1. Go to this page and download the library: Download unlikelysource/simplified-openrouter-php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?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();
}

// Models
$models = $client->models->list(['limit' => 20, 'category' => 'programming']);
foreach ($models as $model) {
    echo "{$model->id}: {$model->contextLength} tokens\n";
}
$model = $client->models->get('openai', 'gpt-4o');
$count = $client->models->count();

// Endpoints (which providers serve a given model)
$endpoints = $client->endpoints->forModel('openai', 'gpt-4o'); // raw decoded array

// Generations
$generation = $client->generations->get('gen-abc123');
echo $generation->totalCost;

// Credits (g-3-small',
    'input' => 'Hello, world!',
]);
$vector = $result->data[0]->vector;

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),
);

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
}