OpenAI Node SDK
The OpenAI Node SDK is the openai npm package for JavaScript and TypeScript apps on Node.js, Deno and Bun. Pointed at the Spanway gateway, the same code reaches any model the gateway serves, OpenAI or not, while your admin controls which models the app may use, its budget and its rate limit. The app holds one virtual key and never a provider key.
A real-world scenario
A product team runs a Next.js backend that writes product descriptions with client.chat.completions.create. The company wants every model call budgeted per product and logged in one place. The admin creates a key named catalog-writer with a 150 USD monthly budget. The team sets OPENAI_BASE_URL and OPENAI_API_KEY in the deployment's environment, and the next release goes through the gateway with no code change. When a batch job loops by mistake, the key's rate limit stops it and the job logs a RateLimitError naming the limit.
Prerequisites
- A running gateway and its address, written here as
https://gateway.example.com. - At least one model registered on the gateway under a public name, for example
gpt-6.1-sol. - Node.js 22 or later and the SDK, installed with
npm install openai.
Make a key for this app
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - Under Key Details, set Key Name to the app's name, such as
catalog-writer, and leave Key Type on AI APIs. - In Models, pick every public model name the app calls, including the small model you use for background jobs such as tagging or summaries, for example
claude-haiku-5-5. - Open Optional Settings and set Max Budget (USD) with Reset Budget, for example 150 USD monthly, and Requests per minute Limit (RPM), for example 60. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (
Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage. - Click Create Key and copy the key. It is shown once.
The same key from the API:
curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "catalog-writer", "key_type": "llm_api", "models": ["gpt-6.1-sol", "claude-haiku-5-5"], "max_budget": 150, "budget_duration": "30d", "rpm_limit": 60}'
Steps
-
Check the key and the model names.
curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY" -
Set the environment variables the SDK reads when it creates a client.
OPENAI_BASE_URLis the gateway address with/v1, because the SDK adds/chat/completionsand the other routes right after it.export OPENAI_BASE_URL="https://gateway.example.com/v1"export OPENAI_API_KEY="sk-...your virtual key..." -
Keep
new OpenAI()as it is, or passbaseURLandapiKeyin code. Options passed in code win over the environment. -
Use a public model name from step 1 as
model. -
Run the app once and find the request on Logs (
/ui/logs).
The OpenAI routes also answer without /v1. A base URL ending in /v1/v1 fails with 404, see the /v1 rule.
Configuration
Save as describe.mjs and run it with node describe.mjs.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: process.env.OPENAI_BASE_URL ?? "https://gateway.example.com/v1",
apiKey: process.env.OPENAI_API_KEY,
});
const completion = await client.chat.completions.create(
{
model: "gpt-6.1-sol",
messages: [{ role: "user", content: "Explain a model group in one sentence." }],
},
{ headers: { "x-spanway-tags": "app:catalog-writer" } },
);
console.log(completion.choices[0].message.content);
Gateway request headers go in the second argument as headers, or once for every call as defaultHeaders on the client. Recent SDK versions also read OPENAI_CUSTOM_HEADERS, one Name: value pair per line, so headers can be set without a code change. Gateway body fields such as cache go in the request object, with // @ts-expect-error above them in TypeScript because they are not in the SDK's types. Every request header is listed on calling the gateway.
Expected result
The script prints the answer. To read the gateway headers, use .withResponse():
const { data, response } = await client.chat.completions
.create({ model: "gpt-6.1-sol", messages: [{ role: "user", content: "Hello" }] })
.withResponse();
console.log(response.headers.get("x-spanway-call-id"), response.headers.get("x-spanway-model-group"));
A run against a test gateway printed this.
a9e96370-69e7-4b4f-b387-c02de0f684e8 gpt-6.1-sol
Log x-spanway-call-id with every failure, it is the id to search for on Logs. x-spanway-model-id names the deployment that answered, x-spanway-routing-reason and x-spanway-attempts say why and after how many provider calls, see routing decision headers, and x-spanway-response-cost with x-spanway-key-spend show the cost and the key's spend so far.
On Logs (/ui/logs), click Filters, pick Key Alias = catalog-writer and click Apply Filters to see every request from the app with its model, tokens, cost and status.
Streaming, tools, images, caching and reasoning
| Feature | How to use it through the gateway | Notes |
|---|---|---|
| Streaming | stream: true and for await (const chunk of stream). Add stream_options: { include_usage: true } for token counts. | Works for every model behind the name. |
| Tools | tools and tool_choice as for OpenAI. | Translated for other providers. |
| Images | image_url content parts with a URL or a base64 data URL. | The model behind the name must accept images. |
| Response cache | cache: { "no-cache": true } or cache: { ttl: 300 } in the request body. | Only when an admin turned on caching. |
| Provider prompt caching | Nothing to change. | Cached tokens show in usage.prompt_tokens_details.cached_tokens. See prompt caching. |
| Reasoning | reasoning_effort: "low", "medium" or "high". | Mapped to other providers' reasoning settings where they have one. |
| Responses API | client.responses.create({ model, input }). | See Responses API. |
The SDK retries connection errors, 408, 409, 429 and 5xx answers twice by default, on top of the gateway's own retries and fallbacks. Set maxRetries: 0 when the gateway's retries should be the only ones. The default timeout is 10 minutes, set with timeout in milliseconds.
Errors
Every error from the gateway is thrown as a subclass of OpenAI.APIError with status, headers and error. Its message is the status followed by the gateway's text, for example 400 /chat/completions: Invalid model name passed in model=nope-model. Call `/v1/models` to view available models for your key. When the body has no message, the message is the status followed by the raw body, such as 404 {"detail":"Not Found"}.
| Case | Error class | Text the gateway sends | Cause and fix |
|---|---|---|---|
| No key on the request | AuthenticationError (401) | Authentication Error, No api key passed in. | A proxy in between strips Authorization. Check that hop. |
| Wrong or deleted key | AuthenticationError (401) | Authentication Error, Invalid proxy server token passed. key=<hash>, not found in db. | Copy the key again, or create a new key. |
| Blocked key | AuthenticationError (401) | Authentication Error, Key is blocked. Update via `/key/unblock` if you're an admin. | Ask the admin to open the key in Virtual Keys and click Unblock Key. |
| Expired key | AuthenticationError (401) | Authentication Error - Expired Key. Key Expiry time <time> and current time <time> | Ask the admin to extend the key or issue a new one. |
| The key may not use the model | PermissionDeniedError (403) | The requested model '<model>' is not available for this API key, or the model name is invalid. | Add the model to the key, or use a name from client.models.list(). |
| The model name is unknown | BadRequestError (400) | Invalid model name passed in model=<name> | Use a public name from GET /v1/models, typed exactly. |
| A parameter the provider does not take | BadRequestError (400) | does not support parameters: <names>, for model=<model> | Remove it, or ask the admin for drop_params: true. |
| The budget is spent | UnprocessableEntityError (422) | Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max> | Wait for the reset or ask for a higher budget. With budget_exceeded_status_code: 429 it arrives as RateLimitError. |
| Over the rate limit | RateLimitError (429) | Rate limit exceeded for <scope>: <value>. Limit type: <type>. | Slow down or ask for a higher limit. err.headers.get("retry-after") says how many seconds to wait. |
Wrong path, often a doubled /v1 | NotFoundError (404) | Not Found | Use exactly one /v1 in OPENAI_BASE_URL. |
| The provider failed | InternalServerError (500 to 503) | The provider's own message, followed by the model group that failed | Retry later and ask for a fallback deployment. |
| Nothing listens at the address | APIConnectionError | None. The message is Connection error. and the cause chain names ECONNREFUSED | Check the address, the port and that the gateway runs. In Docker use host.docker.internal instead of localhost. |
| TLS certificate not trusted | APIConnectionError | None. The message is Connection error. and the cause chain names UNABLE_TO_GET_ISSUER_CERT_LOCALLY or SELF_SIGNED_CERT_IN_CHAIN | Start Node with NODE_EXTRA_CA_CERTS=/path/to/company-root.pem. |
| The answer took too long | APIConnectionTimeoutError | None. The message is Request timed out. | Raise timeout, or stream long answers. |
| No key configured | OpenAIError | None, thrown when the client is created | Set OPENAI_API_KEY or pass apiKey. |
See the client error reference for the same cases in every SDK.
Troubleshooting
- Log
err.status,err.messageanderr.headers.get("x-spanway-call-id")in your catch block. - Open Logs (
/ui/logs), search for the call id or filter by Key Alias, and open the row for the status, the error, the deployment and the provider's answer. - If the request is not on Logs, it never reached the gateway. Run with
OPENAI_LOG=debug, or setlogLevel: "debug"on the client, to print each request URL and its answer, which shows a wrong host or a doubled/v1. - For TLS errors,
NODE_EXTRA_CA_CERTSmust be set before Node starts. Setting it inside the script has no effect. - Read
x-spanway-routing-reasonandx-spanway-attemptsto see retries and fallbacks, explained on routing decision headers.
More symptoms are in troubleshooting.
Rotation and removal
Open the key in Virtual Keys, click Regenerate Key, set a Grace Period such as 24h, and deploy the new key in OPENAI_API_KEY before the grace period ends. From the API this is POST /key/{key}/regenerate with {"grace_period": "24h"}, which needs an Enterprise license. Without one, create a new key, switch the app and delete the old key.
Block Key (POST /key/block) stops the app at once and Unblock Key undoes it. Deleting the key (POST /key/delete with {"keys": ["<key>"]}) is permanent, keeps its spend history and makes every later request fail with 401. To take the app off the gateway, unset OPENAI_BASE_URL and set a provider key again.
Related
- OpenAI Python SDK for the same steps in Python.
- Connect any client for base URLs and headers on every API surface.
- Client error reference for every gateway error.
- Chat completions for every request field.
- Calling the gateway for every request and response header.