SDK 가이드
Python
Python의 공식 openai 패키지에 base_url과 api_key만 지정해 api14를 쓰는 방법입니다. 채팅, 스트리밍, 도구 호출, 구조화된 출력, 이미지, 음성 합성과 인식, 재시도를 다룹니다. 이미지 생성 호출과 타임아웃 설정도 포함합니다.
api14에서 공식 openai Python 패키지를 사용하세요. base_url과 api_key를 설정하고, 아무 모델 ID(예: openai/gpt-5-mini)를 model로 사용합니다.
설치
pip install openai
export API14_API_KEY="sk-api14-..."
설정
from openai import OpenAI
import os
client = OpenAI(
base_url="https://api14.com/api/v1",
api_key=os.environ["API14_API_KEY"],
)
비동기 클라이언트도 있습니다. from openai import AsyncOpenAI는 같은 인수를 받습니다. 웹 서버나 배치 작업처럼 많은 요청을 동시에 보낼 때 사용하세요.
import asyncio
from openai import AsyncOpenAI
aclient = AsyncOpenAI(base_url="https://api14.com/api/v1", api_key=os.environ["API14_API_KEY"])
async def ask(q):
r = await aclient.chat.completions.create(model="openai/gpt-5-mini", messages=[{"role": "user", "content": q}])
return r.choices[0].message.content
async def main():
return await asyncio.gather(*(ask(q) for q in ["What is RAG?", "What is a token?"]))
answers = asyncio.run(main())
동시 요청 수는 요금제의 분당 요청 한도 아래로 유지하세요. 가이드: 배치 처리를 참고하세요.
인수 없이 OpenAI()를 호출하면 OPENAI_BASE_URL과 OPENAI_API_KEY를 읽으므로, 환경 변수만으로 기존 앱이 api14를 가리키게 할 수 있습니다.
export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
채팅
result = client.chat.completions.create(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "Explain vector databases in two sentences."}],
)
print(result.choices[0].message.content)
스트리밍
stream = client.chat.completions.create(
model="anthropic/claude-sonnet-4.5",
messages=[{"role": "user", "content": "Write a haiku about APIs."}],
stream=True,
)
for chunk in stream:
if chunk.choices:
print(chunk.choices[0].delta.content or "", end="")
스트리밍을 참고하세요.
도구 호출
import json
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What's the weather in Istanbul?"}]
while True:
res = client.chat.completions.create(model="openai/gpt-5-mini", messages=messages, tools=tools)
msg = res.choices[0].message
if not msg.tool_calls:
break
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_weather(**args) # 직접 작성한 함수
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
print(msg.content)
도구 호출을 참고하세요.
구조화된 출력
client.chat.completions.parse는 Pydantic 모델을 엄격한 JSON Schema로 변환하고 파싱된 객체를 반환합니다. 최신 openai 릴리스가 필요하며, 이전 1.x 버전에서는 client.beta.chat.completions.parse로 제공됩니다. supported_parameters에 structured_outputs 또는 response_format이 포함된 모델을 사용하세요.
from pydantic import BaseModel
class Person(BaseModel):
name: str
born: int
city: str
res = client.chat.completions.parse(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "Extract: Ada Lovelace, born 1815 in London."}],
response_format=Person,
)
person = res.choices[0].message.parsed # Person(name='Ada Lovelace', born=1815, city='London')
구조화된 출력을 참고하세요.
이미지 입력
import base64
image = base64.b64encode(open("photo.png", "rb").read()).decode()
res = client.chat.completions.create(
model="google/gemini-2.5-flash",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What is in this picture?"},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image}"}},
],
}],
)
공개 https:// URL도 사용할 수 있습니다. 비전 및 파일을 참고하세요.
이미지 생성
result = client.images.generate(
model="openai/gpt-5.4-image-2",
prompt="A minimalist product photo of a ceramic mug on a wooden table",
n=1,
extra_body={"aspect_ratio": "1:1"},
)
open("image.png", "wb").write(base64.b64decode(result.data[0].b64_json))
SDK가 모르는 파라미터(aspect_ratio, provider, models, reasoning)는 extra_body에 넣습니다.
음성 합성 및 음성 인식
audio = client.audio.speech.create(
model="openai/gpt-4o-mini-tts",
input="Hello from api14!",
voice="alloy",
)
audio.write_to_file("speech.mp3")
text = client.audio.transcriptions.create(
model="openai/whisper-1",
file=open("speech.mp3", "rb"),
)
print(text.text)
오류
import openai
try:
client.chat.completions.create(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "Hi"}],
)
except openai.APIStatusError as e:
if e.status_code == 402:
print("Balance too low, add funds:", e.code) # insufficient_balance
elif e.status_code == 429:
print("Retry after", e.response.headers.get("retry-after"), "s:", e.code) # rate_limited
else:
raise
오류를 참고하세요.
타임아웃과 재시도
SDK는 기본적으로 연결 오류, 408, 409, 429, 5xx를 지수 백오프로 두 번 재시도하며 Retry-After를 따릅니다. 기본 타임아웃은 10분입니다. 둘 다 클라이언트에서, 또는 with_options로 호출마다 설정할 수 있습니다.
import httpx
client = OpenAI(
base_url="https://api14.com/api/v1",
api_key=os.environ["API14_API_KEY"],
timeout=httpx.Timeout(60.0, connect=5.0),
max_retries=4,
)
client.with_options(timeout=300, max_retries=0).chat.completions.create(...)
daily_limit_reached나 insufficient_balance는 재시도해도 소용없습니다. 멈추고 알림을 보내세요. 속도 제한을 참고하세요.
모든 기능
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
});
const result = await client.chat.completions.create({
"model": "openai/gpt-5-mini",
"messages": [
{
"role": "user",
"content": "Explain vector databases in two sentences."
}
]
});
console.log(result.choices[0].message.content);