주요 포인트
- npm install openai를 실행한 후 baseURL을 https://api.gemininsfw.cc/v1로 설정합니다.
- 스트리밍은 응답에 대해 for await를 사용하고, 사용량은 마지막에 나옵니다.
- 도구 호출은 메시지에서 반환되며, 결과는 role tool로 입력됩니다.
- HTTP 429 발생 시, 재시도하기 전에 오류 코드와 Retry-After 헤더를 확인하세요.
llm api node 프로젝트용 빠른 설정
이것은 llm api node 통합을 위한 빠른 경로입니다. Node 18 이상, ES 모듈을 사용하는 프로젝트, 그리고 키 페이지에서 발급한 API 키가 필요합니다.
mkdir llm-demo && cd llm-demo
npm init -y
npm pkg set type=module
npm install openai
export API_KEY="your-key-here"
index.js를 생성하세요:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.gemininsfw.cc/v1",
apiKey: process.env.API_KEY,
});
const resp = await client.chat.completions.create({
model: "uncensored",
messages: [
{ role: "system", content: "You are a concise assistant." },
{ role: "user", content: "Give me three names for a fantasy tavern." },
],
temperature: 0.8,
});
console.log(resp.choices[0].message.content);
console.log(resp.usage);
node index.js로 실행하세요. 패키지는 키를 Authorization: Bearer 헤더로 전송하므로 직접 설정할 필요가 없습니다.
SDK 없음: 일반 fetch
의존성을 완전히 없애고 싶다면 Node 18에는 fetch가 내장되어 있습니다. API에는 POST /v1/chat/completions과 GET /v1/models 두 가지 메서드가 있으므로 간단한 래퍼를 작성하기 쉽습니다.
async function chat(messages) {
const res = await fetch("https://api.gemininsfw.cc/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ model: "uncensored", messages }),
});
if (res.ok === false) {
const err = await res.text();
throw new Error(`HTTP ${res.status}: ${err}`);
}
return res.json();
}
const data = await chat([{ role: "user", content: "Hello" }]);
console.log(data.choices[0].message.content);
스트리밍 헬퍼, 타입 지정된 응답 및 내장 재시도가 필요할 때는 SDK가 더 나은 선택입니다. 번들 크기가 중요한 작은 스크립트나 서버리스 함수에는 원본 버전이 적합합니다.
Node에서의 스트리밍
stream: true를 설정하고 for await로 결과를 반복합니다. 토큰은 도착할 때마다 출력되며, 스트림 끝에 사용량이 보고됩니다.
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Tell a two-paragraph story about a lighthouse." }],
stream: 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("\n", chunk.usage);
}
스트리밍을 브라우저로 전달하려면 Express 핸들러가 Content-Type: text/event-stream를 설정하고 각 delta를 SSE data: 라인으로 작성해야 합니다. 한 가지 규칙을 기억하세요: 스트리밍 요청은 스트림이 끝날 때까지 동시성 슬롯을 유지합니다. 브라우저가 연결을 끊으면 스트림 읽기를 중지하여 슬롯을 해제합니다. SDK에서는 stream.controller.abort()를 호출합니다.
도구 호출 및 JSON 모드
도구
tools와 선택적으로 tool_choice을 전달합니다. 모델이 함수를 호출하려면 응답에 tool_calls가 포함됩니다. 함수를 실행하고 출력을 role: "tool" 메시지로 반환합니다.
const tools = [{
type: "function",
function: {
name: "roll_dice",
description: "Roll an n-sided die",
parameters: {
type: "object",
properties: { sides: { type: "integer" } },
required: ["sides"],
},
},
}];
const messages = [{ role: "user", content: "Roll a d20 for me." }];
const first = await client.chat.completions.create({
model: "uncensored", messages, tools, tool_choice: "auto",
});
const msg = first.choices[0].message;
if (msg.tool_calls?.length) {
const call = msg.tool_calls[0];
const { sides } = JSON.parse(call.function.arguments);
const result = 1 + Math.floor(Math.random() * sides);
messages.push(msg, {
role: "tool",
tool_call_id: call.id,
content: JSON.stringify({ result }),
});
const final = await client.chat.completions.create({
model: "uncensored", messages, tools,
});
console.log(final.choices[0].message.content);
}
JSON 모드
response_format: { type: "json_object" }를 추가하고 프롬프트에서 JSON을 요청합니다. 출력이 잘릴 수 있으므로 JSON.parse을 try/catch로 감쌉니다.
작은 채팅 서버용 프로젝트 레이아웃
실제 앱에서는 클라이언트를 하나의 모듈로 유지하고 필요한 곳에서 가져오세요. 이렇게 하면 baseURL, 키 및 재시도 설정이 한 곳에 위치합니다.
// llm.js
import OpenAI from "openai";
export const llm = new OpenAI({
baseURL: "https://api.gemininsfw.cc/v1",
apiKey: process.env.API_KEY,
maxRetries: 2,
});
export async function complete(messages, opts = {}) {
const r = await llm.chat.completions.create({
model: "uncensored",
messages,
...opts,
});
return r.choices[0].message.content;
}
그런 다음 라우트 핸들러에서 complete()를 호출하고 키를 직접 건드리지 않습니다. 대화 기록을 서버에 저장하고 세션 ID를 키로 사용하여 관리하세요. 기록이 길어지면 이전 턴을 잘라내야 합니다. API는 상태가 없으므로 각 요청에는 모델이 볼 모든 메시지를 포함해야 합니다.
오류, 재시도 및 제한
SDK는 status 필드가 있는 OpenAI.APIError 하위 클래스를 던집니다. 전체 키는 동시 요청 8개와 분당 300개의 요청을 허용하며, 체험 키는 각각 2개와 60개를 허용합니다. 한도를 초과하면 코드 rate_limited 또는 concurrency와 함께 HTTP 429를 받습니다. 짧은 과부하 동안 API는 Retry-After: 5와 함께 429를 보냅니다.
const client = new OpenAI({
baseURL: "https://api.gemininsfw.cc/v1",
apiKey: process.env.API_KEY,
maxRetries: 3,
timeout: 120_000,
});
async function safeAsk(prompt) {
try {
const r = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: prompt }],
});
return r.choices[0].message.content;
} catch (e) {
if (e.status === 429) {
console.error("limited, retry-after:", e.headers?.["retry-after"]);
}
throw e;
}
}
배치 작업의 경우 Promise.all로 모든 것을 동시에 실행하지 마세요. 고정된 수의 워커가 있는 작은 큐를 사용하세요(예: 6). 이렇게 하면 전체 키의 8개 동시 슬롯을 초과하지 않습니다. 요청 본문은 8 MB로 제한되며, 프롬프트와 응답을 합쳐 컨텍스트 창은 100,000 토큰입니다.
비용 및 다음 단계
가격은 입력 토큰 100만 개당 $0.15, 출력 토큰 100만 개당 $0.50입니다. 프롬프트 토큰 3,000개와 응답 토큰 600개로 구성된 채팅봇 턴의 비용은 3,000 x $0.15 / 1M = $0.00045 + 600 x $0.50 / 1M = $0.0003이며, 총 $0.00075입니다. 1,000개의 턴은 $0.75입니다. 실패하거나 거부된 요청은 요금이 부과되지 않으며, 응답 헤더 X-Balance-USD에 남은 금액이 표시됩니다.
새로운 사용자는 키 페이지에서 $0.50의 무료 체험 크레딧을 받을 수 있으며, 요금 페이지에는 $20부터 $500까지의 선불 크레딧 충전 옵션이 나열되어 있습니다. 요청 형식에 대한 자세한 내용은 문서을 참조하세요. 이 서비스는 텍스트만 처리하므로 이미지, 오디오 및 임베딩 호출은 작동하지 않습니다.
