Integration guide · Evidence checked 20 November 2026

OpenAI Node SDK with Plugsky: ESM, CJS, streaming and tools

The official openai npm package works with Plugsky once you change the base URL and the model IDs. This guide covers the ESM and CommonJS entry points, the capitalisation trap, streaming, tool calling, embeddings and typed error handling.

Short answer. Install openai, create new OpenAI({ apiKey, baseURL: "https://api.plugsky.com/v1" }), and call client.chat.completions.create({ model: "plugsky-pro", messages }). Streaming, tools and embeddings use the standard SDK methods. The two things that break migrations are the baseURL spelling and using a secret key in browser code.

What the SDK gives you

The OpenAI Node SDK is a typed client for the OpenAI HTTP API. Against Plugsky it works for chat completions and embeddings, including streaming, JSON mode where the model supports it, tool definitions and token usage. It is not a promise that every OpenAI product exists behind the same host; Responses, Assistants, audio and image generation are separate services.

The approved base URL for these examples is https://api.plugsky.com/v1. Plugsky's public docs also show https://plugsky.com/v1 in places; choose one host, put it in configuration, and confirm it matches the key and network path you were issued.

ESM and CommonJS

The package publishes a CommonJS entry point and also supports ESM imports. Pick the form that matches your project's module system; do not mix require into an ESM file without an interop layer.

Importing the OpenAI Node SDK by module system
Project typeImportNotes
ESM ("type": "module")import OpenAI from "openai";Top-level await is available in modern Node.
CommonJSconst OpenAI = require("openai");Wrap awaited calls in an async function.
TypeScriptimport OpenAI from "openai";Types ship with the package; set moduleResolution to a modern mode.
Denoimport OpenAI from "npm:openai";Documented by the package; still a server-side client.

The package metadata checked on 20 November 2026 lists Node 22 or newer in its engines field. That is a packaging fact, not a statement about every runtime you may have in production. Read the current field before an upgrade, and test on the Node version you actually deploy.

Install and create the client

npm install openai
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.PLUGSKY_API_KEY,
  baseURL: "https://api.plugsky.com/v1",
  timeout: 120_000,
  maxRetries: 2,
});

baseURL is the parameter to watch. The Python SDK spells it base_url; the Node SDK spells it baseURL. In plain JavaScript, the wrong casing is ignored and the client falls back to https://api.openai.com/v1; TypeScript flags it as an unknown property. Either way, you can spend an hour debugging a 401 from the wrong provider.

The SDK's documented defaults are a ten-minute timeout and two retries. Both are configurable. For an interactive chat route, a two-minute timeout is usually more appropriate than ten; for a long extraction job, keep the longer default.

Make a chat request

const response = await client.chat.completions.create({
  model: "plugsky-pro",
  messages: [
    { role: "system", content: "You are a concise support assistant." },
    { role: "user", content: "Summarise this ticket in three bullets." },
  ],
  temperature: 0.2,
  max_tokens: 800,
});

console.log(response.choices[0].message.content);
console.log(response.usage);

Use max_tokens for the output budget. Some OpenAI reasoning models require max_completion_tokens; Plugsky's documented examples use the standard max_tokens field, so confirm the current API reference before you rely on the newer name.

Log usage and the x-plugsky-served-model response header per request. The header tells you which engine actually served the call, which is useful when a legacy model ID maps to a newer engine than its name suggests. Call .withResponse() on the request when you need the raw headers alongside the parsed body.

Stream with an async iterator

const stream = await client.chat.completions.create({
  model: "plugsky-pro",
  messages: [{ role: "user", content: "Count to five, one word per line." }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

Read delta.content, not message.content. The delta can be missing on the first chunk, which carries the role, and on the final chunk, which carries the finish reason. The nullish coalescing operator keeps the loop from passing undefined to process.stdout.write, which would throw.

For a web handler, pipe the deltas to the response and flush them. A proxy that buffers the whole body turns a streaming API into a slow non-streaming one, even though the upstream is behaving correctly.

Call tools

const completion = await client.chat.completions.create({
  model: "plugsky-pro",
  messages: [{ role: "user", content: "Where is order A-1042?" }],
  tools: [{
    type: "function",
    function: {
      name: "get_order_status",
      description: "Look up an order by its ID.",
      parameters: {
        type: "object",
        properties: { order_id: { type: "string" } },
        required: ["order_id"],
        additionalProperties: false,
      },
    },
  }],
  tool_choice: "auto",
});

const call = completion.choices[0].message.tool_calls?.[0];
if (call) {
  const args = JSON.parse(call.function.arguments);
  console.log(call.function.name, args);
}

function.arguments is a JSON string, not an object. Parse it inside a try/catch: a model can emit malformed JSON, and an unhandled parse error will take down the request handler. Tool support depends on the selected model, so check the model's feature list before you ship the flow.

Create embeddings

const embedding = await client.embeddings.create({
  model: "plugsky-embed",
  input: ["first document", "second document"],
});

console.log(embedding.data[0].embedding.length); // 2048

plugsky-embed returns 2,048-dimension vectors and accepts up to 2,048 inputs per request. If you pass dimensions to truncate, use the same value at query time and rebuild collections that were indexed at a different size.

Handle typed errors

try {
  const response = await client.chat.completions.create({
    model: "plugsky-pro",
    messages: [{ role: "user", content: "Hello" }],
  });
  console.log(response.choices[0].message.content);
} catch (err) {
  if (err instanceof OpenAI.RateLimitError) {
    console.error("rate limited", err.headers?.get("retry-after"));
  } else if (err instanceof OpenAI.APIError) {
    console.error(err.status, err.request_id, err.error);
  } else {
    throw err;
  }
}

The SDK exports the error classes as static properties on OpenAI, so you do not need a separate import. APIError carries status, headers, request_id and the parsed error body. Plugsky's body adds error_code, retry_after and a limit object for plan-level failures.

Node SDK error classes and the appropriate response
ClassHTTPTypical causeAction
OpenAI.BadRequestError400Malformed body, context too large, tool schema rejected.Fix the request; do not retry unchanged.
OpenAI.AuthenticationError401Key missing, revoked or sent to the wrong host.Check baseURL and the key; do not retry.
OpenAI.PermissionDeniedError403Plan does not include the feature.Check the plan or account status.
OpenAI.NotFoundError404Unknown model ID.Read /v1/models and use a current ID.
OpenAI.RateLimitError429RPM, concurrency or daily cap reached.Honour Retry-After; back off with jitter.
OpenAI.InternalServerError5xxUpstream or gateway failure.Retry with a cap; log request_id.
OpenAI.APIConnectionTimeoutErrorn/aClient timed out.Retry, shorten the request or raise the timeout.

Node-specific gotchas

  • Do not ship the key to a browser. The SDK supports a dangerouslyAllowBrowser flag. Its name is the warning. Call Plugsky from a server, edge function or BFF and authenticate your own users there.
  • Abort long requests. Pass an AbortSignal in the request options so a disconnected user does not leave an inference call running. Treat the abort as a client cancellation, not a provider error.
  • Respect proxy settings. A corporate proxy or a custom dispatcher can break streaming or the model-list call. Test from the same network as the deployed process.
  • Pin the SDK. A major-version upgrade can change defaults for retries, timeouts or error shapes. Read the changelog and run your integration tests before bumping in production.
  • Do not retry a tool side effect blindly. If your function charges a card or sends an email, make the operation idempotent before you let the SDK retry the surrounding request.

Limits to design around

Plugsky publishes 39 model IDs. The main text models serve a 262,144-token context; the vision models 131,072; the embedding models 8,192. Your plan can cap input and output below the model's own ceiling: Hobby allows 64K input and 8K output, Starter 128K and 16K, Builder 256K and 32K, and Scale a 512K plan input ceiling with 32K output.

Concurrency and RPM are plan-level: 4 and 120 on Hobby, 6 and 240 on Starter, 10 and 600 on Builder, 16 and 1,200 on Scale. Builder and Scale have no monthly token cap and no per-token overage, subject to fair use. Free accounts created from 2 November 2026 get 100 requests and 50,000 tokens per day; older accounts keep 500 requests and 250,000 tokens per day until migration.

What we did not verify

  • We did not benchmark latency, throughput or answer quality. The limits above are plan limits, not performance guarantees.
  • We did not test every Node runtime or bundler. The module-system behaviour described here reflects the package metadata checked on 20 November 2026.
  • We did not verify browser or edge-runtime support. Use a server-side runtime you control.
  • We did not review a security report for your deployment. Request the current SOC 2 report under NDA and confirm its scope and period; readiness is not certification.

Frequently asked questions

Does the OpenAI Node SDK work with Plugsky?

Yes, for chat completions and embeddings. Install the openai npm package, pass baseURL as https://api.plugsky.com/v1, and use a Plugsky model ID. The rest of the Chat Completions call shape is unchanged.

What is the difference between baseURL and base_url?

The Node SDK uses baseURL with a capital URL. The Python SDK uses base_url with underscores. In plain JavaScript, passing the Python spelling is ignored, so requests go to api.openai.com instead of Plugsky; TypeScript flags it as an unknown property.

Can I use the SDK in a browser?

Do not. The client needs your secret API key, and the SDK exposes it to anyone who loads the page. Call Plugsky from a server or edge function and keep the browser on your own authenticated endpoint.

Does streaming work in both ESM and CommonJS?

Yes. The stream is an async iterable in both module systems. Use for await over the returned stream and read chunk.choices[0].delta.content, which may be undefined on the first and last chunks.

How do I handle errors in Node?

Catch OpenAI.APIError and branch on the subclasses: RateLimitError, AuthenticationError, BadRequestError, NotFoundError and InternalServerError. Read err.status, err.request_id and err.error for the Plugsky error_code and retry guidance.

Which Node version does the SDK require?

The package metadata checked on 20 November 2026 lists Node 22 or newer. The SDK still publishes CommonJS and supports require, but check the current engines field before you upgrade a production runtime.

Related pages

Ship the Node client without the migration risk

Start free, test your tool calls and streaming path, then choose the plan that matches your concurrency.

Start Free → See pricing

Sources

SDK packaging and API shape were checked against the official repository on 20 November 2026. Plugsky limits were checked against its docs on the same date.

Official pages used for this integration guide
SourcePage checkedChecked
OpenAIopenai-node repository and README20 Nov 2026
OpenAINode SDK API reference20 Nov 2026
OpenAIChat Completions API reference20 Nov 2026
PlugskyQuickstart and error codes20 Nov 2026

Last checked 20 November 2026. Plan terms live at /pricing; the live model list is at /models.