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

Vercel AI SDK

Vercel AI SDK 是一个用于构建 AI 应用程序的 TypeScript 库。该 SDK 支持许多不同的 AI 提供商、流式完成工具等等。

要在 AI SDK 内部使用 Cloudflare AI 网关,您可以为大多数支持的提供商配置自定义"网关 URL"。以下是一些工作示例。

示例

OpenAI

如果您在 AI SDK 中使用 openai 提供商,您可以使用 createOpenAI 创建自定义设置,传递您的 OpenAI 兼容 AI 网关 URL:

import { createOpenAI } from "@ai-sdk/openai";
const openai = createOpenAI({
baseURL: `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai`,
});

Anthropic

如果您在 AI SDK 中使用 anthropic 提供商,您可以使用 createAnthropic 创建自定义设置,传递您的 Anthropic 兼容 AI 网关 URL:

import { createAnthropic } from "@ai-sdk/anthropic";
const anthropic = createAnthropic({
baseURL: `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/anthropic`,
});

Google AI Studio

如果您在 AI SDK 中使用 Google AI Studio 提供商,您需要在 Google AI Studio 兼容的 AI 网关 URL 后附加 /v1beta 以避免错误。需要 /v1beta 路径,因为 Google AI Studio 的 API 在其端点结构中包含此内容,而 AI SDK 单独设置模型名称。这确保了与 Google 的 API 版本控制的兼容性。

import { createGoogleGenerativeAI } from "@ai-sdk/google";
const google = createGoogleGenerativeAI({
baseURL: `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/google-ai-studio/v1beta`,
});

从 AI SDK 检索 log id

当调用 SDK 时,您可以从响应标头访问 AI 网关 log id

const result = await generateText({
model: anthropic("claude-3-sonnet-20240229"),
messages: [],
});
console.log(result.response.headers["cf-aig-log-id"]);

其他提供商

对于上面未列出的其他提供商,您可以通过为任何 AI 提供商创建自定义实例并传递您的 AI 网关 URL 来遵循类似的模式。有关查找特定于您的提供商的 AI 网关 URL 的帮助,请参阅支持的提供商页面