Dành cho Lập trình viên & Tham chiếu API
Lập trình ứng dụng với Python & Node.js SDK
Đọc ~6 phút
Sử dụng trực tiếp thư viện OpenAI chính hãng
Bạn không cần cài bất kỳ thư viện tùy chỉnh nào. Hãy dùng thư viện
openai chính thức của Python hoặc npm. Chỉ cần truyền 2 tham số: base_url="https://apistudio.kandes.shop/v1" và api_key="ks-...".1
Streaming phản hồi theo thời gian thực (Server-Sent Events)
Tốc độ caoHiển thị từng ký tự phản hồi ra màn hình giúp người dùng không phải chờ đợi.
from openai import OpenAI
client = OpenAI(
api_key="ks-your-api-key",
base_url="https://apistudio.kandes.shop/v1",
)
stream = client.chat.completions.create(
model="claude-3-7-sonnet",
messages=[{"role": "user", "content": "Viết bài thơ về mùa thu Hà Nội"}],
stream=True,
)
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)2
Cơ chế Bắt lỗi & Tự động Retry (Error Handling)
Chuẩn ProductionXử lý lỗi mạng và lỗi chạm hạn mức một cách bài bản.
from openai import OpenAI, APIError, RateLimitError, AuthenticationError
client = OpenAI(
api_key="ks-your-api-key",
base_url="https://apistudio.kandes.shop/v1",
max_retries=2, # Tự động retry với lỗi 500/502/503
)
try:
response = client.chat.completions.create(
model="claude-3-7-sonnet",
messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)
except AuthenticationError:
print("Lỗi 401: Khóa API không đúng hoặc đã bị xóa.")
except RateLimitError:
print("Lỗi 429: Khóa chạm hạn mức ngày hoặc vượt tần suất gọi.")
except APIError as e:
if e.status_code == 402:
print("Lỗi 402: Số dư ví Kandes không đủ. Hãy nạp thêm tiền!")
else:
print(f"Lỗi API ({e.status_code}): {e.message}")