주요 포인트
- openai를 설치하고 base_url을 https://api.gemininsfw.cc/v1로 설정한 후 모델 ID uncensored를 사용하세요.
- 스트리밍, 도구 호출 및 JSON 모드는 이미 알고 있는 SDK 호출을 통해 작동합니다.
- HTTP 429에서 재시도하고 Retry-After 헤더를 읽으세요. 스트림은 종료될 때까지 동시성 슬롯을 차지합니다.
- 호출당 비용은 쉽게 계산할 수 있습니다: 입력 토큰 100만 개당 $0.15, 출력 토큰 100만 개당 $0.50입니다.
간단한 답변: 작동하는 Python 호출
llm api python 예제를 검색하셨다면 전체 코드를 제공합니다. SDK를 설치하고 키를 내보낸 후 스크립트를 실행하세요. 엔드포인트는 OpenAI 채팅 완성 형식을 사용하므로 특별한 클라이언트가 필요하지 않습니다.
pip install openai
export API_KEY="your-key-here"
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.gemininsfw.cc/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a context window is in two sentences."},
],
temperature=0.7,
)
print(resp.choices[0].message.content)
print(resp.usage)
모델 ID는 uncensored입니다. 인증은 표준 Authorization: Bearer 헤더를 사용하며, SDK는 api_key에서 이를 생성합니다. 키가 없다면 API 키 페이지에서 회원가입과 무료 체험 크레딧 절차를 안내합니다.
먼저 연결을 확인하세요
애플리케이션 코드를 작성하기 전에 키와 URL이 정확한지 확인하세요. API는 GET /v1/models를 노출하며 SDK는 이를 감쌉니다:
for m in client.models.list():
print(m.id)
출력에서 uncensored을 확인해야 합니다. curl로 동일한 확인:
curl https://api.gemininsfw.cc/v1/models \
-H "Authorization: Bearer $API_KEY"
401은 키가 잘못되었거나 누락되었음을 의미합니다. 연결 오류는 base URL에 /v1 접미사가 없거나 오타가 있음을 의미합니다. 이 두 가지 문제가 대부분의 초기 실패를 차지합니다.
모든 응답에는 로깅할 가치가 있는 헤더가 포함됩니다: 지원 문의용 X-Request-Id, 남은 크레딧용 X-Balance-USD, 그리고 제한 사항을 위한 두 개의 X-RateLimit-Limit-* 헤더입니다. SDK에서는 with_raw_response를 사용하여 이를 확인하세요:
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "ping"}],
max_tokens=5,
)
print(raw.headers.get("X-Balance-USD"), raw.headers.get("X-Request-Id"))
completion = raw.parse()스트리밍 응답
채팅 인터페이스에서는 토큰이 도착하는 대로 처리해야 합니다. stream=True을 설정하고 반복하세요. 서버는 Server-Sent Events를 보내고 스트림 끝에 사용량을 보고합니다.
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a four-line poem about servers."}],
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 getattr(chunk, "usage", None):
print("\n", chunk.usage)
동시성 관련 중요한 세부 사항: 스트리밍 요청은 스트림이 끝날 때까지 슬롯을 차지합니다. 스트림을 열고 읽기를 중단하면 슬롯이 비워지지 않습니다. 항상 스트림을 소비하거나 finally 블록에서 닫으세요.
JSON 모드 및 도구 호출
두 가지 기능은 이 API를 채팅 상자뿐만 아니라 백엔드에도 유용하게 만듭니다.
JSON 모드
response_format={"type": "json_object"}를 전달하고 프롬프트에서 JSON을 원한다고 명시하세요. 그런 다음 결과를 구문 분석하세요:
import json
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply only with a JSON object."},
{"role": "user", "content": "Give me a character with keys name, age, trait."},
],
)
data = json.loads(resp.choices[0].message.content)
print(data)
여전히 json.loads를 try 블록으로 감싸야 합니다. 낮은 max_tokens으로 잘린 긴 답변은 유효하지 않은 JSON을 생성할 수 있습니다.
함수 호출
일반 스키마로 도구를 정의하고 응답에서 tool_calls을 확인한 후 함수를 실행하고 결과를 role: "tool" 메시지로 다시 보내세요.
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "Weather in Lisbon?"}]
first = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message
if msg.tool_calls:
call = msg.tool_calls[0]
messages.append(msg)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": '{"temp_c": 21, "sky": "clear"}',
})
final = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools
)
print(final.choices[0].message.content)429 오류 및 재시도 처리
전체 키는 동시 요청 8개와 분당 요청 300개를 허용합니다. 체험 키는 동시 2개, 분당 60개를 허용합니다. 한도를 초과하면 HTTP 429 오류가 발생하며, 오류 코드로 어떤 한도를 초과했는지 알 수 있습니다. rate_limited은 분당 요청이 많음을, concurrency은 동시 요청이 많음을 의미합니다. 일시적 과부하 시 API는 Retry-After: 5와 함께 429도 반환합니다.
OpenAI SDK는 자체적으로 몇 번 재시도합니다. 배치 작업의 경우 병렬 작업에 자체 제한을 추가하여 동시성 한도 내에 머무르세요:
import time
from concurrent.futures import ThreadPoolExecutor
from openai import RateLimitError
def ask(prompt):
for attempt in range(5):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError as e:
wait = int(e.response.headers.get("Retry-After", 5))
time.sleep(wait * (attempt + 1))
raise RuntimeError("still rate limited")
prompts = [f"Summarize topic {i} in one line." for i in range(40)]
with ThreadPoolExecutor(max_workers=6) as pool:
results = list(pool.map(ask, prompts))
워커 6개는 8개 제한 아래에 있어 다른 트래픽을 위한 여유가 있습니다. 본문 제한은 8 MB이며, 매우 큰 문서를 붙여넣는 경우에만 의미가 있습니다. 프롬프트와 완성을 위한 컨텍스트 창은 100,000 토큰입니다.
호출 비용
선불 크레딧에서 토큰당 과금됩니다: 입력 토큰 100만 개당 $0.15, 출력 토큰 100만 개당 $0.50입니다. resp.usage을 읽고 코드에서 비용을 계산하세요:
def cost_usd(usage):
return usage.prompt_tokens * 0.15 / 1_000_000 + usage.completion_tokens * 0.50 / 1_000_000
print(round(cost_usd(resp.usage), 6))
작동 예시: 입력 토큰 2,000개와 출력 토큰 500개로 호출하면 입력 비용은 2,000 x $0.15 / 1M = $0.0003, 출력 비용은 500 x $0.50 / 1M = $0.00025로 총 $0.00055가 발생합니다. 실패하거나 거부된 요청에는 요금이 부과되지 않습니다. 가격 책정 페이지에는 충전 금액과 보너스가 있으며 크레딧은 만료되지 않습니다.
대화 기록 유지
API는 상태가 없습니다: 이전 호출을 기억하지 않습니다. 대화를 유지하려면 메시지 목록을 유지하고 매번 전체 목록을 보내야 합니다. 모든 턴 후에 어시스턴트 응답을 추가하세요.
history = [{"role": "system", "content": "You are a helpful storyteller."}]
def say(text):
history.append({"role": "user", "content": text})
r = client.chat.completions.create(model="uncensored", messages=history)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(say("Start a story about a clockmaker."))
print(say("Continue, and add a stranger at the door."))
입력 토큰은 매 턴마다 증가하며, 전체 대화 기록이 매번 입력으로 청구됩니다. 창은 프롬프트와 완성을 위해 100,000 토큰으로 많지만, 긴 대화는 호출당 비용이 더 많이 듭니다. 간단한 해결책은 시스템 프롬프트와 마지막 N턴을 유지하거나, 모델에게 오래된 턴을 요약하여 짧은 메시지로 만들도록 요청하는 것입니다. seed 매개변수는 고정된 temperature와 함께 테스트 시 반복 가능한 출력을 원할 때 도움이 됩니다.
다음 단계
기본 호출이 작동하면 키를 환경 변수나 시크릿 매니저에 넣고 저장소에는 남기지 마세요. docs에서 요청 형식을 더 자세히 다룹니다. 다른 OpenAI 스타일 엔드포인트 뒤의 모델들을 비교 중이라면, GLM API 가이드에서 유사한 설정이 어떻게 보이는지 확인할 수 있습니다. 이 서비스는 텍스트 전용임을 기억하세요: 이미지, 오디오, 임베딩, 파인튜닝은 없습니다.
