Skip to content

Anthropic SDK for TypeScript

Your TypeScript keeps calling client.messages.create(...). Change two settings and every call is governed: it's checked against your policies, charged to the right team and recorded in Request logs. And it isn't limited to Claude: the gateway translates both ways, so the same Messages code can call GPT or Gemini models and read the answer in the Anthropic shape.

What it is

The official @anthropic-ai/sdk package on npm, for Node.js, Deno, Bun and edge runtimes. It speaks the Anthropic Messages format, which the gateway accepts at /v1/messages.

The two settings

Setting Environment variable Constructor option Value
Base address ANTHROPIC_BASE_URL baseURL https://<your-gateway> (no /v1: the SDK adds /v1/messages)
Key ANTHROPIC_API_KEY apiKey Your Vidai key (starts vk_), never a provider's key

The gateway's address, and the base URL for each kind of SDK, are under Connect your app on the Keys page and in System › Settings › Gateway. You get the key from Keys › Issue a key; its secret is shown once.

export ANTHROPIC_BASE_URL="https://<your-gateway>"
export ANTHROPIC_API_KEY="vk_…"

Versions before 1.0 send the key in the x-api-key header; 1.0 and later send it as Authorization: Bearer. The gateway accepts both. ANTHROPIC_AUTH_TOKEN (or authToken) works too; set only one of the two.

A minimal call

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic(); // reads ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY
// or: new Anthropic({ baseURL: 'https://<your-gateway>', apiKey: 'vk_…' })

const message = await client.messages.create({
  model: 'claude-sonnet-4.5',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Say hello in Dutch.' }],
});
console.log(message.content);

The same code calls other providers' models: put a name such as gpt-4.1 or gemini-3.5-flash in model. The gateway translates the request for that provider and the answer back into the Anthropic shape, streams and tool use included.

Streaming

const stream = client.messages.stream({
  model: 'claude-sonnet-4.5',
  max_tokens: 256,
  messages: [{ role: 'user', content: 'Count to five.' }],
});
stream.on('text', (text) => process.stdout.write(text));
await stream.finalMessage();

stream: true on messages.create works as well. A stream from a GPT or Gemini model arrives as the full Anthropic event sequence (message_start, content_block_delta, message_stop and the rest), so the SDK's helpers work unchanged.

Tool calls

tools and tool_choice work as documented by Anthropic, on every provider: the model's calls come back as tool_use blocks, and you send results as tool_result blocks.

const message = await client.messages.create({
  model: 'gpt-4.1',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Weather in Utrecht?' }],
  tools: [{
    name: 'get_weather',
    description: 'Weather for a city',
    input_schema: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] },
  }],
});
console.log(message.content.filter((b) => b.type === 'tool_use'));

Anthropic's own server tools behave differently on another provider's model: web search is mapped to the provider's search where it has one, computer use is dropped, and bash or text_editor tools get a 400. On a Claude model they all work as usual.

Reading what the gateway did

End the call with .withResponse() to get the parsed message and the raw response, whose headers the gateway fills in:

const { data: message, response } = await client.messages
  .create({ model: 'claude-sonnet-4.5', max_tokens: 64, messages: [{ role: 'user', content: 'Hi' }] })
  .withResponse();

console.log(response.headers.get('x-vidai-request-id')); // quote this; paste it into Request logs › Request reference
console.log(response.headers.get('x-vidai-model'));      // the model that answered
console.log(response.headers.get('x-vidai-adapted'));    // what translation changed, if anything

.asResponse() returns the raw response alone, as soon as the headers arrive, without reading the body.

Other headers you may see: x-vidai-requested-model (when a different model answered), x-vidai-routing-rule, x-vidai-provider-key (the provider key's label, never its secret), x-vidai-fallback and x-vidai-fallback-from, x-vidai-fallback-attempts, x-vidai-translation-profile and x-vidai-pseudonymised. Cost is never in the answer: find the call in Request logs.

Errors

The gateway writes its errors in the Anthropic format ({"type": "error", "error": {...}}), so the SDK throws its usual error classes. Match on the x-vidai-error-code header rather than the message: codes are stable.

Status Error class Common gateway codes
400 BadRequestError bad_request, provider_override_not_allowed, an endpoint or tool this provider doesn't serve
401 AuthenticationError missing_api_key, invalid_api_key, conflicting_auth_headers
403 PermissionDeniedError api_key_disabled, model_not_allowed, denied_by_routing_rule, content_guardrail_blocked
404 NotFoundError model_not_found, endpoint_not_found
413 ContentTooLargeError payload_too_large
429 RateLimitError rate_limit_exceeded, token_limit_exceeded, concurrency_limit_exceeded
5xx InternalServerError ai_traffic_suspended, fallback_exhausted, upstream_timeout, upstream_unreachable
try {
  await client.messages.create({ model: 'claude-sonnet-4.5', max_tokens: 16, messages: [{ role: 'user', content: 'Hi' }] });
} catch (err) {
  if (err instanceof Anthropic.APIError) {
    console.log(err.status, err.headers?.get('x-vidai-error-code'));
    console.log(err.headers?.get('x-vidai-request-id'));
  } else {
    throw err;
  }
}

A key that's switched off carries a short reason beside api_key_disabled in the error body (for example agent_suspended); treat the list of reasons as open-ended.

Model names

Send the names your organisation has approved, as listed under Models in the Control room; they needn't be Claude models. client.models.retrieve('claude-sonnet-4.5') answers only for a model your key may call (otherwise a 404 model_not_found). An alias set by an admin works like any other name; x-vidai-model says which model really answered.

What goes through the gateway

Feature Through the gateway
Messages, streaming, tools, vision, PDFs, extended thinking Yes, to Anthropic, Bedrock (Claude), Vertex AI, OpenAI, Azure OpenAI and Gemini models
Prompt caching (cache_control) Yes on Claude models. On other providers the markers are removed; cache hits are still reported in cache_read_input_tokens
Token counting (messages.countTokens) Yes; for a model of another provider the gateway counts, and x-vidai-token-count says how
Files API Yes, to Anthropic only
Message batches No

Check it works in a minute

node --input-type=module -e "import Anthropic from '@anthropic-ai/sdk'; const m = await new Anthropic().messages.create({model:'claude-sonnet-4.5', max_tokens:5, messages:[{role:'user',content:'ping'}]}); console.log(m.content)"

A short answer means the address and key are right. The call shows in Request logs within seconds.

Good to know

  • The SDK retries twice by default (connection errors, 408, 409, 429 and 5xx). A fallback chain may already have tried another model before you see an error; set maxRetries: 0 if you don't want both, or keep a small number for network errors.
  • The gateway's own 429 has no Retry-After header; back off on your side. A provider's own rate-limit headers pass through.
  • On a GPT or Gemini model, thinking is mapped to the provider's reasoning setting; thinking blocks come back without a signature, so multi-turn flows that rely on signatures need a Claude model.
  • On another provider's model, anthropic-beta headers are removed, and an image given by URL may fail on Gemini: send images as base64 for the most predictable result.
  • The id to quote to your admin is x-vidai-request-id, not the SDK's own _request_id.
  • In a browser the SDK refuses to run unless you set dangerouslyAllowBrowser: true. Keep Vidai keys on a server, as you would a provider's key.