跳转到内容

恢复那些已停止工作的代理(agents)。

在 ADK 中得到支持。Python v1.16.0Kotlin v0.1.0

ADK代理的执行可能会因多种因素而中断,例如网络连接中断、电源故障,或所需的外部系统离线等。ADK的“恢复”(Resume)功能允许代理工作流程从中断的地方继续执行,从而无需重新启动整个工作流程。在ADK Python 1.16及更高版本中,你可以配置工作流程使其具备恢复能力:系统会记录工作流程的执行进度,并在发生意外中断后允许你重新启动该流程。

本指南介绍了如何配置您的 ADK 代理工作流程,使其能够被重新启动(即在中断后继续执行)。 如果您使用的是自定义代理(Custom Agents),您可以对其进行更新,使其具备重新启动的功能。有关更多信息,请参阅…… 将简历添加到自定义代理(Custom Agents)中。.

添加可恢复的配置(即:即使配置过程中出现错误,系统也能尝试恢复到之前的配置状态)。

要通过为 ADK 工作流的 `App` 对象应用“可恢复性”(Resumability)配置来启用代理工作流的“恢复”(Resume)功能,请参考以下代码示例:

app = App(
    name='my_resumable_agent',
    root_agent=root_agent,
    # Set the resumability config to enable resumability.
    resumability_config=ResumabilityConfig(
        is_resumable=True,
    ),
)
val runner =
    InMemoryRunner(
        app =
            App(
                appName = "my_resumable_agent",
                rootAgent = rootAgent,
                resumabilityConfig = ResumabilityConfig(isResumable = true),
            ),
        sessionService = InMemorySessionService(),
    )

注意:长时间运行的函数、确认操作以及身份验证过程可能会影响系统的性能。请确保这些操作在必要时才执行。

适用于使用该功能的代理(agents)。 长时间运行的函数(Long Running Functions), 确认信息(Confirmations),或 身份验证(Authentication) 由于需要用户输入信息,因此添加了“可恢复的确认机制”(即用户可以在稍后重新确认操作),这改变了这些功能的运作方式。有关更多详细信息,请参阅这些功能的官方文档。

注意:自定义代理(Custom Agents)

默认情况下,自定义代理(Custom Agents)不支持“恢复会话”(Resume)功能。您必须更新代理代码,才能使自定义代理支持该功能。有关如何修改自定义代理以支持“恢复会话”功能的信息,请参阅…… 将简历添加到自定义代理(Custom Agents)中。.

恢复已停止的工作流程

当 ADK 工作流停止执行时,您可以使用包含该工作流实例调用 ID(Invocation ID)的命令来恢复其执行。该调用 ID 可以在工作流的配置信息中找到。 事件 工作流程的历史记录。请确保 ADK API 服务器正在运行(以防其被中断或关闭),然后运行以下命令以恢复工作流程。具体操作方法请参考下面的 API 请求示例。

# restart the API server if needed:
adk api_server my_resumable_agent/

# resume the agent:
curl -X POST http://localhost:8000/run_sse \
 -H "Content-Type: application/json" \
 -d '{
   "app_name": "my_resumable_agent",
   "user_id": "u_123",
   "session_id": "s_abc",
   "invocation_id": "invocation-123"
 }'

您也可以使用 `Runner` 对象的 `RunAsync` 方法来恢复工作流程,如下所示:

async for event in runner.run_async(user_id='u_123', session_id='s_abc',
    invocation_id='invocation-123'):
  print(event)

# When new_message is set to a function response,
# we are trying to resume a long running function.
fun resumeAgent(runner: InMemoryRunner) =
    runBlocking {
        runner
            .runAsync(
                userId = "user123",
                sessionId = "session456",
                invocationId = "previous-invocation-id",
            ).collect { event ->
                // resume execution from previous state
            }
    }

注意:

目前不支持通过 ADK Web 用户界面或 ADK 命令行(CLI)工具来恢复工作流程。

它是如何工作的?

“简历”功能的工作原理是记录代理(Agent)完成的工作流程任务,其中包括所有详细的步骤(包括那些逐步完成的步骤)。 事件 和 事件操作(Event Actions)跟踪代理任务在可恢复工作流中的完成情况。如果工作流被中断后再次启动,系统会通过设置每个代理的完成状态来恢复该工作流。如果某个代理尚未完成任务,系统会重新执行该代理已完成的操作,并从部分完成的状态继续执行工作流。对于多代理工作流,具体的恢复行为会根据工作流中使用的多代理类而有所不同(具体细节如下所述)。

  • 顺序执行代理(Sequential Agent):从保存的状态中读取 `current_sub_agent`,以确定接下来应该运行的子代理(sub-agent)。
  • Loop Agent使用 `current_sub_agent` 和 `times_looped` 的值,从上一次完成迭代后的状态继续执行循环(即从上次使用的子代理(sub-agent)的状态开始继续执行循环)。
  • 并行代理(Parallel Agent):用于确定哪些子代理已经完成了任务;仅执行那些尚未完成任务的子代理。

事件日志记录包括那些成功返回结果的工具所产生的数据。 例如,如果某个代理程序成功执行了功能工具 A 和 B,但在执行工具 C 时出现了故障,系统会重新显示工具 A 和 B 的执行结果,并通过重新发起工具 C 的请求来继续执行工作流程。

注意:工具的执行行为可能会对系统产生某些影响(例如:增加系统负载、消耗系统资源等)。在使用该工具之前,请确保您了解其可能的副作用,并根据实际情况做出相应的决策。

当使用 Tools 恢复工作流程时,“Resume”(恢复)功能会确保代理(agent)中配置的所有 Tools 都能够被正确执行。 至少一次在恢复工作流程时,某个任务可能会被多次执行。如果您的代理使用了某些工具(在这些工具中,重复执行可能会产生负面影响,例如导致不必要的购买行为),那么您应该修改这些工具,以便它们能够检测并防止重复执行。

注意:不支持使用 “Resume” 功能来修改工作流(Workflow)。

在恢复已停止的代理工作流之前,请勿对其进行任何修改。例如,不允许向已停止的工作流中添加或删除代理,之后再继续执行该工作流。

将简历添加到自定义代理(Custom Agents)中。

自定义代理(Custom Agents)需要满足特定的实现要求,才能支持流程的“可恢复性”(即流程在中断后能够从中断点继续执行)。您必须确定并定义自定义代理中的工作流程步骤,确保这些步骤能够生成可以被保存的结果,以便在将任务传递给下一个处理步骤时使用。以下步骤说明了如何修改自定义代理以支持流程的“可恢复性”。

  • 创建 `CustomAgentState` 类:扩展 `BaseAgentState` 类,以创建一个能够保存代理状态的对象。
    • (可选)创建 WorkFlowStep 类。如果您的自定义代理(custom agent)包含一系列有序的步骤,可以考虑创建一个 `WorkFlowStep` 列表对象,该对象用于定义代理的各个独立且可保存的步骤。
  • “添加初始代理状态”(Add initial agent state): 修改你的代理程序中的异步运行函数(async run function),以便设置代理程序的初始状态。
  • 添加代理状态检查点:修改您的代理的异步运行函数(async run function),以便在代理完成整个任务的每个步骤后,生成并保存该步骤的状态信息。
  • 添加代理状态信息以跟踪代理的运行状态: 修改你的代理的 `async run` 函数,以便在其中添加相应的代码。 end_of_agent=True 代理完成全部任务后的状态。

以下示例展示了需要对 `StoryFlowAgent` 类所做的代码修改。 自定义代理(Custom Agents) guide:

class WorkflowStep(int, Enum):
 INITIAL_STORY_GENERATION = 1
 CRITIC_REVISER_LOOP = 2
 POST_PROCESSING = 3
 CONDITIONAL_REGENERATION = 4

# Extend BaseAgentState

class StoryFlowAgentState(BaseAgentState):
  step: WorkflowStep

# In the StoryFlowAgent class, replace the existing run implementation with:

@override
async def _run_async_impl(
    self, ctx: InvocationContext
) -> AsyncGenerator[Event, None]:
    """
    Implements the custom orchestration logic for the story workflow.
    Uses the instance attributes assigned by Pydantic (e.g., self.story_generator).
    """
    agent_state = self._load_agent_state(ctx, StoryFlowAgentState)

    if agent_state is None:
      # Record the start of the agent
      agent_state = StoryFlowAgentState(step=WorkflowStep.INITIAL_STORY_GENERATION)
      ctx.set_agent_state(self.name, agent_state=agent_state)
      yield self._create_agent_state_event(ctx)

    next_step = agent_state.step
    logger.info(f"[{self.name}] Starting story generation workflow.")

    # Step 1. Initial Story Generation
    if next_step <= WorkflowStep.INITIAL_STORY_GENERATION:
      logger.info(f"[{self.name}] Running StoryGenerator...")
      async for event in self.story_generator.run_async(ctx):
          yield event

      # Check if story was generated before proceeding
      if "current_story" not in ctx.session.state or not ctx.session.state[
          "current_story"
      ]:
          return  # Stop processing if initial story failed

    agent_state = StoryFlowAgentState(step=WorkflowStep.CRITIC_REVISER_LOOP)
    ctx.set_agent_state(self.name, agent_state=agent_state)
    yield self._create_agent_state_event(ctx)

    # Step 2. Critic-Reviser Loop
    if next_step <= WorkflowStep.CRITIC_REVISER_LOOP:
      logger.info(f"[{self.name}] Running CriticReviserLoop...")
      async for event in self.loop_agent.run_async(ctx):
          logger.info(
              f"[{self.name}] Event from CriticReviserLoop: "
              f"{event.model_dump_json(indent=2, exclude_none=True)}"
          )
          yield event

    agent_state = StoryFlowAgentState(step=WorkflowStep.POST_PROCESSING)
    ctx.set_agent_state(self.name, agent_state=agent_state)
    yield self._create_agent_state_event(ctx)

    # Step 3. Sequential Post-Processing (Grammar and Tone Check)
    if next_step <= WorkflowStep.POST_PROCESSING:
      logger.info(f"[{self.name}] Running PostProcessing...")
      async for event in self.sequential_agent.run_async(ctx):
          logger.info(
              f"[{self.name}] Event from PostProcessing: "
              f"{event.model_dump_json(indent=2, exclude_none=True)}"
          )
          yield event

    agent_state = StoryFlowAgentState(step=WorkflowStep.CONDITIONAL_REGENERATION)
    ctx.set_agent_state(self.name, agent_state=agent_state)
    yield self._create_agent_state_event(ctx)

    # Step 4. Tone-Based Conditional Logic
    if next_step <= WorkflowStep.CONDITIONAL_REGENERATION:
      tone_check_result = ctx.session.state.get("tone_check_result")
      if tone_check_result == "negative":
          logger.info(f"[{self.name}] Tone is negative. Regenerating story...")
          async for event in self.story_generator.run_async(ctx):
              logger.info(
                  f"[{self.name}] Event from StoryGenerator (Regen): "
                  f"{event.model_dump_json(indent=2, exclude_none=True)}"
              )
              yield event
      else:
          logger.info(f"[{self.name}] Tone is not negative. Keeping current story.")

    logger.info(f"[{self.name}] Workflow finished.")
    ctx.set_agent_state(self.name, end_of_agent=True)
    yield self._create_agent_state_event(ctx)