Inference API を呼び出す
serverless gateway は標準の /v1/chat/completions endpoint を提供します。この API 形式に対応した HTTP client であれば、変更なしでそのまま利用できます。
開始前に次のものを用意してください。
- serverless API key — API key を作成する を参照
- Model Catalog で確認した gateway URL と model 名
gateway URL と model 名を確認する
- 左サイドバーで Serverless Inference をクリックします。
- Model Catalog タブをクリックします。
- model カードをクリックして詳細ビューを開きます。
- Gateway URL と 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 はそのまま利用できます。base_url に serverless gateway、api_key に serverless key を設定するだけです。
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
"stream": true を追加すると、生成された token を逐次受け取れます。gateway は 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)
よくあるエラー
| HTTP ステータス | 原因 | 対処 |
|---|---|---|
401 Unauthorized | API key が無効、または未指定 | Authorization ヘッダーの形式 Bearer <key> を確認します |
402 Payment Required | Wallet の残高が 0 | Billing で Wallet にチャージします |
404 Not Found | model 名が認識されない | Model Catalog で model 名を確認します |
429 Too Many Requests | rate limit を超過 | 時間をおいて再試行するか、support に上限の引き上げを依頼します |
次のステップ
- Usage & Billing を確認する — request ごとの token 使用量とコストを確認します。