跳到正文
DEV Community· nRouter·· 4 天前AI 評分42

nRouter PHP 指南筆記:為何它不是一套 PHP SDK

The PHP SDK That Isn't One: Notes on nRouter's PHP Guide

AI 導讀

nRouter 的 PHP 指南使用標準 openai-php/client 連接閘道,而非提供自家 PHP 套件;整合只需設定 base URI 和虛擬金鑰。串流範例透過清除輸出緩衝並逐段呼叫 flush(),即時傳送內容。閘道錯誤會以帶有錯誤碼的型別例外呈現,成本則記錄在 x-nr-* 回應標頭中。

正文

Most gateway vendors ship a PHP package you have to learn. nRouter's PHP guide does something more honest: there is no nRouter PHP package. The guide configures the standard openai-php/client library — the client most PHP teams already use — and points it at the gateway.

Disclosure: I work on nRouter. The guide is here: https://nrouter.ai/docs/sdks/php

The whole integration is a factory call

Install the usual packages:

composer require openai-php/client guzzlehttp/guzzle

Then build the client with the gateway's base URI and your virtual key:

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

Every call after that is plain openai-php: $client->chat()->create([...]), read $response->choices[0]->message->content. The gateway speaks the OpenAI wire format, so the library you already know is the SDK. If your team later moves providers, nothing about the client code changes — the base URI and the key are the integration.

Streaming is a flushing discipline

PHP streaming has a classic trap: the tokens arrive, but the browser sees nothing until the script ends, because output buffering holds them. The guide's streaming example deals with it directly — it clears the output buffer, sends the text/event-stream header, then echoes each delta and calls flush() inside the loop:

$stream = $client->chat()->createStreamed([...]);

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

Small detail, but it is the difference between a stream that feels live and one that dumps the whole answer at the end.

Errors stay typed

Gateway refusals map to HTTP status codes, and in openai-php/client they surface as typed exceptions. The guide catches OpenAI\Exceptions\ErrorException and reads the gateway's error code and message off it:

} catch (ErrorException $e) {
    echo "API Error ({$e->getErrorCode()}): {$e->getMessage()}\n";
}

So a rejected key, an exhausted budget, or a rate limit arrives as a catchable exception with a code — not a malformed response you have to guess at.

The pattern worth keeping

A gateway that respects the ecosystem's standard client is making a claim about itself: the value is in the routing, the budgets, and the receipts (the guide tracks cost through the gateway's x-nr-* response headers), not in locking your codebase into a proprietary SDK. For PHP teams, that means the trial is an afternoon: change the factory call, keep everything else.

Guide: https://nrouter.ai/docs/sdks/php

來源:DEV Community · dev.to