Skip to content
Cloudflare Docs
非官方翻译 - 此文档为非官方中文翻译版本,仅供参考。如有疑问请以 英文官方文档 为准。

OpenAI

OpenAI 帮助您使用 ChatGPT 进行构建。

端点

https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai

聊天完成端点

https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai/chat/completions \

响应端点

https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai/responses \

URL 结构

在向 OpenAI 发出请求时,将您当前使用的 URL 中的 https://api.openai.com/v1 替换为 https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai

前提条件

在向 OpenAI 发出请求时,确保您具有以下内容:

  • 您的 AI 网关账户 ID。
  • 您的 AI 网关网关名称。
  • 一个有效的 OpenAI API 令牌。
  • 您要使用的 OpenAI 模型的名称。

聊天完成端点

cURL 示例

Terminal window
curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai/chat/completions \
--header 'Authorization: Bearer {openai_token}' \
--header 'Content-Type: application/json' \
--data '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "What is Cloudflare?"
}
]
}'

JavaScript SDK 示例

import OpenAI from "openai";
const apiKey = "my api key"; // 或 process.env["OPENAI_API_KEY"]
const accountId = "{account_id}";
const gatewayId = "{gateway_id}";
const baseURL = `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/openai`;
const openai = new OpenAI({
apiKey,
baseURL,
});
try {
const model = "gpt-3.5-turbo-0613";
const messages = [{ role: "user", content: "What is a neuron?" }];
const maxTokens = 100;
const chatCompletion = await openai.chat.completions.create({
model,
messages,
max_tokens: maxTokens,
});
const response = chatCompletion.choices[0].message;
console.log(response);
} catch (e) {
console.error(e);
}

OpenAI 响应端点

cURL 示例

Terminal window
curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai/responses \
--header 'Authorization: Bearer {openai_token}' \
--header 'Content-Type: application/json' \
--data '{
"model": "gpt-4.1",
"input": [
{
"role": "user",
"content": "Write a one-sentence bedtime story about a unicorn."
}
]
}'

JavaScript SDK 示例

import OpenAI from "openai";
const apiKey = "my api key"; // 或 process.env["OPENAI_API_KEY"]
const accountId = "{account_id}";
const gatewayId = "{gateway_id}";
const baseURL = `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/openai`;
const openai = new OpenAI({
apiKey,
baseURL,
});
try {
const model = "gpt-4.1";
const input = [
{
role: "user",
content: "Write a one-sentence bedtime story about a unicorn.",
},
];
const response = await openai.responses.create({
model,
input,
});
console.log(response.output_text);
} catch (e) {
console.error(e);
}