EN ▾
Get API key

LLM API in Node.js: Setup, Streaming and Tools

To use this API from Node.js, install the official openai package and point it at a different base URL. Your existing chat code keeps working with the model ID uncensored.

Updated

Green hexagon node linked to chat bubbles and a server, illustrating a Node.js LLM API integration

Key points

  • npm install openai, then set baseURL to https://api.gemininsfw.cc/v1.
  • Streaming uses for await over the response; usage comes at the end.
  • Tool calls come back on the message and results go in as role tool.
  • On HTTP 429, read the error code and the Retry-After header before retrying.

Quick setup for an llm api node project

This is the fast path for an llm api node integration. You need Node 18 or newer, a project with ES modules, and an API key from the key page.

mkdir llm-demo && cd llm-demo
npm init -y
npm pkg set type=module
npm install openai
export API_KEY="your-key-here"

Create index.js:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.gemininsfw.cc/v1",
  apiKey: process.env.API_KEY,
});

const resp = await client.chat.completions.create({
  model: "uncensored",
  messages: [
    { role: "system", content: "You are a concise assistant." },
    { role: "user", content: "Give me three names for a fantasy tavern." },
  ],
  temperature: 0.8,
});

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

Run it with node index.js. The package sends the key as an Authorization: Bearer header, so you do not set it by hand.

No SDK: plain fetch

If you prefer zero dependencies, Node 18 has fetch built in. The API has two methods, POST /v1/chat/completions and GET /v1/models, so a thin wrapper is easy to write.

async function chat(messages) {
  const res = await fetch("https://api.gemininsfw.cc/v1/chat/completions", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model: "uncensored", messages }),
  });
  if (res.ok === false) {
    const err = await res.text();
    throw new Error(`HTTP ${res.status}: ${err}`);
  }
  return res.json();
}

const data = await chat([{ role: "user", content: "Hello" }]);
console.log(data.choices[0].message.content);

The SDK is the better choice once you need streaming helpers, typed responses and built-in retries. The raw version is fine for a small script or a serverless function where bundle size matters.

Streaming in Node

Set stream: true and loop over the result with for await. Tokens print as they arrive, and usage is reported at the end of the stream.

const stream = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Tell a two-paragraph story about a lighthouse." }],
  stream: true,
});

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) process.stdout.write(delta);
  if (chunk.usage) console.log("\n", chunk.usage);
}

To forward the stream to a browser, an Express handler can set Content-Type: text/event-stream and write each delta as an SSE data: line. Keep one rule in mind: a streamed request holds its concurrency slot until the stream ends. If the browser disconnects, stop reading the upstream stream so the slot is freed. With the SDK, call stream.controller.abort().

Tool calling and JSON mode

Tools

Pass tools and optionally tool_choice. When the model wants a function, the reply has tool_calls. You run the function and return the output as a role: "tool" message.

const tools = [{
  type: "function",
  function: {
    name: "roll_dice",
    description: "Roll an n-sided die",
    parameters: {
      type: "object",
      properties: { sides: { type: "integer" } },
      required: ["sides"],
    },
  },
}];

const messages = [{ role: "user", content: "Roll a d20 for me." }];
const first = await client.chat.completions.create({
  model: "uncensored", messages, tools, tool_choice: "auto",
});
const msg = first.choices[0].message;

if (msg.tool_calls?.length) {
  const call = msg.tool_calls[0];
  const { sides } = JSON.parse(call.function.arguments);
  const result = 1 + Math.floor(Math.random() * sides);
  messages.push(msg, {
    role: "tool",
    tool_call_id: call.id,
    content: JSON.stringify({ result }),
  });
  const final = await client.chat.completions.create({
    model: "uncensored", messages, tools,
  });
  console.log(final.choices[0].message.content);
}

JSON mode

Add response_format: { type: "json_object" } and ask for JSON in the prompt. Wrap JSON.parse in try/catch in case the output was cut short.

Project layout for a small chat server

For a real app, keep the client in one module and import it where needed. That way the base URL, the key and the retry settings live in a single place.

// llm.js
import OpenAI from "openai";

export const llm = new OpenAI({
  baseURL: "https://api.gemininsfw.cc/v1",
  apiKey: process.env.API_KEY,
  maxRetries: 2,
});

export async function complete(messages, opts = {}) {
  const r = await llm.chat.completions.create({
    model: "uncensored",
    messages,
    ...opts,
  });
  return r.choices[0].message.content;
}

Then your route handlers call complete() and never touch the key. Store the conversation history on the server, keyed by session, and trim old turns when the history grows. Because the API is stateless, each request must carry every message you want the model to see.

Errors, retries and limits

The SDK throws OpenAI.APIError subclasses with a status field. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. Past a limit you get HTTP 429 with the code rate_limited or concurrency. During short overload the API sends 429 with Retry-After: 5.

const client = new OpenAI({
  baseURL: "https://api.gemininsfw.cc/v1",
  apiKey: process.env.API_KEY,
  maxRetries: 3,
  timeout: 120_000,
});

async function safeAsk(prompt) {
  try {
    const r = await client.chat.completions.create({
      model: "uncensored",
      messages: [{ role: "user", content: prompt }],
    });
    return r.choices[0].message.content;
  } catch (e) {
    if (e.status === 429) {
      console.error("limited, retry-after:", e.headers?.["retry-after"]);
    }
    throw e;
  }
}

For batches, do not fire everything with Promise.all. Use a small queue with a fixed number of workers, for example 6, so you never exceed the 8 concurrent slots of a full key. Request bodies are capped at 8 MB, and the context window is 100,000 tokens for prompt and answer together.

Cost and next steps

Prices are $0.15 per 1M input tokens and $0.50 per 1M output tokens. A chatbot turn with 3,000 prompt tokens and 600 reply tokens costs 3,000 x $0.15 / 1M = $0.00045 plus 600 x $0.50 / 1M = $0.0003, which is $0.00075. One thousand such turns come to $0.75. Failed or refused requests are not charged, and the response header X-Balance-USD tells you what is left.

New users can claim $0.50 of trial credit on the key page, and the pricing page lists top-ups from $20 to $500. For the request format in more detail, see the docs. This service handles text only, so image, audio and embedding calls will not work.

Questions and answers

Does it work with TypeScript?

Yes. The openai package ships its own types, and the only changes are baseURL and the model name uncensored.

Can I use it from a serverless function?

Yes. It is a standard HTTPS API, so fetch works. Keep the key in the platform's secret store and watch the concurrency limit of your key.

Which Node version do I need?

Node 18 or newer is the safe choice, because it includes fetch and works with current versions of the openai package.

Is there a Node-specific package for this service?

No. Use the official openai package or plain fetch against the OpenAI-compatible endpoints.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API keyRead the docs