Uncensored AI API 코드 예시: Python, Node.js 및 cURL
이 페이지는 OpenAI 채팅 완료 형식을 따르는 무검열 AI API용 복사-붙여넣기 코드를 모았습니다. Python, Node.js 및 cURL로 첫 호출을 수행하고, SDK 및 raw fetch를 사용한 스트리밍, 함수 호출, 429 및 503 재시도 로직, 다중 턴 상태 관리, max_tokens을 사용한 비용 제어를 찾을 수 있습니다.

주요 포인트
- base_url을 https://api.uncensoredaiapis.com/v1로 설정하고 모델 "uncensored"를 사용하여 공식 openai SDK를 사용하십시오. 커스텀 클라이언트가 필요하지 않습니다.
- 스트리밍은 SSE 청크를 반환하며, 빈 choices 목록을 가진 최종 사용량 청크가 자동으로 도착합니다.
- 429 및 503(upstream_busy)만 재시도하십시오. 400, 401, 402, 403은 재시도가 아닌 수정이 필요합니다.
- API는 상태가 없습니다: 매 턴마다 기록을 다시 전송하고 max_tokens으로 출력을 제한하십시오(선택사항; 설정하지 않으면 응답이 컨텍스트 창의 끝까지 이어질 수 있습니다).
첫 번째 호출: Python, Node.js 및 cURL
예제에서는 https://api.uncensoredaiapis.com/v1, 모델 uncensored 및 POST /v1/chat/completions 또는 GET /v1/models을 사용합니다. 현재 키를 Authorization: Bearer <key> 헤더에 전송하십시오. 필요한 경우 계정을 생성하고 자격이 있는 무료 체험 크레딧을 요청한 후 표시된 잔액이 요청 실행 준비가 되었는지 확인하십시오.
예제들은 API_KEY라는 환경 변수에서 키를 읽습니다. 셸에서 한 번만 내보내면 모든 코드 조각을 수정할 필요가 없습니다. 키를 소스 코드에 붙여넣거나 브라우저 JavaScript에 포함하지 마십시오. API는 백엔드에서 호출하십시오.
export API_KEY="paste-your-key-here"Python: 공식 openai 패키지(v1 이상) 사용. 기본 OpenAI 설정과의 유일한 차이점은 base_url과 모델 이름입니다.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a two-line villain monologue."}],
max_tokens=200,
)
print(resp.choices[0].message.content)
print(resp.usage)Node.js에서는 ES 모듈로 openai npm 패키지를 사용합니다(v4 이상).
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredaiapis.com/v1",
apiKey: process.env.API_KEY,
});
const resp = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Write a two-line villain monologue." }],
max_tokens: 200,
});
console.log(resp.choices[0].message.content);
console.log(resp.usage);그리고 키가 작동하는지 확인하는 가장 빠른 방법인 일반적인 cURL:
curl https://api.uncensoredaiapis.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "Write a two-line villain monologue."}],
"max_tokens": 200
}'응답은 일반적인 OpenAI 구조를 가집니다: 텍스트는 choices[0].message.content이고, 프롬프트 및 completion 토큰 수가 포함된 usage 객체가 있습니다. 이를 토큰별 가격에 곱해 지출을 추적할 수 있습니다. 전체 파라미터 목록은 문서을 참조하십시오.
SDK를 사용한 스트리밍(SSE)
stream: true를 설정하면 API는 하나의 JSON 본문 대신 서버 전송 이벤트를 반환합니다. 공식 SDK 두 개는 이를 이터레이터로 변환하므로, 코드에서 청크를 반복하여 각 delta를 출력합니다. 토큰 usage를 포함하는 최종 청크가 자동으로 추가되므로 요청할 필요가 없습니다. 이 청크에는 빈 choices 목록이 있으므로, 읽기 전에 인덱스를 확인해야 합니다.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Describe a rainy harbor town in 120 words."}],
max_tokens=300,
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print("\n\nusage:", chunk.usage)Node.js 버전은 for await를 사용합니다:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredaiapis.com/v1",
apiKey: process.env.API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Describe a rainy harbor town in 120 words." }],
max_tokens: 300,
stream: true,
});
for await (const chunk of stream) {
const text = chunk.choices?.[0]?.delta?.content;
if (text) process.stdout.write(text);
if (chunk.usage) console.log("\n\nusage:", chunk.usage);
}스트리밍은 가격 책정에 영향을 주지 않습니다. 동일한 입력 및 출력 토큰에 대해 지불하며, 전체 500 토큰 응답을 기다리는 것이 느리게 느껴지는 채팅 및 역할극 인터페이스에서 첫 단어를 더 빨리 볼 수 있습니다.
raw fetch를 사용한 스트리밍
SDK에 의존하지 않으려면(예: 엣지 함수나 작은 스크립트), 스트림을 직접 읽을 수 있습니다. 전송 형식은 일반 SSE입니다. 각 이벤트는 data:로 시작하는 줄과 JSON 청크로 구성되며, 이벤트는 빈 줄로 구분됩니다. 네트워크 청크는 이벤트 경계와 일치하지 않으므로 새 줄에서 버퍼링하고 분할해야 합니다. 아래 예제는 Node 18 이상에서 실행되며(stream.mjs로 저장), 표준 fetch 및 ReadableStream을 지원하는 모든 런타임에서도 작동합니다.
const res = await fetch("https://api.uncensoredaiapis.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "uncensored",
messages: [{ role: "user", content: "Tell a 100-word ghost story." }],
max_tokens: 250,
stream: true,
}),
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const decoder = new TextDecoder();
let buffer = "";
for await (const bytes of res.body) {
buffer += decoder.decode(bytes, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop(); // keep the incomplete tail for the next round
for (const line of lines) {
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
const chunk = JSON.parse(data);
const text = chunk.choices?.[0]?.delta?.content;
if (text) process.stdout.write(text);
if (chunk.usage) console.log("\n\nusage:", chunk.usage);
}
}읽기 시작하기 전에 res.ok을 확인하세요. 401, 402 또는 403과 같은 오류는 이벤트 스트림이 아닌 error 객체를 포함한 일반 JSON 본문으로 도착하므로, 이를 SSE로 구문 분석하면 아무것도 생성되지 않습니다. 브라우저에서는 res.body.getReader()로 동일한 논리를 사용할 수 있지만, 브라우저는 비밀 키로 이 API에 직접 접근하는 대신 자체 백엔드를 호출해야 한다는 점을 기억하세요.
도구 및 tool_choice를 통한 함수 호출
도구 호출은 OpenAI 형식을 사용합니다. tools에 함수를 설명하고, 모델은 실행을 원할 때 텍스트 대신 tool_calls로 응답합니다. 함수를 직접 실행한 후 role: "tool" 및 일치하는 tool_call_id과 함께 메시지 형태로 결과를 다시 전송합니다. 두 번째 요청에서 최종 자연어 답변이 반환됩니다. tool_choice은 동작을 제어합니다: "auto"는 모델이 결정하게 하고, "none"은 도구를 금지하며, {"type": "function", "function": {"name": "get_order_status"}}과 같은 객체는 해당 함수를 강제합니다.
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
def get_order_status(order_id: str) -> dict:
# Replace with a real lookup.
return {"order_id": order_id, "status": "shipped", "eta_days": 2}
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its id.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order A-1042?"}]
first = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
tool_choice="auto",
max_tokens=500,
)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg) # keep the assistant turn that contains tool_calls
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_order_status(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
max_tokens=500,
)
print(final.choices[0].message.content)
else:
print(msg.content)Node.js의 동일한 루프:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredaiapis.com/v1",
apiKey: process.env.API_KEY,
});
const getOrderStatus = ({ order_id }) => ({ order_id, status: "shipped", eta_days: 2 });
const tools = [{
type: "function",
function: {
name: "get_order_status",
description: "Look up the shipping status of an order by its id.",
parameters: {
type: "object",
properties: { order_id: { type: "string" } },
required: ["order_id"],
},
},
}];
const messages = [{ role: "user", content: "Where is order A-1042?" }];
const first = await client.chat.completions.create({
model: "uncensored", messages, tools, tool_choice: "auto", max_tokens: 500,
});
const msg = first.choices[0].message;
if (msg.tool_calls?.length) {
messages.push(msg);
for (const call of msg.tool_calls) {
const result = getOrderStatus(JSON.parse(call.function.arguments));
messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}
const final = await client.chat.completions.create({
model: "uncensored", messages, tools, max_tokens: 500,
});
console.log(final.choices[0].message.content);
} else {
console.log(msg.content);
}두 가지 실용적인 참고 사항입니다. 첫째, arguments은 언어 모델이 생성한 JSON 문자열이므로, 프로덕션에서는 항상 json.loads을 오류 처리로 감싸고 데이터베이스에 접근하기 전에 필드를 검증하십시오. 둘째, 도구 정의는 각 요청에서 입력 토큰으로 계산되므로 설명을 짧게 유지하고 현재 단계에 관련 있는 도구만 전송하십시오.
429 및 503 백오프 재시도
두 가지 오류는 재시도할 가치가 있습니다. 429는 키당 분당 300회 요청 한도를 초과했음을 의미합니다. 503과 코드 upstream_busy는 서비스가 일시적으로 포화 상태임을 의미하며, 몇 초간 기다리는 것이 의도된 응답입니다. 400(요청 수정), 401(키 수정), 402 no_credit(잔액 충전) 또는 403 content_blocked(요청이 다시 차단됨)은 재시도하지 마십시오. 오류는 모두 동일한 JSON 형태인 {"error":{"code":...,"message":...}}를 공유하므로 코드만 직접 로깅할 수 있습니다.
OpenAI SDK는 기본적으로 연결 오류, 429 및 5xx 오류를 몇 번까지 재시도하며, max_retries를 통해 이를 늘릴 수 있습니다. 지연 시간을 직접 제어하려면 내장 재시도를 비활성화하고 지터가 있는 지수 백오프를 사용하여 호출을 직접 래핑하십시오. 이렇게 하면 병렬 작업자가 동시에 재시도하는 것을 방지할 수 있습니다.
import os
import random
import time
from openai import OpenAI, APIStatusError, APIConnectionError
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
max_retries=0, # we handle retries ourselves
)
RETRYABLE = {429, 503}
def chat_with_retry(messages, max_attempts=5, **kwargs):
for attempt in range(max_attempts):
try:
return client.chat.completions.create(
model="uncensored", messages=messages, **kwargs
)
except APIStatusError as e:
if e.status_code not in RETRYABLE or attempt == max_attempts - 1:
raise
except APIConnectionError:
if attempt == max_attempts - 1:
raise
delay = min(30, 2 ** attempt) + random.uniform(0, 1)
time.sleep(delay)
resp = chat_with_retry(
[{"role": "user", "content": "Give me three names for a tavern."}],
max_tokens=100,
)
print(resp.choices[0].message.content)Node.js에서 일반 fetch을 사용한 동일한 코드:
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function chatWithRetry(body, maxAttempts = 5) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const res = await fetch("https://api.uncensoredaiapis.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ model: "uncensored", ...body }),
});
if (res.ok) return res.json();
const retryable = res.status === 429 || res.status === 503;
if (!retryable || attempt === maxAttempts - 1) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const delay = Math.min(30000, 2 ** attempt * 1000) + Math.random() * 1000;
await sleep(delay);
}
}
const data = await chatWithRetry({
messages: [{ role: "user", content: "Give me three names for a tavern." }],
max_tokens: 100,
});
console.log(data.choices[0].message.content);429 오류가 빈번하게 발생한다면, 긴 대기 시간보다는 클라이언트 측 동시성 제한(5~10개의 워커를 가진 세마포어 또는 큐)을 적용하는 것이 더 나은 해결책입니다. 분당 300회 요청 시 초당 5회 요청을 유지할 수 있으며, 이는 대부분의 애플리케이션에 충분합니다.
다중 턴 대화 상태
API는 상태가 없습니다. 이전 요청을 기억하지 않으므로, 모델이 볼 수 있는 기록을 포함하여 모든 호출에 이력이 포함되어야 합니다. 메시지 목록을 유지하고 사용자 턴을 추가한 후 API를 호출하고, 어시스턴트 응답을 추가한 후 반복합니다. 인덱스 0의 시스템 메시지는 페르소나 또는 지침을 포함하며 매번 전송됩니다.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
messages = [
{"role": "system", "content": "You are a dry-witted ship's AI. Keep replies under 80 words."}
]
def say(text: str) -> str:
messages.append({"role": "user", "content": text})
resp = client.chat.completions.create(
model="uncensored", messages=messages, max_tokens=300
)
reply = resp.choices[0].message.content
messages.append({"role": "assistant", "content": reply})
return reply
print(say("We just lost the main engine. Options?"))
print(say("Which of those is the least risky?"))전체 대화 기록이 다시 전송되므로 입력 비용은 대화마다 증가합니다. 컨텍스트 창은 100,000 토큰이며 프롬프트와 생성 결과를 합산한 것이므로, 매우 긴 세션에서는 프롬프트가 한도를 초과하면 400 오류가 반환되고, prompt + max_tokens가 한도를 초과하면 응답이 창 끝에서 멈춥니다. 일반적인 전략은 시스템 메시지를 항상 유지한 채 가장 오래된 사용자 및 어시스턴트 쌍을 삭제하거나, 모델에게 오래된 대화 내용을 요약하여 하나의 짧은 메시지로 대체하도록 요청하는 것입니다. 대화 ID를 키로 사용하여 자체 데이터베이스에 기록을 저장하면 재시작 시 대화 흐름이 끊기지 않습니다. 실제 비용 추정치와 함께 긴 세션의 예시는 use cases page에서 확인하십시오.
max_tokens을 사용한 비용 제어
가격은 입력 토큰 백만 개당 $0.15, 출력 토큰 백만 개당 $0.50이며 선불 잔액에서 청구됩니다. 출력은 입력보다 약 3.3배 비싸며, max_tokens은 단일 요청에 대한 출력의 선택적 상한선입니다. 설정하지 않으면 응답이 컨텍스트 창의 끝까지 이어질 수 있습니다. 의도적으로 설정하는 것이 가장 간단한 비용 제어 방법입니다.
최악의 경우 계산을 확인하십시오. 출력을 제한하지 않으면 응답이 컨텍스트 창의 끝까지 이어질 수 있으므로 출력만 최대 100,000 × $0.50 / 1,000,000 = $0.05의 비용이 발생할 수 있습니다. 채팅 응답에 max_tokens을 300으로 설정하면 최악의 경우 $0.00015로 떨어집니다. 입력 토큰 1,500개와 출력 토큰 300개로 구성된 일반적인 턴은 약 $0.000225 + $0.00015, 즉 $0.001 미만으로 비용이 발생합니다.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
INPUT_PER_M = 0.25
OUTPUT_PER_M = 1.00
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Summarise the plot of Hamlet in 5 sentences."}],
max_tokens=250,
)
u = resp.usage
cost = u.prompt_tokens * INPUT_PER_M / 1_000_000 + u.completion_tokens * OUTPUT_PER_M / 1_000_000
print(f"in={u.prompt_tokens} out={u.completion_tokens} cost=${cost:.6f}")
print("finish_reason:", resp.choices[0].finish_reason)finish_reason을 주의 깊게 관찰하십시오. length 값은 응답이 상한에 도달하여 잘렸음을 의미합니다. 이러한 경우가 자주 발생하면 상한을 높이거나 프롬프트에서 더 짧은 출력을 요청하십시오. 상한만 설정하면 모델이 간결하게 만드는 것이 아니라 잘라내기 때문입니다. 목표 단어 수와 같은 지침과 함께 상한을 사용하고, 모든 호출에 usage을 로그에 기록하여 추측이 아닌 실제 평균을 확인하십시오. 무료 체험 크레딧 및 잔액 세부 정보는 가격 책정 페이지에서 확인할 수 있습니다.
질문과 답변
이 무검열 AI API에 전용 SDK가 필요한가요?
아니요. 공식 openai Python 패키지(v1+)와 openai npm 패키지(v4+)가 작동합니다. base_url을 https://api.uncensoredaiapis.com/v1,로 설정하고 키를 전달한 후, 모델 ID uncensored를 사용하십시오.
스트리밍에 토큰 사용량 정보가 포함되나요?
네. stream: true로 설정하면 API가 사용량 정보를 자동으로 담은 마지막 청크를 추가합니다. 해당 청크는 빈 choices 배열을 가지므로, delta를 읽기 전에 choices가 존재하는지 확인하십시오.
어떤 오류에 대해 코드가 재시도해야 합니까?
지수 백오프와 지터(jitter)를 사용하여 429(속도 제한, 키당 분당 300개 요청) 및 503 upstream_busy를 재시도합니다. 400, 401, 402, 403은 재시도하지 마십시오. 같은 요청이 다시 실패할 것입니다.
호출 간에 대화 기록이 저장됩니까?
아니요. 각 요청은 독립적이므로 매번 전체 messages 목록을 전송해야 합니다. 프롬프트와 completion을 합친 컨텍스트 창은 100,000 토큰입니다.