文档
CodeRabbit
Cloudflare
AG Grid
Netlify
Neon
WorkOS
Clerk
Convex
Electric
PowerSync
Sentry
Railway
Prisma
Strapi
Unkey
CodeRabbit
Cloudflare
AG Grid
Netlify
Neon
WorkOS
Clerk
Convex
Electric
PowerSync
Sentry
Railway
Prisma
Strapi
Unkey
类引用
函数引用
接口引用
类型别名引用
变量引用
指南

智能体循环

代理循环是指 LLM 反复调用工具、接收结果并继续推理,直到它可以提供最终答案的模式。这使得复杂的、多步骤的操作成为可能。

mermaid

详细的代理流程

mermaid

多步骤示例

以下是代理循环的一个实际例子

用户:“帮我找到飞往巴黎的低于 500 美元的航班,并预订最便宜的航班”

循环 1:LLM 调用 searchFlights({destination: "Paris", maxPrice: 500})

  • 工具返回:[{id: "F1", price: 450}, {id: "F2", price: 480}]

循环 2:LLM 分析结果并调用 bookFlight({flightId: "F1"})

  • 工具需要批准(敏感操作)
  • 用户批准
  • 工具返回:{bookingId: "B123", confirmed: true}

循环 3:LLM 生成最终响应

  • “我找到了 2 个低于 500 美元的航班。我已经预订了最便宜的航班(航班 F1),价格为 450 美元。您的预订 ID 是 B123。”

代码示例:代理天气助手

typescript
// 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);
}

用户:“今天旧金山应该穿什么?”

智能体循环:

  1. LLM 调用 get_weather({city: "San Francisco"}) → 返回 {temp: 62, conditions: "cloudy"}
  2. LLM 调用 get_clothing_advice({temperature: 62, conditions: "cloudy"}) → 返回 {recommendation: "Light jacket recommended"}
  3. LLM 生成:“旧金山的天气是 62°F 并且多云。我建议穿一件轻夹克。”