1단계: SDK 설치 및 키 설정
이 서비스는 OpenAI chat completions 프로토콜을 사용하므로 특별한 클라이언트가 필요하지 않습니다. 공식 패키지를 설치하고 키를 환경 변수에 저장하세요. 소스 코드에 넣지 마세요.
pip install openai
export API_KEY="paste-your-key-here"
curl https://api.apertus.top/v1/models -H "Authorization: Bearer $API_KEY"
curl https://api.apertus.top/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
-d '{"model":"uncensored","messages":[{"role":"user","content":"ping"}]}'
GET /v1/models 호출은 키가 작동하는지 확인하는 가장 빠른 방법이며, 두 번째 호출은 한 단어 테스트 채팅을 보냅니다. 키가 아직 없다면 여기서 생성하세요. 새 사용자는 키 페이지에서 한 번의 클릭으로 무료 체험 크레딧 $0.50을 받을 수 있습니다. 카드가 필요 없으며 7일 동안 유효합니다.
python -m venv .venv 가상 환경을 사용하여 프로젝트에 패키지 버전을 고정하세요. 노트북에서 작업할 경우 커널 시작 전에 변수를 설정하거나 getpass로 읽어 저장 파일에 남지 않게 하세요.
2단계: 첫 요청 보내기
클라이언트를 base URL에 연결하고 모델로 uncensored를 전달하세요. 나머지는 호스팅된 LLM에 작성할 코드와 동일합니다.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.apertus.top/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain what a context window is in two sentences."},
],
temperature=0.7,
max_tokens=200,
)
print(resp.choices[0].message.content)
print(resp.usage)
시작부터 도움이 되는 세부 사항 세 가지가 있습니다. messages 목록은 전체 대화이므로 모델은 사용자가 보낸 내용만 알 수 있습니다. max_tokens은 선택 사항이며, 이를 지정하지 않으면 응답이 100,000개 토큰 컨텍스트 창에 남은 용량을 모두 사용할 수 있습니다. 그리고 resp.usage는 과금된 토큰을 보여주므로 빌드하는 동안 비용을 확인할 수 있습니다. 동일한 엔드포인트는 seed, stop, top_p 및 빈도 및 존재 페널티도 허용합니다.
3단계: 대화 유지하기
LLM은 호출 간에 기억을 유지하지 않습니다. 채팅을 만들려면 각 메시지를 저장하고 목록을 다시 보내야 합니다. 이 작은 루프는 Python 목록에 기록을 유지합니다:
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
history = [{"role": "system", "content": "Answer briefly."}]
while True:
text = input("you: ")
if text in ("q", "quit"):
break
history.append({"role": "user", "content": text})
resp = client.chat.completions.create(model="uncensored", messages=history)
answer = resp.choices[0].message.content
history.append({"role": "assistant", "content": answer})
print("llm:", answer)
각 호출이 대화 기록을 다시 보내므로 입력 토큰은 모든 턴마다 증가합니다. 긴 세션의 경우 컨텍스트 한계에 도달하기 전에 오래된 메시지를 삭제하거나 요약하세요.
매 턴마다 resp.usage.prompt_tokens를 로깅하는 습관을 들이세요. 각 대화의 길이만큼 숫자가 증가하는 것을 확인하여 언제 기록을 줄여야 하는지 알 수 있습니다.
4단계: 답변 스트리밍
스트리밍은 도착하는 대로 단어를 출력하므로 터미널이나 웹 UI에서 더 빠르게 느껴집니다. stream=True를 설정하고 청크를 반복하세요. 스트림은 서버 전송 이벤트를 사용하며 사용량 데이터로 끝납니다.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "List five uses of a hash map."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
기억해야 할 규칙 하나: 스트리밍 요청은 스트림이 끝날 때까지 동시 슬롯 중 하나를 차지하므로 항상 스트림을 소비하거나 닫으세요.
5단계: JSON 가져오기 및 도구 호출
JSON 모드
프로그램이 출력을 읽는 경우, response_format을 설정하고 프롬프트에서 원하는 형태를 설명하세요.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[{"role": "user", "content":
'Return JSON with keys "title" and "tags" (a list) for a post about Python generators.'}],
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])
함수 호출
tools를 전달하면 모델이 코드에서 함수를 실행하도록 요청할 수 있습니다. 함수를 실행한 후 결과를 role: "tool" 메시지로 보냅니다.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
tools = [{"type": "function", "function": {
"name": "add",
"description": "Add two numbers",
"parameters": {"type": "object",
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
"required": ["a", "b"]}}}]
messages = [{"role": "user", "content": "What is 17.5 plus 24.25?"}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)
messages.append(first.choices[0].message.model_dump(exclude_none=True))
messages.append({"role": "tool", "tool_call_id": call.id, "content": str(args["a"] + args["b"])})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
실제 코드에서는 인덱싱하기 전에 tool_calls이 비어 있지 않은지 확인하세요. 모델이 직접 응답할 수 있습니다.
6단계: 오류 및 속도 제한 처리
전체 키는 동시 요청 8개와 분당 요청 300개를 허용합니다. 체험 키는 각각 2개와 60개를 허용합니다. 이를 초과하면 API는 코드 rate_limited(분당 과다) 또는 concurrency(동시 과다)와 함께 HTTP 429를 반환합니다. 일시적 과부하 시 Retry-After: 5와 함께 429도 전송합니다. SDK는 RateLimitError을 발생시키므로 호출을 짧은 재시도 루프로 감싸야 합니다.
import os, time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
def ask(prompt, tries=5):
for attempt in range(tries):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}])
return r.choices[0].message.content
except RateLimitError:
wait = 5 * (attempt + 1)
print("429, retrying in", wait, "s")
time.sleep(wait)
raise RuntimeError("gave up after retries")
print(ask("Name three Python web frameworks."))
배치 작업에는 동시성 제한을 초과하지 않도록 워커 수를 8로 제한한 스레드 풀을 사용하세요(체험용 키의 경우 2개). 응답에는 X-Request-Id 및 X-Balance-USD 헤더가 포함되어 있어 로그 작성 및 잔액 확인에 유용합니다. 문서에는 모든 파라미터가 나열되어 있으며, XAI API 페이지은 다른 OpenAI 호환 개요를 제공합니다.
비동기 코드 및 일반적인 오류
웹 서버와 많은 동시 호출의 경우 동일한 패키지의 비동기 클라이언트를 사용하세요. 이 클라이언트는 동일한 인수를 받으며 실행 중인 요청에 대해 세마포어 크기 제한 풀을 유지하여 동시성 제한을 넘지 않도록 합니다.
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
sem = asyncio.Semaphore(8)
async def ask(prompt):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}])
return r.choices[0].message.content
async def main():
prompts = [f"Give one tip about Python, number {i}." for i in range(20)]
answers = await asyncio.gather(*(ask(p) for p in prompts))
print(len(answers), "answers")
asyncio.run(main())
무언가 실패하면 다음을 먼저 확인하세요:
- API_KEY에 대한 KeyError. Python을 실행하는 셸에서 변수가 설정되지 않았습니다. 다시 내보내거나 파일에서 로드하세요.
- 404 또는 연결 오류. 기본 URL에
/v1접미사가 누락되었거나 오타가 있습니다. - 인증 오류. 키에 불필요한 공백이나 줄바꿈이 있거나 잘못된 헤더로 전송하고 있습니다. SDK는
Authorization: Bearer을 자동으로 설정합니다. - 모델을 찾을 수 없음. 모델 ID는 소문자로
uncensored입니다. - 비어 있거나 잘린 응답.
max_tokens을 너무 낮게 설정했습니다. 제거하거나 높여야 합니다.
스크립트 비용
가격은 입력 토큰 100만 개당 $0.15, 출력 토큰 100만 개당 $0.50이며 선불 크레딧에서 구독 없이 청구됩니다. 1,000개의 지원 메시지를 분류하는 스크립트를 가정해 보겠습니다. 각 메시지당 약 500개의 입력 토큰을 보내고 약 200개의 출력 토큰을 받습니다.
- 입력: 1,000 × 500 = 500,000 토큰 × $0.15 / 1M = $0.075.
- 출력: 1,000 × 200 = 200,000 토큰 × $0.50 / 1M = $0.10.
- 합계: $0.175.
실패하거나 거부된 요청에는 요금이 부과되지 않으며, 크레딧은 만료되지 않습니다. 충전 금액은 $20부터 $500까지의 정수 금액이며, 암호화폐(TRC20 기반 USDT, Base 기반 USDC)로 가능합니다. $50 이상 충전 시 5%, $100 이상 시 10%, $200 이상 시 15%의 보너스가 제공됩니다. 프롬프트는 학습에 사용되지 않습니다. 자세한 내용은 요금 페이지을 참조하세요.
