https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grok向 Grok ↗ 发送请求时,将当前使用的 URL 中的 https://api.x.ai/v1 替换为 https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/grok。
向 Grok 发送请求时,请确保具备以下条件:
- 你的 AI Gateway Account ID。
- 你的 AI Gateway 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?"
}
]
}'如果你使用 OpenAI SDK 与 JavaScript,可以这样设置端点:
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);如果你使用 OpenAI SDK 与 Python,可以这样设置端点:
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)如果你使用 Anthropic SDK 与 JavaScript,可以这样设置端点:
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);如果你使用 Anthropic SDK 与 Python,可以这样设置端点:
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 schema 访问 Grok 模型。将请求发送至:
https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1/chat/completions指定:
{
"model": "grok/{model}"
}