使用 AI SDK 指定任意模型
开箱即用,Agents SDK 可通过 Responses API 或 Chat Completions API 使用 OpenAI 模型。不过,如果你想使用其他模型,Vercel 的 AI SDK 提供了多种受支持的模型,可通过此适配器引入到 Agents SDK 中。
-
通过安装扩展包来安装 AI SDK 适配器:
Terminal window npm install @openai/agents-extensions -
从 Vercel 的 AI SDK 选择所需的模型包并安装:
Terminal window npm install @ai-sdk/openai -
导入适配器和模型以连接到你的智能体:
import { openai } from '@ai-sdk/openai';import { aisdk } from '@openai/agents-extensions/ai-sdk'; -
初始化一个供智能体使用的模型实例:
const model = aisdk(openai('gpt-5-mini'));
import { Agent, run } from '@openai/agents';
// Import the model package you installedimport { openai } from '@ai-sdk/openai';
// Import the adapterimport { aisdk } from '@openai/agents-extensions';
// Create a model instance to be used by the agentconst model = aisdk(openai('gpt-5-mini'));
// Create an agent with the modelconst agent = new Agent({ name: 'My Agent', instructions: 'You are a helpful assistant.', model,});
// Run the agent with the new modelrun(agent, 'What is the capital of Germany?');传递提供方元数据
Section titled “传递提供方元数据”如果需要随消息发送特定于提供方的选项,可通过 providerMetadata 传递。该值会直接转发给底层 AI SDK 模型。比如,以下在 Agents SDK 中的 providerData
providerData: { anthropic: { cacheControl: { type: 'ephemeral'; } }}在使用 AI SDK 集成时会变为
providerMetadata: { anthropic: { cacheControl: { type: 'ephemeral'; } }}AI SDK UI 流式助手
Section titled “AI SDK UI 流式助手”@openai/agents-extensions/ai-sdk-ui 提供用于将 Agents SDK 流接入 AI SDK UI 路由的响应助手:
createAiSdkTextStreamResponse(source, options?):用于纯文本流式响应。createAiSdkUiMessageStreamResponse(source, options?):用于UIMessageChunk流式响应。
这两个助手均接受 StreamedRunResult、类流式来源或兼容的包装对象,并返回带有适合流式传输的响应头的 Response。
端到端用法请参见本仓库中的 examples/ai-sdk-ui 应用。