Agent Loop

Agent Loop 是 Agent 的核心执行循环:调用 LLM → 处理响应 → 执行工具 → 结果回传 → 继续调用 LLM,直到任务完成或触发停止条件。

#type / concept #status / evergreen #tech / ai #tech / architecture

[!info] related notes

Agent Loop

一句话定义

Agent Loop 是 Agent 的核心执行循环:调用 LLM → 检查是否有 tool_call → 执行工具 → 结果回传 LLM → 继续推理,直到 LLM 输出最终回答或触发停止条件。

核心原理

最小 Agent Loop

async def agent_loop(messages: list, tools: list, llm) -> str:
    for step in range(MAX_STEPS):
        # 1. 调用 LLM
        response = await llm.chat(messages, tools=tools)

        # 2. 检查是否有 tool_call
        if not response.tool_calls:
            # 没有 tool_call,LLM 直接回复
            return response.content

        # 3. 执行每个 tool_call
        for tool_call in response.tool_calls:
            result = await execute_tool(tool_call)
            messages.append(tool_call_message(tool_call, result))

    return "达到最大步数"

带事件流的 Agent Loop

async def agent_loop_with_events(context: Context) -> AsyncIterator[Event]:
    messages = build_messages(context)

    for step in range(MAX_STEPS):
        response = await llm.chat(messages, tools=tools)

        if response.tool_calls:
            for tool_call in response.tool_calls:
                yield ToolCallStartEvent(tool_call)
                result = await execute_tool(tool_call)
                yield ToolCallResultEvent(tool_call, result)
                messages.append(tool_result_message(tool_call, result))
        else:
            yield TextDeltaEvent(response.content)
            break

    yield DoneEvent()

停止条件

条件说明
LLM 无 tool_call模型决定直接回复
达到 max_steps防止无限循环
工具执行失败某步失败需要降级
用户取消前端中断
超时整体时间超限

常见坑

  1. 不做 max_steps 限制: Agent 可能无限循环
  2. 不处理 tool_call 为空的情况: LLM 可能输出空的 tool_calls
  3. 不检查停止条件: 每步都应该检查是否应该停止
  4. 消息累积不控制: 每步都追加消息,上下文越来越大

参考资料

创建于 2026/6/30 更新于 2026/7/15