Browse documentation

PHP SDK

Connect PHP applications to nRouter using openai-php/client. Configure custom base URLs, manage API authentication, and reach top AI models with one key.

Connect PHP applications to the nRouter unified AI gateway (https://api.nrouter.ai/v1) using the standard openai-php/client library. Set your NROUTER_API_KEY, dispatch completions across OpenAI, Anthropic, Gemini, and Bedrock models, stream tokens with low latency, and track x-nr-* costs.

Installation

Install via Composer:

composer require openai-php/client guzzlehttp/guzzle

Set your virtual API key:

export NROUTER_API_KEY="sk-nrouter-xxxxxxxxxxxx"

Chat Completion

Point the client factory to https://api.nrouter.ai/v1:

<?php
require 'vendor/autoload.php';

use OpenAI;

$client = OpenAI::factory()
    ->withApiKey(getenv('NROUTER_API_KEY'))
    ->withBaseUri('https://api.nrouter.ai/v1')
    ->make();

$response = $client->chat()->create([
    'model' => 'gpt-5.4-mini',
    'messages' => [['role' => 'user', 'content' => 'Hello, nRouter!']],
]);

echo $response->choices[0]->message->content . "\n";

SSE Streaming

Stream token chunks directly with immediate output flushing:

<?php
require 'vendor/autoload.php';

if (ob_get_level() > 0) ob_end_clean();
header('Content-Type: text/event-stream');

$client = OpenAI::factory()
    ->withApiKey(getenv('NROUTER_API_KEY'))
    ->withBaseUri('https://api.nrouter.ai/v1')
    ->make();

$stream = $client->chat()->createStreamed([
    'model' => 'claude-haiku-4-5-20251001',
    'messages' => [['role' => 'user', 'content' => 'Write a short poem.']],
]);

foreach ($stream as $response) {
    echo $response->choices[0]->delta->content;
    flush();
}

Error Handling

Gateway refusals map to HTTP status codes — see Errors & Rate Limits. In openai-php/client they raise typed exceptions:

use OpenAI\Exceptions\ErrorException;

try {
    $response = $client->chat()->create([
        'model' => 'gpt-5.4-mini',
        'messages' => [['role' => 'user', 'content' => 'Run task.']],
    ]);
} catch (ErrorException $e) {
    echo "API Error ({$e->getErrorCode()}): {$e->getMessage()}\n";
}

Next Steps

Was this page helpful?