Chuyển tới nội dung chính

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

  1. Ở sidebar bên trái, nhấn Serverless Inference.
  2. Mở tab Model Catalog.
  3. Nhấn vào một thẻ model để mở trang chi tiết.
  4. Copy Gateway URLModel 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 statusNguyên nhânCách xử lý
401 UnauthorizedAPI key sai hoặc thiếuKiểm tra định dạng header Authorization: Bearer <key>
402 Payment RequiredSố dư Wallet bằng 0Nạp thêm vào Wallet ở Billing
404 Not FoundKhông nhận ra tên modelĐối chiếu tên model với Model Catalog
429 Too Many RequestsVượt rate limitChờ rồi thử lại, hoặc liên hệ support để nâng hạn mức

Tiếp theo