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.

All requests to the OpenRouter API are authenticated with a Bearer token derived from your API key. The SDK resolves the key automatically — it reads from the OPENROUTER_API_KEY environment variable by default, or accepts an explicit apiKey entry in the config array passed to OpenRouter::create().

Obtaining an API key

Visit openrouter.ai, create an account, and navigate to the Keys section of your dashboard to generate a new key. OpenRouter API keys begin with the prefix or-.

Setting up authentication

1

Generate your API key

Log in to openrouter.ai and generate an API key from your account dashboard. Copy the key — it will only be shown once.
2

Set the environment variable

The recommended approach is to store your key in an environment variable so it is never hard-coded in source files.Add it to your .env file:
OPENROUTER_API_KEY=or-...
Or export it in your shell before running your application:
export OPENROUTER_API_KEY=or-...
The SDK reads this variable automatically via Env::loadApiKey(), so no additional code is required.
3

Verify the SDK picks it up

Once the environment variable is set, calling OpenRouter::default() (or any model helper) will instantiate a provider using that key without any explicit configuration:
use AiSdk\Generate;
use AiSdk\OpenRouter;

$result = Generate::text()
    ->model(OpenRouter::model('openai/gpt-4o'))
    ->prompt('Explain closures in PHP.')
    ->run();

echo $result->text;

Programmatic configuration

You can supply the API key directly in code by passing it to OpenRouter::create(). This is useful when you manage secrets through a dedicated secrets manager and inject them at runtime.
use AiSdk\OpenRouter;

OpenRouter::create([
    'apiKey' => 'or-...',
]);
OpenRouter::create() stores the resulting provider as the default singleton, so subsequent calls to OpenRouter::model() and OpenRouter::image() automatically use the key you provided.

How authentication works

Internally, the key is attached to every outgoing HTTP request via the OpenRouterOptions::authHeaders() method:
public function authHeaders(): array
{
    return array_merge(['Authorization' => 'Bearer '.$this->apiKey], $this->headers);
}
The Authorization: Bearer <key> header is merged with any custom headers you configure and sent on every request to the OpenRouter API.
Never commit your API key to version control. Use environment variables, a .env file that is listed in .gitignore, or a dedicated secrets manager such as AWS Secrets Manager or HashiCorp Vault.

Build docs developers (and LLMs) love