Gọi Inference API
Serverless gateway cung cấp endpoint chuẩn /v1/chat/completions. Mọi HTTP client hỗ trợ định dạng API này đều dùng được mà không cần sửa gì.
Trước khi bắt đầu, bạn cần:
- Một serverless API key — xem Tạo API key
- URL gateway và tên model lấy từ Model Catalog
Lấy URL gateway và tên model
- Ở sidebar bên trái, nhấn Serverless Inference.
- Mở tab Model Catalog.
- Nhấn vào một thẻ model để mở trang chi tiết.
- Copy Gateway URL và Model name.
curl
curl https://<serverless-gateway-domain>/v1/chat/completions \
-H "Authorization: Bearer <your-api-key>" \
-H "Content-Type: application/json" \
-d '{
"model": "<model-name>",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
"max_tokens": 256
}'
Python (requests)
import requests
response = requests.post(
"https://<serverless-gateway-domain>/v1/chat/completions",
headers={
"Authorization": "Bearer <your-api-key>",
"Content-Type": "application/json",
},
json={
"model": "<model-name>",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
"max_tokens": 256,
},
)
print(response.json()["choices"][0]["message"]["content"])
OpenAI SDK (Python)
OpenAI SDK dùng được trực tiếp — chỉ cần đặt base_url trỏ tới serverless gateway và api_key là serverless key của bạn.
from openai import OpenAI
client = OpenAI(
base_url="https://<serverless-gateway-domain>/v1",
api_key="<your-api-key>",
)
response = client.chat.completions.create(
model="<model-name>",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
max_tokens=256,
)
print(response.choices[0].message.content)
Streaming
Thêm "stream": true để nhận token ngay khi model sinh ra. Gateway trả về Server-Sent Events (SSE).
from openai import OpenAI
client = OpenAI(
base_url="https://<serverless-gateway-domain>/v1",
api_key="<your-api-key>",
)
with client.chat.completions.stream(
model="<model-name>",
messages=[{"role": "user", "content": "Tell me a short story."}],
max_tokens=512,
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Lỗi thường gặp
| HTTP status | Nguyên nhân | Cách xử lý |
|---|---|---|
401 Unauthorized | API key sai hoặc thiếu | Kiểm tra định dạng header Authorization: Bearer <key> |
402 Payment Required | Số dư Wallet bằng 0 | Nạp thêm vào Wallet ở Billing |
404 Not Found | Không nhận ra tên model | Đối chiếu tên model với Model Catalog |
429 Too Many Requests | Vượt rate limit | Chờ rồi thử lại, hoặc liên hệ support để nâng hạn mức |
Tiếp theo
- Theo dõi Usage & Billing — xem lượng token và chi phí theo từng request.