PHPackages                             unlikelysource/simplified-openrouter-php-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. unlikelysource/simplified-openrouter-php-sdk

ActiveLibrary

unlikelysource/simplified-openrouter-php-sdk
============================================

Unofficial PHP SDK for the OpenRouter.ai API, modeled after the official Python SDK.

v0.0.1(yesterday)00MITPHPPHP ^8.1

Since Jul 30Pushed yesterdayCompare

[ Source](https://github.com/dbierer/simplified_openrouter_php_sdk)[ Packagist](https://packagist.org/packages/unlikelysource/simplified-openrouter-php-sdk)[ Docs](https://github.com/dbierer/openrouter_php_sdk)[ RSS](/packages/unlikelysource-simplified-openrouter-php-sdk/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

simplified\_openrouter\_php\_sdk
================================

[](#simplified_openrouter_php_sdk)

An unofficial PHP SDK for the [OpenRouter.ai](https://openrouter.ai) API, modeled after the [official Python SDK](https://github.com/OpenRouterTeam/python-sdk). This is a hand-written, idiomatic PHP client, not a generated 1:1 port — covering the core of the OpenRouter API:

- **Chat Completions** — including streaming
- **Models** — list, get, count
- **Endpoints** — list provider endpoints for a model
- **Generations** — request/usage metadata lookup
- **Credits** — account balance
- **API Keys** — full CRUD (management key required)
- **Embeddings**

The Python SDK is auto-generated from OpenRouter's OpenAPI spec and covers ~90 endpoint groups (TTS/STT, video generation, OAuth, workspaces, BYOK, datasets, guardrails, analytics, and more). This simplified PHP SDK, by design, covers only the subset most developers need. The architecture (a `Transport`class plus one resource class per endpoint group) makes it straightforward to add more resources later if you need them. Contributions welcome!

This SDK leverages the Guzzle HTTP client, and produces PSR-7 compliant requests and responses. IMPORTANT: this is an Alpha release. If you need something more stable and production-ready, consider using [eatzy/openrouter-php-sdk](https://packagist.org/packages/eatzy/openrouter-php-sdk) instead.

Requirements
------------

[](#requirements)

- PHP 8.1+
- [Composer](https://getcomposer.org)

Installation
------------

[](#installation)

```
composer require unlikelysource/simplified-openrouter-php-sdk
```

Quick start
-----------

[](#quick-start)

```
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();
```

Streaming
---------

[](#streaming)

```
$stream = $client->chat->createStreamed([
    'model' => 'openai/gpt-4o-mini',
    'messages' => [ChatMessage::user('Count to 5.')],
]);

foreach ($stream as $chunk) {
    echo $chunk->getContentDelta();
}
```

`createStreamed()` returns a `ChatCompletionStream`, an `IteratorAggregate` that lazily parses the API's `text/event-stream` response and yields one `ChatCompletionChunk` per server-sent event, stopping automatically at the `[DONE]` sentinel.

Request parameters
------------------

[](#request-parameters)

`chat->create()` / `chat->createStreamed()` accept the request body as a plain associative array, matching the [OpenRouter Chat Completions API](https://openrouter.ai/docs/api-reference/chat-completion)directly (`model`, `messages`, `temperature`, `max_tokens`, `tools`, `tool_choice`, `provider`, `reasoning`, `response_format`, etc.) — nothing is hidden behind a rigid DTO, so any parameter the API supports can be passed through as-is. `messages` entries may be plain arrays or `OpenRouter\DTO\ChatMessage` instances (`ChatMessage::system()`, `::user()`, `::assistant()`, `::tool()`).

Resources
---------

[](#resources)

```
// 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 (requires a management API key)
$credits = $client->credits->get();
echo $credits->getRemaining();

// API keys (requires a management API key)
$key = $client->apiKeys->create(['name' => 'my-app-key', 'limit' => 10.0]);
echo $key->key; // plaintext key — only ever available on the create() response
$client->apiKeys->update($key->hash, ['disabled' => true]);
$client->apiKeys->delete($key->hash);
foreach ($client->apiKeys->list() as $k) { /* ... */ }

// Embeddings
$result = $client->embeddings->create([
    'model' => 'openai/text-embedding-3-small',
    'input' => 'Hello, world!',
]);
$vector = $result->data[0]->vector;
```

See `examples/` for complete runnable scripts.

Configuration
-------------

[](#configuration)

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

You can also inject your own Guzzle client (e.g. with custom middleware or a mock handler for testing) via the `httpClient` constructor argument.

Error handling
--------------

[](#error-handling)

Requests that receive an HTTP error status throw a subclass of `OpenRouter\Exceptions\ApiException`, mapped by status code (`BadRequestException`, `UnauthorizedException`, `PaymentRequiredException`, `ForbiddenException`, `NotFoundException`, `TooManyRequestsException`, `InternalServerException`, etc.):

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

Connection-level failures (DNS, timeouts, refused connections) that persist after retries are exhausted throw `OpenRouter\Exceptions\TransportException` instead.

5xx responses are retried automatically with exponential backoff (defaults: up to 4 attempts, starting at 500ms, capped at 60s, 1.5x multiplier) before an exception is raised.

Development
-----------

[](#development)

```
composer install
composer test
```

License
-------

[](#license)

MIT. Not affiliated with or endorsed by OpenRouter.

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity32

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5cc452b785bbadbfc9c3387d0dce79c03cd2ebe7fdac153b1f589901d7b17336?d=identicon)[unlikelysource](/maintainers/unlikelysource)

---

Top Contributors

[![dbierer](https://avatars.githubusercontent.com/u/1141370?v=4)](https://github.com/dbierer "dbierer (1 commits)")

---

Tags

sdkaillmOpenRouterchat-completions

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/unlikelysource-simplified-openrouter-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/unlikelysource-simplified-openrouter-php-sdk/health.svg)](https://phpackages.com/packages/unlikelysource-simplified-openrouter-php-sdk)
```

###  Alternatives

[aws/aws-sdk-php

AWS SDK for PHP - Use Amazon Web Services in your PHP project

6.2k543.5M2.7k](/packages/aws-aws-sdk-php)[neuron-core/neuron-ai

The PHP Agentic Framework.

2.0k656.1k48](/packages/neuron-core-neuron-ai)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k17](/packages/tempest-framework)[spatie/laravel-export

Create a static site bundle from a Laravel app

674146.0k6](/packages/spatie-laravel-export)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

293.1k](/packages/eslazarev-wildberries-sdk)[oat-sa/tao-core

TAO core extension

65143.7k124](/packages/oat-sa-tao-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
