[ PROMPT_NODE_23930 ]
SDK 集成
[ SKILL_DOCUMENTATION ]
# AI Gateway SDK 集成
## Vercel AI SDK (推荐)
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,
apiKey: process.env.CF_API_TOKEN // 认证网关可选
});
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'),
openai('gpt-4o-mini')
]),
prompt: 'Complex task'
});
### 选项
typescript
model: gateway(openai('gpt-4o'), {
cacheKey: 'my-key',
cacheTtl: 3600,
metadata: { userId: 'u123', team: 'eng' }, // 最多 5 个条目
retries: { maxAttempts: 3, backoff: 'exponential' }
})
## OpenAI SDK
typescript
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/openai`,
defaultHeaders: { 'cf-aig-authorization': `Bearer ${cfToken}` }
});
// 统一 API - 通过模型名称切换提供商
model: 'openai/gpt-4o' // 或 'anthropic/claude-sonnet-4-5'
## Anthropic SDK
typescript
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/anthropic`,
defaultHeaders: { 'cf-aig-authorization': `Bearer ${cfToken}` }
});
## Workers AI 绑定
toml
# wrangler.toml
[ai]
binding = "AI"
[[ai.gateway]]
id = "my-gateway"
typescript
await env.AI.run('@cf/meta/llama-3-8b-instruct',
{ messages: [...] },
{ gateway: { id: 'my-gateway', metadata: { userId: '123' } } }
);
## LangChain / LlamaIndex
typescript
// 使用带有自定义 baseURL 的 OpenAI SDK 模式
new ChatOpenAI({
configuration: {
baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/openai`
}
});
## HTTP / cURL
bash
curl https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/openai/chat/completions
-H "Authorization: Bearer $OPENAI_KEY"
-H "cf-aig-authorization: Bearer $CF_TOKEN"
-H "cf-aig-metadata: {"userId":"123"}"
-d '{"model":"gpt-4o","messages":[...]}'
## 请求头参考
| 请求头 | 目的 |
|--------|---------|
| `cf-ai