SDK-Leitfäden
Node.js
Nutzen Sie das offizielle npm-Paket openai mit api14: baseURL und apiKey setzen, Chat, Streaming, Tool Calling, Zod-Schemas, Embeddings und Fehler.
Nutzen Sie das offizielle npm-Paket openai mit api14. Sonst ändert sich nichts: Nur baseURL und apiKey zeigen auf api14, und jede Modell-ID funktioniert als model.
Installation
npm install openai
Speichern Sie Ihren Schlüssel in einer Umgebungsvariablen:
export API14_API_KEY="sk-api14-..."
Konfiguration
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
});
Ohne Optionen liest das SDK OPENAI_BASE_URL und OPENAI_API_KEY. Mit diesen beiden Variablen stellen Sie eine bestehende App ohne Codeänderung auf api14 um:
export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
const client = new OpenAI(); // übernimmt beide Variablen
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 ?? "");
}
Das Eventformat finden Sie unter Streaming.
Tool Calling
Senden Sie tools, führen Sie die vom Modell angeforderten Aufrufe aus, hängen Sie die Ergebnisse an und rufen Sie erneut auf, bis es mit Text antwortet:
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); // Ihre Funktion
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);
Siehe Tool Calling.
Strukturierte Ausgabe
Der Helfer parse wandelt ein Zod-Schema in ein json_schema-Antwortformat um und parst die Antwort (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" }
Siehe Strukturierte Ausgaben.
Bildeingabe
Übergeben Sie content als Array von Parts. Verwenden Sie eine öffentliche URL oder eine 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}` } },
],
}],
});
Siehe Vision & Dateien für PDFs, Audio und 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));
Endpunkte ohne SDK-Methode
Videoaufträge und Rerank gehören nicht zur Oberfläche des OpenAI-SDK. Verwenden Sie die generischen Helfer post / get des Clients, sie nutzen Base URL, Schlüssel und Wiederholungen mit:
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);
Fehler
Fehler kommen im OpenAI-Format und werden als OpenAI.APIError geworfen. Verzweigen Sie nach status und 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;
}
}
Alle Codes finden Sie unter Fehler.
Timeouts und Wiederholungen
Das SDK wiederholt Verbindungsfehler sowie Antworten mit 408, 409, 429 und 5xx standardmäßig zweimal, mit exponentiellem Backoff, der Retry-After beachtet. Das Standard-Timeout beträgt 10 Minuten pro Versuch. Setzen Sie beides am Client oder überschreiben Sie es pro Anfrage:
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
timeout: 60_000, // ms pro Versuch
maxRetries: 4,
});
await client.chat.completions.create(params, { timeout: 300_000, maxRetries: 0 });
Eine Wiederholung kann daily_limit_reached oder insufficient_balance nicht beheben. Stoppen Sie bei langen Batch-Jobs bei diesen Codes, statt zu wiederholen. Siehe Rate Limits.
Alle Fähigkeiten
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);