Browse documentation

PHP SDK

Connect PHP applications to nRouter using openai-php/client. Configure custom base URLs, manage API authentication, and access hundreds of top AI models.

Last updated

nRouter works with openai-php/client. Set the base URI to https://api.nrouter.ai/v1 and pass your sk-nrouter-... key — guardrails, caching, and rate-limits auto-apply from your org config.

Installation

composer require openai-php/client

Setup

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

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

Chat Completion

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

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

Per-Request Overrides

openai-php/client forwards unknown keys, so nrouter_* fields work inline:

<?php
// Run a prompt template with variables
$response = $client->chat()->create([
    'model' => 'gpt-5.5',
    'messages' => [['role' => 'user', 'content' => 'Q1 revenue was $4.2M...']],
    'nrouter_prompt_template_id' => 'your-summarizer-id',
    'nrouter_prompt_variables' => ['language' => 'Spanish', 'max_length' => '100'],
]);

// Bypass cache for a single call
$response = $client->chat()->create([
    'model' => 'gpt-5.5',
    'messages' => [['role' => 'user', 'content' => 'What is the latest news?']],
    'nrouter_cache' => false,
]);

Guardrails are not among these keys. You assign them in the dashboard at key, team, or organization scope — the narrowest scope that mentions a guardrail wins — and they run automatically on every request that scope covers.

Error Handling

<?php
try {
    $client->chat()->create([
        'model' => 'gpt-5.5',
        'messages' => [['role' => 'user', 'content' => 'My SSN is 123-45-6789']],
    ]);
} catch (\Exception $e) {
    // "guardrail_blocked" — guardrail rejected the request
    // "insufficient_credits" — top up to continue
    echo "Error: {$e->getMessage()}\n";
}

Response Headers

Every successful response carries:

  • x-nr-request-id — id for this call, and the join key for its spend row
  • x-nr-model — the model that actually served the request
  • x-nr-cost-statusexact when we priced the call, unpriced when we could not
  • x-nr-request-cost — USD spend for this call. Absent when x-nr-cost-status is unpriced: nRouter never reports a cost of 0 for a call it could not price
  • x-nr-input-tokens, x-nr-output-tokens, x-nr-total-tokens — token counts as reported by the provider

Next Steps

Was this page helpful?