🔧 调用选项(Call Options)
调用选项允许在运行时传递类型安全的输入来动态配置 Agent 行为。
基础示例
typescript
import { ToolLoopAgent } from 'ai';
import { z } from 'zod';
const supportAgent = new ToolLoopAgent({
model: "anthropic/claude-sonnet-4.5",
callOptionsSchema: z.object({
userId: z.string(),
accountType: z.enum(['free', 'pro', 'enterprise']),
}),
instructions: 'You are a helpful customer support agent.',
prepareCall: ({ options, ...settings }) => ({
...settings,
instructions: settings.instructions + `
User context:
- Account type: ${options.accountType}
- User ID: ${options.userId}
Adjust your response based on the user's account level.`,
}),
});
const result = await supportAgent.generate({
prompt: 'How do I upgrade my account?',
options: {
userId: 'user_123',
accountType: 'free',
},
});动态模型选择
typescript
const agent = new ToolLoopAgent({
model: "anthropic/claude-sonnet-4.5",
callOptionsSchema: z.object({
complexity: z.enum(['simple', 'complex']),
}),
prepareCall: ({ options, ...settings }) => ({
...settings,
model: options.complexity === 'simple'
? 'openai/gpt-4o-mini'
: 'openai/o1-mini',
}),
});
await agent.generate({
prompt: 'What is 2+2?',
options: { complexity: 'simple' },
});RAG 集成
typescript
const ragAgent = new ToolLoopAgent({
model: "anthropic/claude-sonnet-4.5",
callOptionsSchema: z.object({
query: z.string(),
}),
prepareCall: async ({ options, ...settings }) => {
const documents = await vectorSearch(options.query);
return {
...settings,
instructions: `Answer questions using the following context:
${documents.map(doc => doc.content).join('\n\n')}`,
};
},
});
await ragAgent.generate({
prompt: 'What is our refund policy?',
options: { query: 'refund policy' },
});在 API 路由中使用
typescript
import { createAgentUIStreamResponse } from 'ai';
import { myAgent } from '@/ai/agents/my-agent';
export async function POST(request: Request) {
const { messages, userId, accountType } = await request.json();
return createAgentUIStreamResponse({
agent: myAgent,
messages,
options: {
userId,
accountType,
},
});
}