We use cookies. Cookies and browser storage keep you signed in and remember your preferences. With your permission we also measure how the site is used. You can any time. See our cookie policy.

Node.js

SDK guides

Node.js

Use api14 from Node.js with the official openai npm package, with setup, chat, streaming, images and error handling examples you can copy.

Use the official openai npm package with api14. Nothing else changes: only baseURL and apiKey point at api14, and every model id works as model.

Install

npm install openai

Store your key in an environment variable:

export API14_API_KEY="sk-api14-..."

Configure

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api14.com/api/v1",
  apiKey: process.env.API14_API_KEY,
});

With no options, the SDK reads OPENAI_BASE_URL and OPENAI_API_KEY. Setting those two variables switches an existing app to api14 without code changes:

export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
const client = new OpenAI(); // picks up both variables

Chat

const result = await client.chat.completions.create({
  model: "openai/gpt-5-mini",
  messages: [{ role: "user", content: "Explain vector databases in two sentences." }],
});

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

Streaming

const stream = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-4.5",
  messages: [{ role: "user", content: "Write a haiku about APIs." }],
  stream: true,
});

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

See Streaming for the event format.

Tool calling

Send tools, run the calls the model asks for, append the results and call again until it answers with text:

const tools = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "Current weather for a city",
    parameters: {
      type: "object",
      properties: { city: { type: "string" } },
      required: ["city"],
    },
  },
}];

const messages = [{ role: "user", content: "What's the weather in Istanbul?" }];
let res = await client.chat.completions.create({ model: "openai/gpt-5-mini", messages, tools });

while (res.choices[0].finish_reason === "tool_calls") {
  const msg = res.choices[0].message;
  messages.push(msg);
  for (const call of msg.tool_calls) {
    const args = JSON.parse(call.function.arguments);
    const result = await getWeather(args.city); // your function
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
  }
  res = await client.chat.completions.create({ model: "openai/gpt-5-mini", messages, tools });
}

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

See Tool calling.

Structured output

The parse helper turns a Zod schema into a json_schema response format and parses the reply (npm install zod):

import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";

const Person = z.object({ name: z.string(), born: z.number().int(), city: z.string() });

const res = await client.chat.completions.parse({
  model: "openai/gpt-5-mini",
  messages: [{ role: "user", content: "Extract: Ada Lovelace, born 1815 in London." }],
  response_format: zodResponseFormat(Person, "person"),
});

console.log(res.choices[0].message.parsed); // { name: "Ada Lovelace", born: 1815, city: "London" }

See Structured outputs.

Image input

Pass content as an array of parts. Use a public URL or a base64 data URL:

import { readFileSync } from "node:fs";

const image = readFileSync("photo.png").toString("base64");

const res = await client.chat.completions.create({
  model: "google/gemini-2.5-flash",
  messages: [{
    role: "user",
    content: [
      { type: "text", text: "What is in this picture?" },
      { type: "image_url", image_url: { url: `data:image/png;base64,${image}` } },
    ],
  }],
});

See Vision & files for PDFs, audio and video.

Embeddings

const result = await client.embeddings.create({
  model: "openai/text-embedding-3-small",
  input: ["The quick brown fox", "Lorem ipsum"],
});

console.log(result.data.map((d) => d.embedding.length));

Endpoints without an SDK method

Video jobs and rerank are not part of the OpenAI SDK surface. Use the client's generic post / get helpers, they reuse the base URL, key and retries:

const ranked = await client.post("/rerank", {
  body: {
    model: "cohere/rerank-v3.5",
    query: "What is the capital of France?",
    documents: ["Paris is the capital of France.", "Berlin is in Germany."],
    top_n: 1,
  },
});
console.log(ranked.results);

Errors

Errors arrive in the OpenAI shape and are thrown as OpenAI.APIError. Branch on status and code:

try {
  await client.chat.completions.create({ model: "openai/gpt-5-mini", messages: [{ role: "user", content: "Hi" }] });
} catch (err) {
  if (err instanceof OpenAI.APIError) {
    if (err.status === 402) console.error("Balance too low, add funds:", err.code); // insufficient_balance
    else if (err.status === 429) console.error("Retry after", err.headers?.["retry-after"], "s:", err.code); // rate_limited
    else throw err;
  }
}

See Errors for every code.

Timeouts and retries

The SDK retries connection errors, 408, 409, 429 and 5xx responses twice by default, with exponential backoff that honours Retry-After. The default timeout is 10 minutes per attempt. Set both on the client, or override them per request:

const client = new OpenAI({
  baseURL: "https://api14.com/api/v1",
  apiKey: process.env.API14_API_KEY,
  timeout: 60_000, // ms per attempt
  maxRetries: 4,
});

await client.chat.completions.create(params, { timeout: 300_000, maxRetries: 0 });

A retry cannot fix daily_limit_reached or insufficient_balance. For long batch jobs, stop on those codes instead of retrying. See Rate limits.

All capabilities

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api14.com/api/v1",
  apiKey: process.env.API14_API_KEY,
});

const result = await client.chat.completions.create({
  "model": "openai/gpt-5-mini",
  "messages": [
    {
      "role": "user",
      "content": "Explain vector databases in two sentences."
    }
  ]
});
console.log(result.choices[0].message.content);