Przewodniki SDK
Node.js
Użyj oficjalnego pakietu npm openai z api14 w Node.js i TypeScript: konfiguracja, streaming, narzędzia, ustrukturyzowane wyjście i błędy.
Użyj oficjalnego pakietu npm openai z api14. Nic więcej się nie zmienia: tylko baseURL i apiKey wskazują na api14, a każdy identyfikator modelu działa jako model.
Instalacja
npm install openai
Przechowuj klucz w zmiennej środowiskowej:
export API14_API_KEY="sk-api14-..."
Konfiguracja
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
});
Bez opcji SDK odczytuje OPENAI_BASE_URL i OPENAI_API_KEY. Ustawienie tych dwóch zmiennych przełącza istniejącą aplikację na api14 bez zmian w kodzie:
export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
const client = new OpenAI(); // picks up both variables
Czat
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 ?? "");
}
Format zdarzeń opisuje Streaming.
Wywoływanie narzędzi
Wyślij tools, wykonaj wywołania, o które prosi model, dołącz wyniki i wywołuj ponownie, aż model odpowie tekstem:
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);
Zobacz Wywoływanie narzędzi.
Ustrukturyzowane wyjście
Pomocnik parse zamienia schemat Zod na format odpowiedzi json_schema i parsuje odpowiedź (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" }
Zobacz Ustrukturyzowane wyjście.
Obraz na wejściu
Przekaż content jako tablicę części. Użyj publicznego adresu URL lub adresu data: w 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}` } },
],
}],
});
Pliki PDF, dźwięk i wideo opisuje Obrazy i pliki w wejściu.
Embeddingi
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));
Endpointy bez metody w SDK
Zadania wideo i rerank nie należą do powierzchni SDK OpenAI. Użyj ogólnych pomocników klienta post / get, które korzystają z bazowego adresu, klucza i ponowień:
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);
Błędy
Błędy przychodzą w formacie OpenAI i są rzucane jako OpenAI.APIError. Rozgałęziaj logikę według status i 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;
}
}
Wszystkie kody opisuje Błędy.
Limity czasu i ponowienia
SDK domyślnie ponawia błędy połączenia oraz odpowiedzi 408, 409, 429 i 5xx dwukrotnie, z wykładniczym opóźnieniem respektującym Retry-After. Domyślny limit czasu to 10 minut na próbę. Ustaw oba na kliencie lub nadpisz je dla pojedynczego żądania:
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 });
Ponowienie nie naprawi daily_limit_reached ani insufficient_balance. W długich zadaniach wsadowych zatrzymaj się na tych kodach zamiast ponawiać. Zobacz Limity zapytań.
Wszystkie możliwości
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);