SDKガイド
Node.js
公式 openai npm パッケージで api14 を使う方法です。baseURL と apiKey の設定から、チャット、ストリーミング、ツール呼び出し、構造化出力、画像入力、埋め込み、SDK にないエンドポイントの呼び出しまでを示します。
公式の openai npm パッケージを api14 で使います。ほかに変わることはなく、baseURL と apiKey を api14 に向けるだけで、あらゆるモデル ID を model として使えます。
インストール
npm install openai
キーは環境変数に保存します。
export API14_API_KEY="sk-api14-..."
設定
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
});
オプションなしの場合、SDK は OPENAI_BASE_URL と OPENAI_API_KEY を読み取ります。この 2 つの変数を設定すると、コードを変更せずに既存のアプリを api14 に切り替えられます。
export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
const client = new OpenAI(); // 両方の変数を読み取る
チャット
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);
ストリーミング
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 ?? "");
}
イベント形式はストリーミングを参照してください。
ツール呼び出し
tools を送信し、モデルが要求した呼び出しを実行して結果を追加し、モデルがテキストで回答するまで再度呼び出します。
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); // 自分の関数
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);
ツール呼び出しを参照してください。
構造化出力
parse ヘルパーは、Zod のスキーマを json_schema のレスポンス形式に変換し、返信を解析します(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" }
構造化出力を参照してください。
画像入力
content をパートの配列として渡します。公開 URL または base64 のデータ 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}` } },
],
}],
});
PDF、音声、動画については画像とファイル入力を参照してください。
埋め込み
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 のメソッドがないエンドポイント
動画ジョブとリランクは、OpenAI SDK の対象外です。クライアントの汎用的な post / get ヘルパーを使うと、ベース URL、キー、再試行がそのまま使われます。
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);
エラー
エラーは OpenAI の形式で届き、OpenAI.APIError としてスローされます。status と 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;
}
}
すべてのコードはエラーを参照してください。
タイムアウトと再試行
SDK は、接続エラー、408、409、429、5xx のレスポンスを、Retry-After に従う指数バックオフでデフォルトで 2 回再試行します。デフォルトのタイムアウトは、1 回の試行あたり 10 分です。どちらもクライアントで設定するか、リクエストごとに上書きできます。
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
timeout: 60_000, // 1 回の試行あたりのミリ秒
maxRetries: 4,
});
await client.chat.completions.create(params, { timeout: 300_000, maxRetries: 0 });
再試行しても daily_limit_reached や insufficient_balance は解決しません。長いバッチジョブでは、これらのコードで再試行せずに停止してください。レート制限を参照してください。
すべての機能
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);