代理循环是指 LLM 反复调用工具、接收结果并继续推理,直到它可以提供最终答案的模式。这使得复杂的、多步骤的操作成为可能。
以下是代理循环的一个实际例子
用户:“帮我找到飞往巴黎的低于 500 美元的航班,并预订最便宜的航班”
循环 1:LLM 调用 searchFlights({destination: "Paris", maxPrice: 500})
循环 2:LLM 分析结果并调用 bookFlight({flightId: "F1"})
循环 3:LLM 生成最终响应
// Tool definitions
const getWeatherDef = toolDefinition({
name: "get_weather",
description: "Get current weather for a city",
inputSchema: z.object({
city: z.string(),
}),
});
const getClothingAdviceDef = toolDefinition({
name: "get_clothing_advice",
description: "Get clothing recommendations based on weather",
inputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
}),
});
// Server implementations
const getWeather = getWeatherDef.server(async ({ city }) => {
const response = await fetch(`https://api.weather.com/v1/${city}`);
return await response.json();
});
const getClothingAdvice = getClothingAdviceDef.server(async ({ temperature, conditions }) => {
// Business logic for clothing recommendations
if (temperature < 50) {
return { recommendation: "Wear a warm jacket" };
}
return { recommendation: "Light clothing is fine" };
});
// Server route
export async function POST(request: Request) {
const { messages } = await request.json();
const stream = chat({
adapter: openaiText("gpt-5.2"),
messages,
tools: [getWeather, getClothingAdvice],
});
return toServerSentEventsResponse(stream);
}
用户:“今天旧金山应该穿什么?”
智能体循环: