AI SDK Gateway Provider 完全指南:用统一网关接入多厂商大模型
2026/9/12 21:33:01 网站建设 项目流程

AI SDK Gateway Provider 完全指南:用统一网关接入多厂商大模型

【免费下载链接】aiThe AI Toolkit for TypeScript. From the creators of Next.js, the AI SDK is a free open-source library for building AI-powered applications and agents项目地址: https://gitcode.com/GitHub_Trending/ai/ai

AI SDK 的 Gateway Provider(@ai-sdk/gateway)是一个托管式统一网关,允许通过单一 Provider 实例、以统一的模型 ID 约定(如xai/grok-4.6anthropic/claude-sonnet-5openai/gpt-5.2)访问 OpenAI、Anthropic、Google、DeepSeek、xAI 等数十家厂商的模型,并附带智能路由、成本追踪、批量任务、实时语音等能力。读完本文,你将掌握 Gateway Provider 的安装、认证配置、Provider 实例构建、全部模型能力接口、网关级路由选项、内置搜索工具以及错误处理体系,可直接在 AI SDK 项目中落地使用。

Gateway Provider 在 AI SDK 中的定位

AI SDK(The AI Toolkit for TypeScript)本身是框架无关的 LLM 应用构建库,而 Provider 层负责把各家模型的私有 API 协议统一成标准接口。@ai-sdk/gateway包(当前仓库版本为 4.0.78,见 packages/gateway/package.json)实现的则是"网关型" Provider:它不直连某一家厂商,而是把请求发送到托管网关https://ai-gateway.vercel.sh/v4/ai(默认 baseURL,源码见 gateway-provider.ts),由网关侧完成模型路由、凭据管理、限流与用量统计。

这意味着使用体验与普通 Provider 完全一致——你只需要一个 API Key,就能在代码里同时切换 Grok、Claude、GPT、Gemini 等模型,而无需为每家厂商单独申请凭据、单独初始化实例。该包依赖@ai-sdk/provider@ai-sdk/provider-utils(工作区内部依赖),并内置了@vercel/oidc以支持 Vercel 部署环境下的无密钥认证。

安装与最小可用示例

安装

Gateway Provider 发布在@ai-sdk/gateway模块下,与ai核心包配合使用:

npm i @ai-sdk/gateway

仓库包声明要求 Node.js >= 22(见 package.json),且将zod声明为 peer dependency(^3.25.76 || ^4.1.8),主包会一并安装。

最小示例

import { gateway } from '@ai-sdk/gateway'; import { generateText } from 'ai'; const { text } = await generateText({ model: gateway('xai/grok-4.6'), prompt: 'Tell me about the history of the San Francisco Mission-style burrito.', });

调用前需配置 API Key(见下节"认证方式")。gateway('xai/grok-4.6')返回一个标准的LanguageModelV4实例,因此可以无缝用于generateTextstreamTextgenerateObject以及useChat/useAssistant等 AI SDK 核心 API。

为 Coding Agent 安装技能

如果你使用 Claude Code、Cursor 等编码 Agent,可以把 AI SDK 技能添加到仓库,让 Agent 在写代码时自动遵循 SDK 的最佳实践:

npx skills add vercel/ai

认证方式:API Key 与 OIDC 自动降级

getGatewayAuthToken的认证解析逻辑(源码见 gateway-provider.ts)遵循以下优先级:

  1. 显式传入的apiKey:通过createGateway({ apiKey })提供;
  2. 环境变量AI_GATEWAY_API_KEY:未显式传入时自动读取;
  3. OIDC 令牌:两者都缺失时,在 Vercel 部署环境中通过@vercel/oidc获取 OIDC 访问令牌(getVercelOidcToken,见 vercel-environment.ts),实现无密钥部署。

认证信息最终通过请求头发送:

Authorization: Bearer <token> ai-gateway-auth-method: api-key | oidc ai-gateway-protocol-version: 0.0.1 x-vercel-ai-gateway-team: <teamIdOrSlug> # 配置了 teamIdOrSlug 时

其中ai-gateway-auth-method头由常量GATEWAY_AUTH_METHOD_HEADER定义(见 gateway-headers.ts)。若认证信息缺失,会抛出GatewayAuthenticationError(401)。

最典型的本地开发配置方式:

export AI_GATEWAY_API_KEY="your-gateway-api-key"

构建 Provider 实例:createGateway 与默认实例

包入口(src/index.ts)同时导出默认实例gateway工厂函数createGatewaycreateGatewayProvider为兼容旧名的别名):

import { gateway, createGateway } from '@ai-sdk/gateway'; // 方式一:直接用默认实例(读取环境变量 AI_GATEWAY_API_KEY) const text = await generateText({ model: gateway('openai/gpt-5.2'), prompt: 'hi' }); // 方式二:按需定制配置 const gw = createGateway({ apiKey: 'sk-...', teamIdOrSlug: 'my-team', });

GatewayProviderSettings完整配置项如下(定义见 gateway-provider.ts):

配置项类型默认值说明
baseURLstringhttps://ai-gateway.vercel.sh/v4/aiAPI 请求基础地址,可指向自托管网关
apiKeystringAI_GATEWAY_API_KEY环境变量通过Authorization头发送的网关密钥或 Vercel Access Token
teamIdOrSlugstring多团队访问令牌的团队 ID 或 slug,通过x-vercel-ai-gateway-team头传递
headersRecord<string, string>附加到每次请求的自定义头
fetchFetchFunction全局 fetch自定义 fetch 实现,可用于拦截请求或测试
webSocketWebSocketConstructor全局 WebSocket流式转录使用的自定义 WebSocket 实现
metadataCacheRefreshMillisnumber5 * 60 * 1000模型元数据缓存刷新间隔(毫秒)

其中metadataCacheRefreshMillis控制getAvailableModels()结果的缓存时长,源码中默认值为 5 分钟(见 gateway-provider.ts),_internal.currentDate仅供测试注入时间源。

支持的模型能力矩阵

GatewayProvider实现了 ProviderV4 规范,模型 ID 采用厂商/模型约定,语言模型 ID 全集定义在 gateway-language-model-settings.ts(例如alibaba/qwen3-maxanthropic/claude-opus-5deepseek/deepseek-v4-progoogle/gemini-3-pro-imageopenai/gpt-5.2spacexai/grok-4.6zai/glm-5.2等;GatewayModelId类型还带有(string & {})逃生舱,允许传入网关侧新上线的模型 ID)。除文本对话外,同一 Provider 还暴露了多种模态与高级能力(方法定义见 gateway-provider.ts):

能力调用方式返回类型
文本生成gateway(modelId)gateway.chat(id)gateway.languageModel(id)LanguageModelV4
Embeddinggateway.embedding(id)gateway.embeddingModel(id)EmbeddingModelV4
图像生成gateway.image(id)gateway.imageModel(id)ImageModelV4
视频生成gateway.video(id)gateway.videoModel(id)Experimental_VideoModelV4
重排序gateway.reranking(id)gateway.rerankingModel(id)RerankingModelV4
语音合成gateway.speech(id)gateway.speechModel(id)SpeechModelV4
语音转写gateway.transcription(id)gateway.transcriptionModel(id)TranscriptionModelV4
实时对话(实验)gateway.experimental_realtime(id)RealtimeFactoryV4
流式转录(实验)gateway.experimental_transcription(id)TranscriptionModelV4+getToken
批量任务(实验)gateway.experimental_batch()BatchV4<{ text: GatewayModelId }>

例如同时使用文本与图像模型:

import { gateway } from '@ai-sdk/gateway'; import { generateText, generateImage } from 'ai'; // 文本 const { text } = await generateText({ model: gateway('anthropic/claude-sonnet-5'), prompt: 'Explain quantum entanglement simply.', }); // 图像 const { image } = await generateImage({ model: gateway('google/gemini-3.1-flash-image'), prompt: 'A watercolor of a Mission-style burrito.', });

批量任务与幂等控制

gateway.experimental_batch()提供异步批处理能力:通过POST {baseURL}/batch/start提交一批文本生成请求,返回网关侧 job id,状态与结果均回查该 job(实现见 gateway-batch.ts)。批处理支持idempotencyKey幂等键——使用相同键重试不会创建重复批次,并支持webhookUrl回调通知。

Realtime 与流式转录的短期令牌机制

experimental_realtimeexperimental_transcription都提供了getToken()方法:在服务端用网关长期凭据向/v1/realtime/client-secrets换取短期客户端密钥(vcst_前缀),浏览器只持有该短期令牌即可建立 WebSocket 连接,网关凭据永远不会暴露给客户端。源码中通过assertGatewayClientSecretServerEnvironment强制该操作仅可在服务端执行(见 gateway-provider.ts)。令牌有效期默认 60 秒,最长 300 秒(expiresAfterSeconds)。

网关级路由与 Provider Options

请求层面,GatewayProviderOptions(定义见 gateway-provider-options.ts)通过 AI SDK 的providerOptions通道把网关侧的路由策略传给服务端,常见用法:

import { gateway } from '@ai-sdk/gateway'; import { generateText } from 'ai'; const { text } = await generateText({ model: gateway('anthropic/claude-sonnet-5'), prompt: 'Write a haiku about Tokyo.', providerOptions: { gateway: { only: ['anthropic', 'openai'], // 只允许这两个厂商 order: ['anthropic', 'openai'], // 按此顺序尝试 models: ['anthropic/claude-sonnet-5', 'openai/gpt-5.2'], // 回退模型 sort: 'cost', // 按成本/吞吐/首字延迟排序: 'cost' | 'tps' | 'ttft' serviceTier: 'flex', // 'flex' | 'priority' caching: 'auto', // 自动缓存 disallowPromptTraining: true, // 禁止使用提示词训练 zeroDataRetention: true, // 仅使用零数据保留协议厂商 has: ['vision'], // 要求模型具备视觉/隐式缓存能力 tags: ['prod'], // 用量标签 user: 'user-123', // 终端用户标识 quotaEntityId: 'org-1', // 配额实体 byok: { anthropic: [...] }, // 请求级 BYOK 凭据 providerTimeouts: { byok: { anthropic: 3000 } }, // 单厂商超时(ms) }, }, });

关键选项速查:

选项类型作用
only/order/modelsstring[]分别限定可用厂商、厂商尝试顺序、回退模型列表
sort'cost' \| 'tps' \| 'ttft'路由前按成本、每秒 token 数或首 token 延迟排序
serviceTier'flex' \| 'priority'统一服务层级意图
caching'auto'启用网关侧自动缓存
disallowPromptTrainingboolean过滤不训练提示词的厂商
zeroDataRetentionboolean过滤签署零数据保留协议的厂商
hasArray<'implicit-caching' \| 'vision'>限制为具备指定能力的模型
idempotencyKeystring批处理幂等键
tags/user/quotaEntityIdstring[] \| string用量标签、终端用户标识、配额实体

网关内置搜索工具

gateway.tools暴露了四个由网关服务端执行的搜索工具(见 gateway-tools.ts):

  • exaSearch:基于 Exa 的网页搜索,返回面向 Agent 工作流优化的 token 高效摘录,支持类型、领域、日期、位置等过滤;
  • parallelSearch:基于 Parallel AI 的搜索 API,接受自然语言目标,单次调用即可替代多次关键词搜索,支持深度与广度的权衡;
  • perplexitySearch:基于 Perplexity 的实时信息、新闻、论文检索,提供带排序的结果与领域、语言、日期范围过滤;
  • takoSearch:在网页与 Tako 知识图谱中联合搜索,返回结构化数据结果与可视化信息。

这些工具可直接作为 AI SDK 的 tool 传给generateText/streamTexttools字段,例如:

import { gateway } from '@ai-sdk/gateway'; import { generateText } from 'ai'; const { text } = await generateText({ model: gateway('openai/gpt-5.2'), tools: { search: gateway.tools.perplexitySearch }, prompt: 'Search for the latest Vercel AI Gateway pricing.', });

成本、用量与可观测性

元数据与账户查询

Provider 实例提供四个查询方法(实现见 gateway-fetch-metadata.ts 与 gateway-spend-report.ts):

const gw = createGateway({ apiKey: process.env.AI_GATEWAY_API_KEY }); // 1. 网关可用模型列表(含定价信息,结果缓存 5 分钟) const { models } = await gw.getAvailableModels(); // 2. 账户余额(remaining balance / totalUsed) const credits = await gw.getCredits(); // 3. 消费报表(按天/用户/模型/标签/厂商/凭据类型聚合) const report = await gw.getSpendReport({ startDate: '2026-09-01', endDate: '2026-09-11', groupBy: 'model', }); // 4. 单次生成的明细(成本、token、延迟、厂商) const info = await gw.getGenerationInfo({ id: 'gen_xxx' });

getSpendReport的聚合维度支持day | user | model | tag | provider | credential_type,并可组合userIdmodelprovidercredentialTypebyok | system)、tags过滤;结果行包含totalCostmarketCostinputTokensoutputTokenscachedInputTokenscacheCreationInputTokensreasoningTokensrequestCount等字段。

Vercel 可观测性头

当部署在 Vercel 上时,Provider 会自动读取VERCEL_DEPLOYMENT_IDVERCEL_ENVVERCEL_REGIONVERCEL_PROJECT_ID环境变量(见 gateway-provider.ts),并为每次请求附加ai-o11y-deployment-idai-o11y-environmentai-o11y-regionai-o11y-request-idai-o11y-project-id头,使网关侧可以按部署维度追踪流量(请求 ID 来自x-vercel-id,见 vercel-environment.ts)。

错误处理体系

包内建了完整的错误类型体系(导出见 src/index.ts,类型定义在 src/errors/ 目录):

错误类型语义
GatewayAuthenticationError认证失败 / 凭据缺失(401)
GatewayForbiddenError无权限访问(403)
GatewayNotFoundError资源不存在(404)
GatewayModelNotFoundError指定模型 ID 不存在
GatewayInvalidRequestError请求参数非法(400)
GatewayRateLimitError触发限流
GatewayTimeoutError请求超时
GatewayFailedDependencyError上游依赖失败
GatewayInternalServerError网关服务端错误(500)
GatewayResponseError通用响应错误
GatewayError所有网关错误的基础类型

所有 API 调用(生成、批处理、元数据、消费报表等)在捕获底层错误后都会通过asGatewayError归一化并携带认证方式信息抛出(见 errors/as-gateway-error.ts),因此调用方可以统一捕获处理:

import { GatewayRateLimitError, GatewayModelNotFoundError } from '@ai-sdk/gateway'; try { await generateText({ model: gateway('unknown/vendor-model'), prompt: 'hi' }); } catch (error) { if (error instanceof GatewayModelNotFoundError) { // 处理模型不存在 } else if (error instanceof GatewayRateLimitError) { // 退避重试 } }

总结

@ai-sdk/gateway把 AI SDK 的多厂商接入收敛到一条网关链路:一个createGateway()实例即可覆盖文本、图像、视频、语音、Embedding、重排序、实时对话与批量任务,配合only/order/models/sort等路由选项实现模型回退与成本优化,借助getCredits/getSpendReport/getGenerationInfo完成用量与成本核算,并通过层次化的GatewayError体系保证错误可诊断。若需更深入地了解其实现,可继续阅读 gateway-provider.ts(Provider 工厂与认证)、gateway-language-model.ts(文本模型调用与流式)、gateway-batch.ts(批处理)以及 src/errors/(错误归一化)等源码文件,或参考同一仓库下其他 Provider 包(如 packages/openai、packages/anthropic)对比其接入模式。

【免费下载链接】aiThe AI Toolkit for TypeScript. From the creators of Next.js, the AI SDK is a free open-source library for building AI-powered applications and agents项目地址: https://gitcode.com/GitHub_Trending/ai/ai

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询