Anthropic TypeScript SDK
The Anthropic TypeScript SDK is the @anthropic-ai/sdk npm package for Node.js, Deno and Bun apps that call Claude with the Messages API. Pointed at the Spanway gateway, the same code keeps the Messages format while the gateway checks a virtual key, applies the key's budget and rate limit, records the cost and routes the request to the deployment behind the public model name, which can be Claude on Anthropic, Amazon Bedrock, Vertex AI or Azure, or a model from another provider.
A real-world scenario
A customer success team runs a TypeScript service that classifies incoming tickets and drafts a first answer. The classification is cheap and runs on every ticket, the draft runs only on some. The admin puts both models on one key named ticket-triage, claude-haiku-5-5 for the classification and claude-sonnet-5-5 for the drafts, with a token per minute limit so a flood of tickets cannot run up the bill. The team sets ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY, and Usage now shows the cost of each model per day for this one service.
Prerequisites
- A running gateway and its address, written here as
https://gateway.example.com. - A model registered on the gateway under a public name, for example
claude-sonnet-5-5. - Node.js 20 or later and the SDK, installed with
npm install @anthropic-ai/sdk. The gateway does not check theanthropic-versionheader the SDK sends, so SDK upgrades need no gateway change.
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
ticket-triageand leave Key Type on AI APIs. - In Models, pick every public name the app calls, here
claude-sonnet-5-5and the fast tierclaude-haiku-5-5. - Open Optional Settings, set Max Budget (USD) with Reset Budget, for example 100 USD monthly, and Tokens per minute Limit (TPM), for example 300000. 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": "ticket-triage", "key_type": "llm_api", "models": ["claude-sonnet-5-5", "claude-haiku-5-5"], "max_budget": 100, "budget_duration": "30d", "tpm_limit": 300000}'
Steps
-
Check the key and the model names.
curl https://gateway.example.com/v1/models -H "x-api-key: $SPANWAY_API_KEY" -H "anthropic-version: 2023-06-01" -
Set the environment variables the SDK reads.
ANTHROPIC_BASE_URLis the gateway address without/v1, because the SDK adds/v1/messagesitself.export ANTHROPIC_BASE_URL="https://gateway.example.com"export ANTHROPIC_API_KEY="sk-...your virtual key..." -
Keep
new Anthropic()as it is, or passbaseURLandapiKeyin code. -
Use a public model name from step 1 as
model. -
Run the app once and find the request on Logs (
/ui/logs).
To send the key as Authorization: Bearer, set ANTHROPIC_AUTH_TOKEN or pass authToken instead of the API key. The gateway accepts both. A base URL that ends in /v1 makes the SDK call /v1/v1/messages, which fails with 404, see the /v1 rule.
Configuration
Save as triage.mjs and run it with node triage.mjs.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
baseURL: process.env.ANTHROPIC_BASE_URL ?? "https://gateway.example.com",
apiKey: process.env.ANTHROPIC_API_KEY,
defaultHeaders: { "x-spanway-tags": "app:ticket-triage" },
});
const message = await client.messages.create({
model: "claude-haiku-5-5",
max_tokens: 50,
messages: [{ role: "user", content: "Classify this ticket as billing, bug or question: I was charged twice." }],
});
for (const block of message.content) {
if (block.type === "text") console.log(block.text);
}
defaultHeaders sends gateway headers on every request, and the second argument of a call, { headers: {...} }, does it for one call. Recent SDK versions also read ANTHROPIC_CUSTOM_HEADERS, one Name: value pair per line, so headers can be set without a code change. 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.messages
.create({ model: "claude-sonnet-5-5", max_tokens: 50, 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.
6bfbed21-169e-4ea7-a030-91969a6a220c claude-sonnet-5-5
x-spanway-call-id 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 is the call's cost.
On Logs (/ui/logs), click Filters, pick Key Alias = ticket-triage and click Apply Filters.
Streaming, tools, images, caching and reasoning
| Feature | How to use it through the gateway | Notes |
|---|---|---|
| Streaming | client.messages.stream({...}) with .on("text", ...) and await stream.finalMessage(), or stream: true for raw events. | Server-sent events in the Anthropic format, whichever provider answers. |
| Tools | tools with input_schema, and tool_choice. | Translated when another provider answers. |
| Images and PDFs | image and document blocks with base64 data. | The model behind the name must accept them. |
| Prompt caching | cache_control: { type: "ephemeral" } on the blocks to cache. | Reported in usage.cache_read_input_tokens and usage.cache_creation_input_tokens. On Vertex AI and Azure deployments the gateway removes the scope field, which those providers reject. |
| Extended thinking | thinking as in the Anthropic API. | Thinking blocks come back from Claude deployments. For other providers the thinking budget is mapped to the model's reasoning effort. |
| Beta features | client.beta.messages.create({ ..., betas: [...] }). | Passed on to Claude on Anthropic. Bedrock, Vertex AI and Azure deployments get only the beta values that provider supports. |
| Token counting | client.messages.countTokens({ model, messages }). | Served at /v1/messages/count_tokens, see count tokens. |
| Message Batches and Files | client.messages.batches and client.beta.files. | Use a second client with baseURL: "https://gateway.example.com/anthropic", the Anthropic pass-through. |
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.
Errors
Every error from the gateway is thrown as a subclass of Anthropic.APIError with status, headers and error. Its message is the status followed by the response body as JSON, for example 400 {"type":"error","error":{"type":"invalid_request_error","message":"anthropic_messages: Invalid model name passed in model=nope-model. Call `/v1/models` to view available models for your key."}}. Errors from the key check, such as a missing key or a spent budget, come back in the same Anthropic shape as errors from the request itself, and the class always follows the HTTP status.
| 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 the key header. 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, the fast tier model included. |
| The model name is unknown | BadRequestError (400) | Invalid model name passed in model=<name> | Use a name from client.models.list(), typed exactly. |
| 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. |
| Over the key or team 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 long to wait. |
| Every deployment is cooling down | RateLimitError (429) | No deployments available for selected model | The providers behind the name failed recently. Ask the admin for a fallback. |
Wrong path, often a doubled /v1 | NotFoundError (404) | Not Found | Remove /v1 from ANTHROPIC_BASE_URL. The message reads 404 {"detail":"Not Found"}. |
| 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. | Check the address, port and that the gateway runs. In Docker use host.docker.internal. |
| TLS certificate not trusted | APIConnectionError | None. 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 | Error | None. The message starts with Could not resolve authentication method. | Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN. |
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
ANTHROPIC_LOG=debug, or setlogLevel: "debug"on the client, to print each request URL and answer. - For TLS errors,
NODE_EXTRA_CA_CERTSmust be set before Node starts. - Read
x-spanway-routing-reasonandx-spanway-attemptsfor 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 ANTHROPIC_API_KEY before it 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. To take the app off the gateway, unset ANTHROPIC_BASE_URL and set an Anthropic key again.
Related
- Anthropic Python SDK for the same steps in Python.
- Anthropic Messages API for every request field the gateway accepts.
- Connect any client for base URLs and headers on every API surface.
- Client error reference for every gateway error.