Kami menggunakan cookie. Cookie dan penyimpanan browser menjaga Anda tetap masuk dan mengingat preferensi Anda. Dengan izin Anda, kami juga mengukur cara situs digunakan. Anda dapat kapan saja. Lihat kebijakan cookie kami.

Node.js

Panduan SDK

Node.js

Pakai paket npm openai resmi dengan api14 hanya dengan mengubah baseURL dan apiKey, termasuk streaming, tool calling, dan structured output.

Gunakan paket npm resmi openai dengan api14. Tidak ada hal lain yang berubah: hanya baseURL dan apiKey yang diarahkan ke api14, dan setiap ID model berfungsi sebagai model.

Instalasi

npm install openai

Simpan key Anda di environment variable:

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

Konfigurasi

import OpenAI from "openai";

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

Tanpa opsi, SDK membaca OPENAI_BASE_URL dan OPENAI_API_KEY. Mengatur kedua variabel itu memindahkan aplikasi yang sudah ada ke api14 tanpa mengubah kode:

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

Lihat Streaming untuk format event.

Tool calling

Kirim tools, jalankan panggilan yang diminta model, tambahkan hasilnya, dan panggil lagi sampai model menjawab dengan teks:

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

Lihat Tool calling.

Structured output

Helper parse mengubah skema Zod menjadi response format json_schema dan mem-parse balasannya (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" }

Lihat Structured outputs.

Input gambar

Kirim content sebagai array part. Gunakan URL publik atau data URL 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}` } },
    ],
  }],
});

Lihat Vision dan file untuk PDF, audio, dan 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));

Endpoint tanpa method SDK

Job video dan rerank bukan bagian dari permukaan OpenAI SDK. Gunakan helper generik post / get milik klien, yang memakai ulang base URL, key, dan retry:

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

Error

Error tiba dalam format OpenAI dan dilempar sebagai OpenAI.APIError. Cabangkan berdasarkan status dan 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;
  }
}

Lihat Error untuk setiap kode.

Timeout dan retry

SDK mengulang error koneksi, respons 408, 409, 429, dan 5xx sebanyak dua kali secara default, dengan exponential backoff yang menghormati Retry-After. Timeout default adalah 10 menit per percobaan. Atur keduanya pada klien, atau timpa 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 });

Retry tidak dapat memperbaiki daily_limit_reached atau insufficient_balance. Untuk job batch panjang, berhenti pada kode tersebut alih-alih mengulang. Lihat Batas laju.

Semua kemampuan

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