メインコンテンツまでスキップ

Inference API を呼び出す

serverless gateway は標準の /v1/chat/completions endpoint を提供します。この API 形式に対応した HTTP client であれば、変更なしでそのまま利用できます。

開始前に次のものを用意してください。


gateway URL と model 名を確認する

  1. 左サイドバーで Serverless Inference をクリックします。
  2. Model Catalog タブをクリックします。
  3. model カードをクリックして詳細ビューを開きます。
  4. 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 はそのまま利用できます。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 UnauthorizedAPI key が無効、または未指定Authorization ヘッダーの形式 Bearer <key> を確認します
402 Payment RequiredWallet の残高が 0Billing で Wallet にチャージします
404 Not Foundmodel 名が認識されないModel Catalog で model 名を確認します
429 Too Many Requestsrate limit を超過時間をおいて再試行するか、support に上限の引き上げを依頼します

次のステップ