https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grokGrok ↗ にリクエストを送るときは、現在使っている URL の https://api.x.ai/v1 を https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grok に置き換えます。
Grok にリクエストを送るときは、次を用意します。
- AI Gateway の Account ID
- AI Gateway のゲートウェイ名
- 有効な xAI API トークン
- 使う xAI モデルの名前
curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grok/v1/chat/completions \
--header 'content-type: application/json' \
--header 'Authorization: Bearer {xai_api_token}' \
--data '{
"model": "grok-4",
"messages": [
{
"role": "user",
"content": "What is Cloudflare?"
}
]
}'JavaScript の OpenAI SDK を使っている場合は、次のようにエンドポイントを設定できます。
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "<api key>",
baseURL:
"https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grok",
});
const completion = await openai.chat.completions.create({
model: "grok-4",
messages: [
{
role: "system",
content:
"You are Grok, a chatbot inspired by the Hitchhiker's Guide to the Galaxy.",
},
{
role: "user",
content: "What is the meaning of life, the universe, and everything?",
},
],
});
console.log(completion.choices[0].message);Python の OpenAI SDK を使っている場合は、次のようにエンドポイントを設定できます。
import os
from openai import OpenAI
XAI_API_KEY = os.getenv("XAI_API_KEY")
client = OpenAI(
api_key=XAI_API_KEY,
base_url="https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grok",
)
completion = client.chat.completions.create(
model="grok-4",
messages=[
{"role": "system", "content": "You are Grok, a chatbot inspired by the Hitchhiker's Guide to the Galaxy."},
{"role": "user", "content": "What is the meaning of life, the universe, and everything?"},
],
)
print(completion.choices[0].message)JavaScript の Anthropic SDK を使っている場合は、次のようにエンドポイントを設定できます。
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: "<api key>",
baseURL:
"https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grok",
});
const msg = await anthropic.messages.create({
model: "grok-beta",
max_tokens: 128,
system:
"You are Grok, a chatbot inspired by the Hitchhiker's Guide to the Galaxy.",
messages: [
{
role: "user",
content: "What is the meaning of life, the universe, and everything?",
},
],
});
console.log(msg);Python の Anthropic SDK を使っている場合は、次のようにエンドポイントを設定できます。
import os
from anthropic import Anthropic
XAI_API_KEY = os.getenv("XAI_API_KEY")
client = Anthropic(
api_key=XAI_API_KEY,
base_url="https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grok",
)
message = client.messages.create(
model="grok-beta",
max_tokens=128,
system="You are Grok, a chatbot inspired by the Hitchhiker's Guide to the Galaxy.",
messages=[
{
"role": "user",
"content": "What is the meaning of life, the universe, and everything?",
},
],
)
print(message.content)REST API 経由で、OpenAI API スキーマを使って Grok モデルにもアクセスできます。リクエストの送信先は次のとおりです。
https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1/chat/completions次を指定します。
{
"model": "grok/{model}"
}