SDK 가이드
Node.js
Node.js에서 공식 openai npm 패키지를 api14와 함께 쓰는 방법입니다. 기본 설정과 스트리밍, 도구 호출, 구조화 출력, 이미지 입력, 임베딩, 타임아웃과 재시도 코드를 보여 줍니다. 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를 읽습니다. 이 두 변수만 설정하면 코드 변경 없이 기존 앱을 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 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}` } },
],
}],
});
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 메서드가 없는 엔드포인트
동영상 작업과 rerank는 OpenAI SDK의 범위에 포함되지 않습니다. 클라이언트의 범용 post / get 헬퍼를 사용하세요. base 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를 따르는 지수 백오프를 사용합니다. 기본 타임아웃은 시도당 10분입니다. 두 값 모두 클라이언트에서 설정하거나 요청별로 재정의할 수 있습니다.
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
timeout: 60_000, // 시도당 ms
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);