SDK rehberleri
Node.js
Resmi openai npm paketini baseURL ve apiKey ile api14'e yönlendirin; Node.js'te sohbet, streaming, araçlar, Zod ile structured output ve hata yönetimi.
api14 ile resmi openai npm paketini kullanın. Başka hiçbir şey değişmez: yalnızca baseURL ve apiKey api14'ü gösterir ve her model kimliği model olarak çalışır.
Kurulum
npm install openai
Anahtarınızı bir ortam değişkeninde saklayın:
export API14_API_KEY="sk-api14-..."
Yapılandırma
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
});
Seçenek verilmediğinde SDK OPENAI_BASE_URL ve OPENAI_API_KEY değerlerini okur. Bu iki değişkeni ayarlamak, mevcut bir uygulamayı kod değişikliği olmadan api14'e geçirir:
export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
const client = new OpenAI(); // picks up both variables
Sohbet
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 ?? "");
}
Olay biçimi için bkz. Streaming.
Tool calling
tools gönderin, modelin istediği çağrıları çalıştırın, sonuçları ekleyin ve model metinle yanıt verene kadar tekrar çağırın:
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);
Bkz. Tool calling.
Structured output
parse yardımcısı bir Zod şemasını json_schema yanıt formatına çevirir ve yanıtı ayrıştırır (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" }
Bkz. Structured outputs.
Görsel girdisi
content alanını parça dizisi olarak geçin. Herkese açık bir URL veya base64 data URL kullanın:
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}` } },
],
}],
});
PDF, ses ve video için bkz. Görsel ve dosyalar.
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));
SDK metodu olmayan uç noktalar
Video işleri ve rerank, OpenAI SDK yüzeyinin parçası değildir. İstemcinin genel post / get yardımcılarını kullanın; base URL'i, anahtarı ve yeniden denemeleri yeniden kullanırlar:
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);
Hatalar
Hatalar OpenAI yapısında gelir ve OpenAI.APIError olarak fırlatılır. status ve code değerlerine göre dallanın:
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;
}
}
Tüm kodlar için bkz. Hatalar.
Zaman aşımları ve yeniden denemeler
SDK bağlantı hatalarını, 408, 409, 429 ve 5xx yanıtlarını varsayılan olarak iki kez, Retry-After değerine uyan üstel geri çekilmeyle yeniden dener. Varsayılan zaman aşımı deneme başına 10 dakikadır. İkisini de istemcide ayarlayın veya istek başına geçersiz kılın:
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 });
Yeniden deneme daily_limit_reached veya insufficient_balance hatalarını düzeltemez. Uzun toplu işlerde bu kodlarda yeniden denemek yerine durun. Bkz. Hız limitleri.
Tüm yetenekler
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);