Skip to main content

TypeScript client

@spanway/client is a typed TypeScript client for the gateway's management API and its OpenAI-compatible inference routes. Its request and response types are generated from the gateway's OpenAPI document, so every field name, enum and required property matches the gateway version the package was built for. A thin set of helpers covers the surfaces a platform team automates, inference helpers call chat completions, responses, Anthropic messages, embeddings, rerank, moderations, image generation and audio, and a raw typed client reaches everything else.

The package is not on npm yet. Publishing to npm starts at launch, together with the other public package registries. Until then each release attaches the packed client to the release page as spanway-client-<version>.tgz, listed in SHA256SUMS and signed with cosign, so download it for the gateway version you run from the location in your onboarding pack, check it as described in release assets, and install the file you verified.

npm install ./spanway-client-2.0.0.tgz

After launch the same package installs with npm install @spanway/client. The package ships ESM and CommonJS builds with declarations and runs on Node 20 or newer, or on any runtime with a global fetch.

A real-world scenario​

A Node service that onboards customers needs to create a team and a budgeted key for each one. The developer uses the TypeScript client so that a wrong field name fails at compile time, and handles a refused call by reading error instead of catching an exception.

Steps​

  1. Download spanway-client-<version>.tgz from the release page, check it against SHA256SUMS and its cosign signature, and install it with npm install ./spanway-client-2.0.0.tgz.

  2. Check that the key the service will use works.

    curl http://localhost:4000/key/info -H "Authorization: Bearer $SPANWAY_API_KEY"
  3. Create the client as in Authentication, then call teams.create and keys.generate as in Examples.

  4. Run the service and open Teams and Virtual Keys in the Admin UI to see the new team and key.

Expected result​

Each call resolves with data filled and error undefined, and the team and key show in the Admin UI.

Authentication​

import { createSpanwayClient } from "@spanway/client";

const spanway = createSpanwayClient({
baseUrl: "https://gateway.example.com",
apiKey: process.env.SPANWAY_API_KEY!,
});

apiKey is a virtual key or the master key and is sent as Authorization: Bearer <key> on every request. The helpers only reach what the key is allowed to manage, so a team admin key manages its own team while the master key manages everything. Pass fetch to inject your own fetch implementation, which is also how the package's own tests record requests without touching globals.

Every call resolves to { data, error, response }. A 2xx response fills data with the decoded payload, anything else fills error. Management helpers put the gateway's error body there as it came, and inference helpers put a normalised GatewayError with status, message, type, param and code. HTTP errors are values, not exceptions.

Helpers​

HelperMethodsLicense
keysgenerate, info, list, update, delete, block, unblock, regenerateStarter
teamscreate, info, list, update, delete, block, unblock, addMember, updateMember, removeMember, addModel, removeModelStarter
userscreate, info, list, update, deleteStarter
organizationscreate, info, list, delete, addMember, updateMember, removeMemberStarter
modelscreate, info, update, patch, deleteStarter
budgetscreate, info, list, settings, update, deleteStarter
guardrailscreate, list, info, update, patch, delete, applyStarter
mcpServerscreate, list, info, update, delete, health, toolsStarter
agentscreate, list, info, update, delete, makePublic, setPublic, killSwitch, identity, discover, dailyActivityStarter, killSwitch and identity need agent_governance
customAgentscreate, list, info, update, delete, run, runs, runInfo, cancelRunEnterprise, needs custom_agents
evalsdatasets.create, datasets.import, datasets.list, datasets.get, datasets.update, datasets.delete, datasets.fromSessions, sessions.preview, runs.create, runs.list, runs.get, runs.results, runs.result, runs.cancel, runs.delete, runs.compare, runs.verdict, runs.items, runs.submitOutputs, runs.finish, runs.waitForVerdict, runs.experiment, playground, scorers, testScorer, remoteScorers.create, remoteScorers.list, remoteScorers.get, remoteScorers.update, remoteScorers.delete, remoteScorers.rotateSecret, online.rules.create, online.rules.list, online.rules.get, online.rules.update, online.rules.delete, online.scores, online.summary, redTeam.catalogue, redTeam.create, redTeam.list, redTeam.get, redTeam.results, redTeam.cancel, redTeam.delete. Also: datasets.fromLogs, datasets.versions.list, datasets.versions.get, datasets.versions.delete, logs.preview, schedules.create, schedules.list, schedules.get, schedules.update, schedules.delete, schedules.runNow, shadow.list, feedback.submit, feedback.list, feedback.delete, review.queues.create, review.queues.list, review.queues.get, review.queues.update, review.queues.delete, review.queues.fromRun, review.queues.fromLogs, review.queues.fromShadow, review.queues.items, review.queues.item, review.queues.deleteItem, review.queues.calibration, review.queues.toDataset, review.assigned, review.next, review.item, review.label, review.skipEnterprise, needs evals
cloudsignup, verify, resend, plans, subscribe, portal, import, credits.list, credits.purchase, credits.autoTopup, credits.setAutoTopup, credits.disableAutoTopup, tenant.get, tenant.update, tenant.cancel, tenant.export, tenant.credentials, tenant.addCredential, tenant.deleteCredential, tenants.list, tenants.get, tenants.changePlan, tenants.suspend, tenants.reinstateSpanway Cloud, needs cloud
billingaccounts.create, accounts.update, accounts.delete, accounts.get, accounts.list, accounts.suspend, accounts.reinstate, usage, invoices.generate, invoices.generateAll, invoices.issue, invoices.markPaid, invoices.void, invoices.get, invoices.list. The CSV export of an invoice is reached through apiEnterprise, needs billing

A helper for a licensed route resolves with a 403 error when the gateway's license does not include that feature, and the error names the feature. The package itself is the same for every gateway.

Each helper forwards to the generated path for its endpoint. Create and update helpers take the request body, lookups take the identifier, list helpers take the query parameters, and all of them are typed from the OpenAPI document. A body with a misspelled field or a string where the gateway expects a number does not compile.

Inference​

The inference helpers call the gateway's OpenAI-compatible routes with the same key and base URL as every other helper.

HelperMethodsRoute
chat.completionscreate, streamPOST /v1/chat/completions
responsescreate, streamPOST /v1/responses
embeddingscreatePOST /v1/embeddings
messagescreate, streamPOST /v1/messages
rerankcreatePOST /v1/rerank
moderationscreatePOST /v1/moderations
imagesgeneratePOST /v1/images/generations
audio.speechcreatePOST /v1/audio/speech
audio.transcriptionscreatePOST /v1/audio/transcriptions

Chat and responses parameters are typed from the gateway's OpenAPI document, so chat messages and Responses input items are checked against the gateway's own schemas. Tool definitions, tool_choice and response_format are passed through as open objects, because providers accept different shapes there. The chat parameters also include the newer OpenAI fields the document does not list yet, such as max_completion_tokens, reasoning_effort, modalities, audio, prediction and web_search_options. Embeddings parameters are defined in the package until the gateway's embeddings schema describes them, and a misspelled field fails to compile on every inference method. create never streams and stream always does, so neither accepts a stream field. The OpenAPI document does not describe stream chunks, stream events, chat usage or the embeddings response, so the package defines those types itself, following the OpenAI and Anthropic shapes the gateway returns. With encoding_format: "base64" the embedding vectors are typed as strings, with "float" or no format as number arrays, and with a format only known at runtime as either.

const completion = await spanway.chat.completions.create({
model: "claude-sonnet-5-5",
messages: [{ role: "user", content: "Summarise the release notes" }],
});
if (completion.error) throw new Error(completion.error.message);
console.log(completion.data.choices[0]?.message.content, completion.data.usage?.total_tokens);

stream resolves once the gateway accepts the request. Its data is an async iterator over the server-sent events, which stops at data: [DONE] or when the connection closes, and breaking out of the loop closes the connection.

const chat = await spanway.chat.completions.stream({
model: "claude-sonnet-5-5",
messages: [{ role: "user", content: "Write a haiku about gateways" }],
stream_options: { include_usage: true },
});
if (chat.error) throw new Error(chat.error.message);
for await (const chunk of chat.data) process.stdout.write(chunk.choices[0]?.delta.content ?? "");

const reply = await spanway.responses.stream({ model: "claude-sonnet-5-5", input: "Tell me about AI" });
if (reply.error) throw new Error(reply.error.message);
for await (const event of reply.data) {
if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
if (event.type === "response.completed") console.log(event.response.usage);
}

const vectors = await spanway.embeddings.create({ model: "text-embedding-3-large", input: ["first", "second"] });

The messages helpers take Anthropic Messages parameters, so max_tokens is required and a role is user or assistant. A messages stream yields the Anthropic event union, message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stop and ping, and narrowing on type and then on delta.type gives typed text, tool input and thinking deltas. Rerank parameters are typed from the gateway's OpenAPI document. Moderations, image generation and audio parameters are defined in the package, as are every response shape these routes return. Speech comes back as a Blob with the bytes the provider sent. A transcription is sent as multipart form data with the file under file, and returns a Transcription object for json and verbose_json or the raw text for text, srt and vtt.

import { readFile } from "node:fs/promises";

const message = await spanway.messages.stream({
model: "claude-sonnet-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Explain rate limits" }],
});
if (message.error) throw new Error(message.error.message);
for await (const event of message.data) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") process.stdout.write(event.delta.text);
}

const ranked = await spanway.rerank.create({
model: "rerank-v4.0-pro",
query: "capital of France",
documents: ["Berlin is in Germany", "Paris is the capital of France"],
});
const verdict = await spanway.moderations.create({ model: "omni-moderation-latest", input: "some user text" });
const image = await spanway.images.generate({ model: "gpt-image-2", prompt: "a lighthouse at dawn" });
const speech = await spanway.audio.speech.create({ model: "gpt-4o-mini-tts", input: "Hello", voice: "alloy" });
const transcript = await spanway.audio.transcriptions.create({
file: new Blob([await readFile("call.wav")], { type: "audio/wav" }),
filename: "call.wav",
model: "gpt-transcribe",
});

An HTTP error comes back as error, a GatewayError with status, message, type, param and code taken from the gateway's error body, so a rejected key or an exceeded budget is handled with an if. Once a stream has started, the gateway reports a failure as an error frame, an Anthropic error event on a messages stream, or, when a chunk cannot be serialized, a plain-text frame. Either way the loop throws a SpanwayStreamError whose error property holds a GatewayError, with the raw text as the message for a plain-text frame. A Responses API error event is a normal stream event and is yielded like any other. Every inference method takes { signal } as a second argument. Aborting before the response arrives rejects the call with an AbortError, and aborting during a stream rejects the loop with it.

const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000);
const story = await spanway.chat.completions.stream(
{ model: "claude-sonnet-5-5", messages: [{ role: "user", content: "Tell me a long story" }] },
{ signal: controller.signal },
);

Examples​

Create a team with a monthly budget and a key scoped to it.

const team = await spanway.teams.create({ team_alias: "platform", max_budget: 500, budget_duration: "30d" });
if (team.error) throw new Error(`team creation failed with ${team.response.status}`);

const key = await spanway.keys.generate({
key_alias: "platform-ci",
team_id: team.data.team_id,
models: ["claude-sonnet-5-5"],
duration: "30d",
});
console.log(key.data?.key);

Add a deployment and read the deployment list. models.info() reads GET /model/info, the deployments the calling key manages, so with an admin key it returns every deployment. To see the public model names a key may call, send GET /v1/models with that key.

await spanway.models.create({
model_name: "claude-sonnet-5-5",
spanway_params: { model: "anthropic/claude-sonnet-5-5", api_key: "os.environ/ANTHROPIC_API_KEY" },
model_info: { id: null, access_groups: ["platform"] },
});
const deployments = await spanway.models.info();

Start an eval run and page through the failures.

const run = await spanway.evals.runs.create({
dataset_id: "dataset-golden",
models: ["claude-sonnet-5-5", "claude-haiku-5-5"],
scorer: { type: "exact_match" },
});
const failures = await spanway.evals.runs.results(run.data!.run_id, { passed: false, page: 1 });

Compare the two models of that run item by item and list the regressions.

const comparison = await spanway.evals.runs.compare({
arms: [
{ run_id: run.data!.run_id, model: "claude-sonnet-5-5" },
{ run_id: run.data!.run_id, model: "claude-haiku-5-5" },
],
filter: "regressed",
});

Start a gated run with a CI key and wait for its verdict, which polls every 10 seconds by default and gives up after timeoutMs.

const gated = await spanway.evals.runs.create({
dataset_name: "support-golden",
models: ["claude-sonnet-5-5"],
scorer: { type: "exact_match" },
baseline_key: "support-bot",
gate: { min_pass_rate: 0.85, max_new_failures: 2 },
});
const verdict = await spanway.evals.runs.waitForVerdict(gated.data!.run_id, { timeoutMs: 20 * 60_000 });
if (verdict.conclusion === "failed") process.exit(1);

Reach an endpoint without a helper through the raw client, which carries the same auth header and the same types.

const readiness = await spanway.api.GET("/health/readiness");
const logs = await spanway.api.GET("/spend/logs", { params: { query: { request_id: "abc" } } });

The paths, components and operations types are exported for code that needs to name a gateway type, and JsonBody<"/key/generate", "post"> or Query<"/key/list", "get"> select a single body or query type.

Keeping the types current​

The types are generated from the gateway's OpenAPI document for each release, so the client version always equals the gateway version, and a client built for one release matches every route and field of that release. Upgrade the client together with the gateway. Each tarball is signed with cosign and ships with an SPDX SBOM on the release page, as described in release assets.

License​

The package ships under the Spanway Client License in its LICENSE file, the same terms as the Python client. You may use and modify it in production to call a Spanway gateway you are allowed to use, and redistribute it, changed or not, as part of software that calls a Spanway gateway, as long as the notice stays with it. Bundling it into your own app is fine. Selling it on its own or using it to build a competing gateway is not. The gateway itself is licensed separately.

For Python, see the Python client. For exploring the API interactively, see the Postman collection.

Errors​

What you getTypical causeFix
error with status 401The key is wrong, deleted or expired.Use a valid key.
error with status 403 naming a featureThe route needs a license feature the gateway lacks.Add the feature, see feature names.
error with status 422 and a detail listA field failed validation on the gateway.Fix the field named in loc.
A rejected promise with a network errorfetch could not reach the gateway.Check baseUrl and the network.
A type error at compile timeA misspelled field or a wrong type.Fix the call, the types come from the gateway's OpenAPI document.

Logs​

The client writes no log of its own. Every call it makes is an ordinary gateway request, so it shows up on Logs (/ui/logs) under the key you passed, and a call that changes something, such as keys.generate or teams.update, also writes a row to the audit log with the key's user as the actor. The gateway's own log lines for those requests are in the log reference. To see what the client sends, pass your own fetch that logs the method and URL before it calls the real one, and leave the Authorization header out of what you print.