Usamos cookies. Cookies e o armazenamento do navegador mantêm você conectado e lembram suas preferências. Com sua permissão, também medimos como o site é usado. Você pode a qualquer momento. Veja nossa política de cookies.

Node.js

Guias de SDK

Node.js

Use o pacote npm oficial openai com a api14: configure baseURL e apiKey, faça chat, streaming, tool calling, saída estruturada com Zod e trate erros.

Use o pacote npm oficial openai com a api14. Nada mais muda: apenas baseURL e apiKey apontam para a api14, e qualquer id de modelo funciona como model.

Instalação

npm install openai

Guarde sua chave em uma variável de ambiente:

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

Configuração

import OpenAI from "openai";

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

Sem opções, o SDK lê OPENAI_BASE_URL e OPENAI_API_KEY. Definir essas duas variáveis muda um app existente para a api14 sem alterar o código:

export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
const client = new OpenAI(); // usa as duas variáveis

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 ?? "");
}

Veja Streaming para o formato dos eventos.

Tool calling

Envie tools, execute as chamadas que o modelo pedir, anexe os resultados e chame de novo até que ele responda com texto:

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); // sua função
    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);

Veja Tool calling.

Saída estruturada

O helper parse transforma um schema Zod em um formato de resposta json_schema e faz o parse da resposta (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" }

Veja Saídas estruturadas.

Entrada de imagem

Passe content como um array de partes. Use uma URL pública ou uma data URL em base64:

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}` } },
    ],
  }],
});

Veja Visão e arquivos para PDFs, áudio e vídeo.

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 sem método no SDK

Jobs de vídeo e rerank não fazem parte da superfície do SDK da OpenAI. Use os helpers genéricos post / get do cliente, que reaproveitam a URL base, a chave e as novas tentativas:

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);

Erros

Os erros chegam no formato da OpenAI e são lançados como OpenAI.APIError. Trate por status e 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;
  }
}

Veja Erros para todos os códigos.

Timeouts e novas tentativas

Por padrão, o SDK repete erros de conexão e respostas 408, 409, 429 e 5xx duas vezes, com backoff exponencial que respeita Retry-After. O timeout padrão é de 10 minutos por tentativa. Defina ambos no cliente ou sobrescreva por requisição:

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

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

Uma nova tentativa não resolve daily_limit_reached nem insufficient_balance. Em jobs em lote longos, pare nesses códigos em vez de repetir. Veja Limites de taxa.

Todos os recursos

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);