Node.js AI API: Express에서 스트리밍, 도구 및 오류 처리
이 Node.js AI API 튜토리얼은 빈 폴더에서 시작하여 채팅 응답을 스트리밍하고, 도구를 호출하며, 속도 제한 오류를 처리하는 Express 라우트까지 안내합니다. 공식 OpenAI 패키지에서 Base URL과 키만 변경한 후 uncensored 모델 ID를 전송하면 됩니다.
업데이트됨Unfiltered AI

주요 포인트
- openai 패키지를 설치하고 baseURL을 https://api.unfilteredaiapi.com/v1로 설정하세요.
- stream: true로 스트리밍하고 청크를 서버 전송 이벤트로 브라우저에 전달하세요.
- 도구 호출은 tool_calls로 도착하며, role tool로 결과를 반환하세요.
- 429는 rate_limited, concurrency 또는 임시 과부하를 의미하며, Retry-After 지연 후 다시 시도하세요.
설정: 설치 및 첫 번째 요청 보내기
Node 18 이상이 필요합니다. 프로젝트를 생성하고 SDK와 Express를 설치한 후 ES 모듈로 전환하세요.
mkdir ai-node && cd ai-node
npm init -y
npm pkg set type=module
npm install openai express
# base URL: https://api.unfilteredaiapi.com/v1 model: uncensored
export AI_API_KEY="YOUR_KEY"
API 키 페이지에서 키를 가져오세요. 신규 계정은 클릭 한 번으로 7일 유효한 $0.50의 무료 체험 크레딧을 받을 수 있습니다. 그런 다음 client.js를 생성하세요:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.unfilteredaiapi.com/v1",
apiKey: process.env.AI_API_KEY,
});
const res = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Give me three names for a tavern keeper." }],
});
console.log(res.choices[0].message.content);
node client.js로 실행하세요. 아래 각 스니펫은 자체적으로 실행되도록 클라이언트를 다시 정의합니다. 이미 OpenAI 패키지를 사용하고 있다면 전체 마이그레이션은 다른 baseURL, 키 및 모델 ID로 구성됩니다. 이 서비스는 OpenAI 호환이며 텍스트 전용이며 100,000 토큰 컨텍스트 창을 제공합니다. 지원되는 모든 메서드에 대해서는 문서를 참조하세요.
응답 스트리밍
스트리밍은 생성되는 대로 토큰을 전송하므로 사용자가 텍스트를 즉시 볼 수 있습니다. stream: true를 설정하고 청크를 반복하세요:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.unfilteredaiapi.com/v1",
apiKey: process.env.AI_API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Describe a rainy harbor town." }],
stream: true,
stream_options: { include_usage: true },
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
if (chunk.usage) console.log("\nusage:", chunk.usage);
}
사용량 정보는 마지막 청크에 도착하므로 요청당 실제 토큰 개수를 로깅할 수 있습니다. 한 가지 사실을 기억하세요: 스트리밍 요청은 스트림이 끝날 때까지 동시성 슬롯을 점유합니다. 클라이언트가 연결을 끊으면 슬롯이 빠르게 해제되도록 업스트림 호출을 중단하세요.
브라우저로 스트리밍하는 Express 라우트
여기에는 POST /chat 라우트가 있는 작은 서버가 있습니다. 이 라우트는 스트리밍을 서버 전송 이벤트로 전달하고 브라우저가 연결을 닫으면 업스트림 요청을 취소합니다.
import express from "express";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.unfilteredaiapi.com/v1",
apiKey: process.env.AI_API_KEY,
});
const app = express();
app.use(express.json({ limit: "1mb" }));
app.post("/chat", async (req, res) => {
const { messages } = req.body;
if (Array.isArray(messages) === false) return res.status(400).json({ error: "messages required" });
res.set({
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
const controller = new AbortController();
req.on("close", () => controller.abort());
try {
const stream = await client.chat.completions.create(
{ model: "uncensored", messages, stream: true },
{ signal: controller.signal }
);
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content;
if (delta) res.write("data: " + JSON.stringify({ delta }) + "\n\n");
}
res.write("data: [DONE]\n\n");
} catch (err) {
res.write("data: " + JSON.stringify({ error: err.status || 500 }) + "\n\n");
} finally {
res.end();
}
});
app.listen(3000, () => console.log("listening on 3000"));
키를 브라우저 코드에 넣지 마세요. 위의 라우트는 키를 서버에 유지합니다. 동일한 패턴은 FastAPI 채팅백엔드 글에서 Python으로 보여줍니다.
도구 호출
도구 호출은 OpenAI 형식을 따릅니다: tools에서 함수를 설명하고, 모델은 tool_calls로 응답하며, 함수를 실행하고 결과를 role: "tool" 메시지로 다시 보냅니다.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.unfilteredaiapi.com/v1",
apiKey: process.env.AI_API_KEY,
});
const tools = [{
type: "function",
function: {
name: "roll_dice",
description: "Roll a die with the given number of sides",
parameters: {
type: "object",
properties: { sides: { type: "integer" } },
required: ["sides"],
},
},
}];
const messages = [{ role: "user", content: "Roll a d20 for my attack." }];
const first = await client.chat.completions.create({
model: "uncensored", messages, tools, tool_choice: "auto",
});
const msg = first.choices[0].message;
if (msg.tool_calls) {
messages.push(msg);
for (const call of msg.tool_calls) {
const { sides } = JSON.parse(call.function.arguments);
const result = 1 + Math.floor(Math.random() * sides);
messages.push({ role: "tool", tool_call_id: call.id, content: String(result) });
}
const second = await client.chat.completions.create({ model: "uncensored", messages, tools });
console.log(second.choices[0].message.content);
}
실제 코드에서는 모델이 가끔 잘못된 JSON을 반환할 수 있으므로 항상 arguments를 try 블록 내에서 파싱하세요. 도구 없이 구조화된 출력을 위해 response_format: { type: "json_object" }를 설정하고 프롬프트에 JSON을 명시하세요. 주사위나 인벤토리 함수를 호출하는 게임 장면은 게임 NPC 및 텍스트 어드벤처 구축에서 다룹니다.
오류 및 속도 제한 처리
API는 세 가지 상황에서 HTTP 429를 반환합니다. 오류 코드 rate_limited은 분당 요청 수가 많음을 의미합니다: 전체 키는 300개, 체험 키는 60개입니다. 코드 concurrency은 동시 요청이 많음을 의미합니다: 전체 키는 8개, 체험 키는 2개입니다. 일시적 과부하 시 Retry-After: 5 헤더와 함께 429도 반환합니다. SDK는 발생한 오류의 상태를 노출하므로 작은 래퍼로 세 가지 상황을 모두 처리할 수 있습니다:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.unfilteredaiapi.com/v1",
apiKey: process.env.AI_API_KEY,
});
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export async function chatWithRetry(params, tries = 4) {
for (let i = 0; i < tries; i++) {
try {
return await client.chat.completions.create({ model: "uncensored", ...params });
} catch (err) {
if (err.status === 429 && i < tries - 1) {
const wait = Number(err.headers?.["retry-after"]) || 2 ** i;
await sleep(wait * 1000);
continue;
}
throw err;
}
}
}
래퍼는 서버가 지정한 지연 시간을 기다린 후 지수 백오프로 전환합니다. OpenAI 패키지도 일부 오류를 자체적으로 재시도하므로, 이를 제어하려면 클라이언트에 maxRetries를 설정하세요. 잘못된 키에 대한 401과 같은 다른 상태는 재시도하지 않아야 합니다. 제한 사항에 대한 심층 분석은 FAQ를 참조하세요.
라우트 실행 및 테스트
node server.js로 서버를 시작하고 두 번째 터미널에서 테스트하세요. -N 플래그는 curl 버퍼링을 비활성화하여 이벤트가 하나씩 도착하는 것을 볼 수 있게 합니다:
# the server calls https://api.unfilteredaiapi.com/v1 with model uncensored
curl -N http://localhost:3000/chat -H "Content-Type: application/json" -d '{"messages":[{"role":"user","content":"Write a two-line riddle."}]}'
브라우저에서는 fetch와 리더를 사용하거나 작은 SSE 헬퍼 라이브러리로 스트림을 읽으세요. 라우트가 POST이므로 네이티브 EventSource 객체는 사용할 수 없으므로 fetch를 사용하고 청크를 직접 디코딩하세요.
프로덕션 환경에서의 모범 사례
- 키를 환경 변수나 비밀 저장소에 보관하고 저장소에는 절대 넣지 마십시오.
- 요청 본문 크기를 제한하세요. API는 최대 8 MB까지 받지만, 자체 라우트는 훨씬 작은 크기를 받아야 합니다.
- 보내는 대화 기록을 제한하세요. 오래된 턴은 비용이 늘거나 100,000 토큰 창이 가득 차기 전에 잘라내세요.
- 이미 8개의 스트림이 활성화되어 있을 때 추가 작업을 대기열에 넣거나 거부하세요. API가 사용자에게 429를 반환하게 두지 마세요.
X-Request-Id응답 헤더를 기록하여 단일 요청을 추적할 수 있게 하세요.
잔액 및 비용 확인
모든 응답에는 X-Balance-USD 헤더가 포함되며, GET /v1/balance는 잔액을 직접 반환합니다. 가격은 1M 입력 토큰당 $0.15, 1M 출력 토큰당 $0.50이며 선불 크레딧에서 차감됩니다. 실패하거나 거부된 요청은 무료입니다. 입력 토큰 800개와 출력 토큰 250개로 구성된 채팅 턴은 $0.000245가 들며, 10,000 턴은 $2.45입니다. 각 응답에서 usage를 로깅하면 청구 금액을 몇 센트 이내로 예측할 수 있습니다. 가격 책정 페이지에는 $20부터 $500까지의 충전 금액이 나열되어 있습니다.
더 많은 가이드
질문과 답변
어떤 npm 패키지를 사용해야 하나요?
공식 openai 패키지가 작동합니다. baseURL을 https://api.unfilteredaiapi.com/v1로 설정하고 키를 전달한 후 uncensored 모델 ID를 사용하세요.
Node에서 응답을 스트리밍할 수 있나요?
네. stream: true를 전달하고 for await로 반복하세요. 마지막 청크에서 토큰 개수를 얻으려면 include_usage가 포함된 stream_options를 추가하세요.
API가 함수 호출을 지원하나요?
네. tools와 tool_choice를 보내고, 응답에서 tool_calls를 읽은 후 role tool인 메시지로 결과를 반환하세요.
HTTP 429 시 서버는 어떻게 해야 하나요?
Retry-After 값이 있으면 기다렸다가 없으면 지수 백오프 후 몇 번 다시 시도하세요. 오류 코드가 concurrency인 경우 동시 요청을 줄이세요.