[ PROMPT_NODE_23922 ]
AI Gateway 说明文档
[ SKILL_DOCUMENTATION ]
# Cloudflare AI 网关
关于实施 Cloudflare AI 网关的专家指南——这是一个为 AI 模型提供商设计的通用网关,具备分析、缓存、限流和路由功能。
## 何时使用此参考
- 为任何 AI 提供商(OpenAI、Anthropic、Workers AI 等)设置 AI 网关
- 实现缓存、限流或请求重试/回退
- 配置带有 A/B 测试或模型回退的动态路由
- 使用 BYOK 安全管理提供商 API 密钥
- 添加安全功能 (护栏、DLP)
- 通过日志记录和自定义元数据设置可观测性
- 调试 AI 网关请求或优化配置
## 快速开始
**你的设置是什么?**
- **使用 Vercel AI SDK** → 模式 1 (推荐) - 参见 [sdk-integration.md](./sdk-integration.md)
- **使用 OpenAI SDK** → 模式 2 - 参见 [sdk-integration.md](./sdk-integration.md)
- **Cloudflare Worker + Workers AI** → 模式 3 - 参见 [sdk-integration.md](./sdk-integration.md)
- **直接 HTTP (任何语言)** → 模式 4 - 参见 [configuration.md](./configuration.md)
- **框架 (LangChain 等)** → 参见 [sdk-integration.md](./sdk-integration.md)
## 模式 1: Vercel AI SDK (推荐)
使用官方 `ai-gateway-provider` 包的最现代模式,支持自动回退。
typescript
import { createAiGateway } from 'ai-gateway-provider';
import { createOpenAI } from '@ai-sdk/openai';
import { generateText } from 'ai';
const gateway = createAiGateway({
accountId: process.env.CF_ACCOUNT_ID,
gateway: process.env.CF_GATEWAY_ID,
});
const openai = createOpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// 单模型
const { text } = await generateText({
model: gateway(openai('gpt-4o')),
prompt: 'Hello'
});
// 自动回退数组
const { text } = await generateText({
model: gateway([
openai('gpt-4o'), // 首先尝试
anthropic('claude-sonnet-4-5'), // 回退
]),
prompt: 'Hello'
});
**安装:** `npm install ai-gateway-provider ai @ai-sdk/openai @ai-sdk/anthropic`
## 模式 2: OpenAI SDK
OpenAI API 的直接替代方案,支持多提供商。
typescript
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/compat`,
defaultHeaders: {
'cf-aig-authorization': `Bearer ${cfToken}` // 用于已认证的网关
}
});
// 通过更改模型格式切换提供商: {provider}/{model}
const