11-19 更新 实时
首页/ AI 大模型/ 正文

谷歌 ADK 智能体:可暂停、恢复并等待人类数小时

AI 大模型 来源:Towards Data Science 2026-11-17 21:30 0 阅读 机器翻译
谷歌 ADK 智能体:可暂停、恢复并等待人类数小时

为什么我们应该停止与智能体聊天

如今大多数智能体的使用场景中,都有一个用户与智能体对话的界面。这在问答较为迅速的某些场景下是可行的,但我认为大多数智能体根本不会遵循“对话式”的模式。

因为说实话:如今真正的智能体生命周期很长。它们可能持续几分钟、几小时,甚至几天。而显然,你不会在聊天窗口前等上几个小时。

与人的沟通可以遵循两种模式:同步和异步。

同步 = 打电话。一旦一方挂断,对话就结束了。你无法同时进行不止一通电话。

异步 = 电子邮件。你写完就忘了。你不会一直盯着邮箱(嗯,等重要消息时可能会,但很快就会觉得无聊)。你会去做别的事,等回复到达时,通知会提醒你。

正如与人的沟通遵循这两条原则,我认为智能体也应被同样对待。不是像人一样,而是像同步或异步系统一样。

为什么我们需要异步智能体?

第一点,正如我上面所说,是用户体验。为了随时回复而时刻盯着某个东西,其余时间又只能干等着,这让人精疲力尽。

第二点与成本和基础设施有关。一个与用户保持通道常开的智能体(比如通过 websockets),会持续消耗带宽,并且在等待用户回复期间一直处于存活状态。智能体这一侧的闲置时间对成本来说极为不利。

简单来说:智能体的大部分时间都花在等待上。

它们消耗内存,消耗 CPU,消耗带宽,哪怕是在你自己的机器上。我开着几十个跑 Claude 的终端,电池很受伤。

如今大多数真实的智能体式用例,要么需要一个人工确认环节,要么是对信号做出反应(比如 webhook 触发)。人工确认环节可能需要好几个小时。这段时间里智能体怎么办?如果连接中断了又会怎样?

那么,什么时候该用异步智能体?

任务耗时从几分钟到几天 -> 异步

需要在过程中立即得到答案 -> Chat

人类必须在过程中批准或提供输入,但不必立即进行 -> 异步

人类必须在过程中立即批准或提供输入 -> 聊天

它应当由触发器(调度器、事件)启动 -> 异步

在本系列中,我想通过一个具体示例,带你了解如何使用 Google 的 Agent Development Kit 实现异步概念。我在教程或博客文章中看到的大多数实现往往过于简单,而我想通过一系列文章来讲解一个更贴近现实的实现。

第 1 部分将介绍 ADK 特有的概念——Runners、DatabaseSessionService、Events、FunctionCalls、RequestInput——它们用于运行智能体、持久化记忆、恢复执行等。我还会解释 webhook 如何工作,以及如何使用它们与远程服务通信。这一部分将主要进行本地开发,服务器运行在 localhost 上,并使用 SQLite 数据库。

第 2 部分将介绍我们所构建内容向生产环境的迁移。具体来说,我们将介绍 Cloud Run 等服务——它托管你的应用,并可在空闲时缩容至零(对成本高效),Cloud Tasks 用于在后台通过重试委托任务,以及 Cloud Scheduler 用于调度任务。

让我们开始第一部分吧!

为什么同步 HTTP 对长时间运行的 AI 智能体会失效

让我们设想有一个智能体,它执行一项非常简单的任务:抓取 RSS 订阅源,并对最新的几篇内容做摘要,从而提供每日简报。

这是一个很好的测试对象:它做的是真实工作(API 调用 + LLM 摘要),而且耗时足够长,等待它可能会让人难受。我目前有大约 20 个订阅源,读完所有这些大约需要 1–2 分钟。好吧,这不算难以承受,但想象一下扩展到 1000 个来源,你就能明白我的意思了。

这个智能体很简单,就是一个 LLM 加一个工具。工具本身不过是一个遍历数据源的循环:

import feedparser FEEDS = [ "https://blog.google/technology/ai/rss/", "https://blog.google/innovation-and-ai/infrastructure-and-cloud/google-cloud/rss/", "https://cloudblog.withgoogle.com/products/ai-machine-learning/rss/", "https://developers.googleblog.com/feeds/posts/default/", "https://simonwillison.net/atom/everything/", "https://hnrss.org/newest?q=htmx+OR+ADK+OR+%22agent+development%22&points=20", "https://huggingface.co/blog/feed.xml", "https://www.anthropic.com/rss.xml", "https://read.deeplearning.ai/the-batch/rss/", "https://thegradient.pub/rss/", "http://export.arxiv.org/rss/cs.AI", "http://export.arxiv.org/rss/cs.CL", ] def fetch_rss_feeds() -> str: """Fetch the latest articles from the configured RSS feeds. Call this first.""" results = [] for url in FEEDS: entries = feedparser.parse(url)['entries'] for entry in entries: if entry: title = entry.title or "(no title)" link = entry.link or "" published = entry.published if hasattr(entry, "published") else "unknown" summary = (entry.summary or "")[:300].strip() results.append(f"[{published}] {title}\n{link}\n{summary}\n") return "\n---\n".join(results) if results else "No articles found."

这是一个非常幼稚的实现。在生产环境中,我主要会使用 asyncio 库中的 TaskGroups 和 Semaphores。现在,我们暂且把它当作我们的工具。

智能体是一个简单的 LLM,带有这个工具:

from google.adk.agents import Agentroot_agent = Agent( name="daily-feed", model="gemini-4-argon", instruction=""" You are a sharp tech analyst writing a daily AI & data engineering briefing. Your first action MUST be to call the fetch_rss_feeds tool to get today's articles. Then summarize ONLY the articles returned by that tool. Do NOT search the web. Do NOT add information from outside the fetched articles. For each entry, provide: - The title and source - A 1-2 sentence summary of why it matters - The article link Rules: - Be concise and opinionated. Skip fluff. - Prioritize novelty and impact. - Always cite your sources with the link. """, tools=[fetch_rss_feeds],)

在进入智能体的执行循环之前,我想回顾一下 ADK 使用的一些概念/对象,因为它们将在本文剩余部分中至关重要。

智能体:一个 LLM + 指令 + 工具。

工具:LLM 可以使用的一个函数。在我们的例子中,这就是 fetch_rss_feeds。重要:docstring 会告诉 LLM 何时以及如何使用它,所以不要忽视它

Runner:智能体的执行循环。它调用 LLM,调用工具,并处理两者之间的通信。

会话:一段对话的历史:它的事件、消息和输出。它还持有一个键值状态,你可以用它来跟踪循环内的选择、步骤等。

SessionService:会话的存储位置。InMemorySessionService 将会话保存在内存中(进程停止后所有内容都会丢失)。DatabaseSessionService 将会话持久化到数据库中。

Event:循环执行过程中的一个步骤。Runner 自始至终都会产出 Event。

FunctionCall 和 FunctionResponse:它们分别中断和恢复循环,其方式是保留一个 interrupt_id,用于确定从哪里恢复。当 FunctionCall 由 RequestInput 或 LongRunningFunctionTool 发出时,它会携带一个 interrupt_id。

现在我们已经有了各种构建模块,接下来把它们串联起来。按步骤进行:

定义会话的存储方式(保存在内存中还是数据库中)

运行 runner 并收集事件

app_name=...agent=...session_service=...async def _run(message: str, session_id: str, **kwargs): # 创建一个绑定到该服务的会话 await session_service.create_session( app_name=app_name, user_id="admin", session_id=session_id ) # 创建 runner runner = Runner( agent=agent, app_name=app_name, session_service=session_service ) # 将消息格式化为 Content content = types.Content(role="user", parts=[types.Part(text=message)]) # 运行循环并收集事件 async for event in runner.run_async( user_id="admin", session_id=session_id, new_message=content ): if event.content and event.content.parts: print(f"agent> {event.content.parts[0].text}\n") return event.content.parts[0].text

假设我们的智能体部署在远程端点上(例如作为一个微服务)。它提供一个 /run 端点,用于触发智能体的执行。请求体如下所示:

import uuidfrom pydantic import BaseModel, Fieldclass RunRequest(BaseModel): session_id: str = Field(default_factory=lambda: str(uuid.uuid4())[:8]) message: str = "Start" interrupt_id: str | None = None

一个极简版的 API 实现可以像这样:

# sync_agent.pydef to_sync_app( agent, app_name: str, session_service: InMemorySessionService | DatabaseSessionService ): async def _run(message: str, session_id: str, **kwargs): # defined above api = FastAPI(title=app_name) @api.get("/health") def health(): return {"agent": app_name, "status": "healthy"} @api.post("/run") async def run(req: RunRequest): t0 = time.time() output = await asyncio.create_task(_run(**req.model_dump())) return {"status": "success", "output": output[:100], "time_elapsed": time.time()-t0} return api

原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。

查看英文原文(Google ADK Agents That Pause, Resume, and Wait Hours for a Human)

Why we should stop chatting with agents

In most agent use cases today there is a UI in which the user and the agent have a conversation. This works for certain use cases where questions and answers are quick, but I believe most agents simply don’t follow a “conversational” pattern.

Because let’s be honest: real agents today have a long lifetime. They can span minutes, hours, maybe days. And obviously, you don’t wait for hours in front of your chat window.

Communication with humans can follow two patterns: synchronous and asynchronous.

Synchronous = phone call. If one drops, the conversation ends. You cannot have more than one call at the same time.

Asynchronous = emails. You write, and you forget. You don’t just stare at your mailbox (well, you may when you wait for an important message, but you’ll quickly get bored). You go do other things, and a notification pings you when a reply arrives.

Just like communication with humans follows those two principles, I believe agents should be treated the same. Not like humans, but like synchronous or asynchronous systems.

Why do we need async agents?

The first one is, as I said above, user experience. It is exhausting to monitor something constantly in order to reply, and to sit idle the rest of the time.

The second one is related to costs and infrastructure. An agent that keeps a channel open with the user (via websockets for example) is consuming bandwidth, and stays alive while waiting for the user’s response. This idle time on the agent side is terrible for costs.

Let’s put it simply: Agents spend most of their time waiting.

They cost RAM, they cost CPU, they cost bandwidth. Even on your machine. I have dozens of terminals open with Claude, and my battery suffers.

Most real agentic use cases today require either a human validation step, or a reaction to signals (webhook triggers for example). A human validation step may take several hours. What happens to the agent during this time? What happens if the connection breaks?

So when should we use async agents?

The work takes minutes to days -> Async

The answer is needed along the way, and immediately -> Chat

A human has to approve or give input along the way, but not immediately -> Async

The human has to approve or give input along the way immediately -> Chat

It should start with a trigger (scheduler, event) -> Async

In this series, I want to guide you through a concrete example of how to implement async concepts with the Agent Development Kit from Google. Most implementations I have seen from tutorials or blog posts are often very simplistic, and I wanted to go through a realistic implementation in a series of articles.

Part 1 will cover concepts specific to ADK - Runners, DatabaseSessionService, Events, FunctionCalls, RequestInput - that are used to run agents, persist memory, resume executions, etc. I will also explain how webhooks work, and how to use them to communicate with remote services. This part will be mostly local development, with servers running on localhost and SQLite databases.

Part 2 will cover the move to production of what we build. Specifically, we will cover services like Cloud Run which hosts your apps and can scale to zero when idle (efficient for cost), Cloud Tasks to delegate tasks in the background with retries, and Cloud Scheduler to schedule tasks.

Let’s kickstart this first part!

Why synchronous HTTP breaks for long-running AI agents

Let’s imagine we have an agent that does a very simple task: fetching RSS feeds and summarizing the latest ones to provide a daily brief.

It’s a good test subject: it does real work (API calls + LLM summary) and takes long enough that waiting for it could hurt. I currently have around 20 feeds, and it takes around 1–2 minutes to read all these. OK, it’s not overwhelming, but think of scaling to 1000 sources and you get the idea.

The agent is simply an LLM and a tool. The tool itself is just a loop over sources:

import feedparserFEEDS = [ "https://blog.google/technology/ai/rss/", "https://blog.google/innovation-and-ai/infrastructure-and-cloud/google-cloud/rss/", "https://cloudblog.withgoogle.com/products/ai-machine-learning/rss/", "https://developers.googleblog.com/feeds/posts/default/", "https://simonwillison.net/atom/everything/", "https://hnrss.org/newest?q=htmx+OR+ADK+OR+%22agent+development%22&points=20", "https://huggingface.co/blog/feed.xml", "https://www.anthropic.com/rss.xml", "https://read.deeplearning.ai/the-batch/rss/", "https://thegradient.pub/rss/", "http://export.arxiv.org/rss/cs.AI", "http://export.arxiv.org/rss/cs.CL",]def fetch_rss_feeds() -> str: """Fetch the latest articles from the configured RSS feeds. Call this first.""" results = [] for url in FEEDS: entries = feedparser.parse(url)['entries'] for entry in entries: if entry: title = entry.title or "(no title)" link = entry.link or "" published = entry.published if hasattr(entry, "published") else "unknown" summary = (entry.summary or "")[:300].strip() results.append(f"[{published}] {title}\n{link}\n{summary}\n") return "\n---\n".join(results) if results else "No articles found."

This is a very naive implementation. In a production context, I would mostly use TaskGroups and Semaphores from the asyncio library. For now, let’s consider this as our tool.

The agent is a simple LLM with this tool:

from google.adk.agents import Agentroot_agent = Agent( name="daily-feed", model="gemini-4-argon", instruction=""" You are a sharp tech analyst writing a daily AI & data engineering briefing. Your first action MUST be to call the fetch_rss_feeds tool to get today's articles. Then summarize ONLY the articles returned by that tool. Do NOT search the web. Do NOT add information from outside the fetched articles. For each entry, provide: - The title and source - A 1-2 sentence summary of why it matters - The article link Rules: - Be concise and opinionated. Skip fluff. - Prioritize novelty and impact. - Always cite your sources with the link. """, tools=[fetch_rss_feeds],)

Before going to the execution loop of the agent, I want to recap some concepts / objects used by ADK since they will be key in the rest of the article.

Agent: an LLM + instructions + tools.

Tool: a function the LLM can use. In our case, this is fetch_rss_feeds. Important: the docstring tells the LLM when and how to use it, so don’t overlook it

Runner: the execution loop for the agent. It calls the LLM, calls the tools, and handles the communication between both.

Session: the history of a conversation: its events, messages and outputs. It also holds a key-value state that you can use to track choices, steps, etc. inside the loop.

SessionService: where sessions are stored. InMemorySessionService keeps them in memory (everything is lost when the process stops). DatabaseSessionService persists them in a database.

Event: a step in the execution of the loop. The Runner yields Events all the way through.

FunctionCall and FunctionResponse: they respectively interrupt and resume the loop, by keeping an interrupt_id that will be used to know where to resume. When a FunctionCall is emitted by RequestInput or a LongRunningFunctionTool, it carries an interrupt_id.

Now we have the building blocks, let’s wire them together. Proceed in steps:

Define the way the session will be stored (in memory or in a database)

Run the runner and collect the events

app_name=...agent=...session_service=...async def _run(message: str, session_id: str, **kwargs): # Create a session attached to the service await session_service.create_session( app_name=app_name, user_id="admin", session_id=session_id ) # Create a runner runner = Runner( agent=agent, app_name=app_name, session_service=session_service ) # Format the message as a Content content = types.Content(role="user", parts=[types.Part(text=message)]) # Run the loop and collect events async for event in runner.run_async( user_id="admin", session_id=session_id, new_message=content ): if event.content and event.content.parts: print(f"agent> {event.content.parts[0].text}\n") return event.content.parts[0].text

Let’s imagine our agent is deployed on a remote endpoint (for ex, as a microservice). It provides a /run endpoint which triggers the execution of the agent. The request body looks like this:

import uuidfrom pydantic import BaseModel, Fieldclass RunRequest(BaseModel): session_id: str = Field(default_factory=lambda: str(uuid.uuid4())[:8]) message: str = "Start" interrupt_id: str | None = None

A very minimal implementation of our API could be implemented like this:

# sync_agent.pydef to_sync_app( agent, app_name: str, session_service: InMemorySessionService | DatabaseSessionService ): async def _run(message: str, session_id: str, **kwargs): # defined above api = FastAPI(title=app_name) @api.get("/health") def health(): return {"agent": app_name, "status": "healthy"} @api.post("/run") async def run(req: RunRequest): t0 = time.time() output = await asyncio.create_task(_run(**req.model_dump())) return {"status": "success", "output": output[:100], "time_elapsed": time.time()-t0} return api

In this implementation, despite the async in front of the run function, we wait for the output before returning a message.

This is 100% synchronous: the HTTP request stays open until the agent responds.

Wrap the agent in the to_sync_appand start the agent with:

uv run uvicorn rss-feed-parser.sync_agent:app --port 8002

Let’s open another terminal and send a request with curl

curl -X POST http://127.0.0.1:8002/run \-H "Content-Type: application/json" \-d '{"message": "start"}'

You can see the agent receiving the request and starting working in the agent terminal:

INFO: Uvicorn running on http://127.0.0.1:8002 (Press CTRL+C to quit)agent> I'll fetch today's articles right away!...

Since we are in sync mode, the curl terminal just waits and hangs. The HTTP connection is kept open, and we eventually receive the reply after about a minute and a half:

{ "status":"success", "output":"Here's your **AI & Data Engineering Briefing (truncated)" , "time_elapsed":83.74279189109802}

Our application has just kept an HTTP connection open for 83 seconds, between our request and the final report. During that time, the terminal was blocked.

Timeouts because on most servers, HTTP request will time out after some time. Could be seconds, or hours, but it will happen. After a timeout, the agent keeps working but has nowhere to go when it’s done.

Resources because during all this time, the connection was kept open. Keeping a connection open means keeping a client-side process alive, which is wasteful because nothing is happening. Furthermore, the client cannot perform any work and just has to wait. Not efficient.

The Fire-and-Forget Pattern: HTTP 202 Accepted and Webhooks

As said before, thinking async is thinking “delegation”. You hand over a task to the agent, go do something else, and get notified when the agent is done.

Think about doing laundry. There are two options:

You go to the self-service laundry, and just stay for the whole time the machine is running, in case someone steals your clothes. You stay and you stare at the machine.

Or you can go to a professional cleaner, drop your clothes, get a receipt, and go home. The laundry calls you when it’s ready.

In the latter, the receipt is the task id, and the phone call is a webhook. And what this means concretely for you is that you can live your life between the moment you drop your clothes and the moment you collect them.

Let’s now write a to_async_app wrapper that returns 202 when receiving a new request, with the task id attached (the receipt). We can reuse the previous to_sync_app and only change the /run route:

@api.post("/run", status_code=202)async def run(req: RunRequest): asyncio.create_task(_run(**req.model_dump())) return {"status": "created", "session_id": req.session_id}

Compared to the sync route:

We no longer await the task. asyncio.create_task schedules _run to run in the background and returns immediately, so the endpoint can answer right away.

The task id is simply the session_id: the one the caller sent, or the one RunRequest generated.

If you curl the agent now, it immediately replies with:

{"status":"created","session_id":"092e44f1"}

But how does the agent communicate, or “call back”, when it’s done? In the sync agent, we kept the connection open. Here, we closed it. So how do we reach the caller again?

A webhook is an endpoint that listens for incoming requests and reacts to them. In our case, we can tell the agent to POST its status / output to a webhook when it’s done running, or when it pauses:

async def report_progress( webhook_url: str, session_id: str, app_name: str, interrupt_id: str="", status: str='created', message: str="",): async with httpx.AsyncClient() as client: await client.post(f"{webhook_url}", json={ "message": message, "session_id": session_id, "app_name": app_name, "interrupt_id": interrupt_id, "status": status })

This way, we can create a to_async_app function that will run the agent with the webhook part and with the 202 receipt we defined earlier.

The app does something simple: it creates a session, instantiates a runner, loops through the events, and sends a report.

Since we don’t interrupt the graph here, resuming it is not possible, so I choose not to persist sessions. We’ll see that right after.

def to_async_app( agent, app_name: str, webhook_url: str, session_service: InMemorySessionService | DatabaseSessionService): async def _run(message: str, session_id: str, **kwargs): await session_service.create_session( app_name=app_name, user_id="admin", session_id=session_id ) runner = Runner( agent=agent, app_name=app_name, session_service=session_service ) content = types.Content(role="user", parts=[types.Part(text=message)]) async for event in runner.run_async( user_id="admin", session_id=session_id, new_message=content ): if event.content and event.content.parts: print(f"agent> {event.content.parts[0].text}\n") await report_progress( webhook_url=webhook_url, session_id=session_id, app_name=app_name, status="completed", message=event.content.parts[0].text) return None api = FastAPI(title=app_name) # ... same FastAPI app with the 202 /run endpoint above

the _run function now awaits report_progress with the webhook URL, to send the result back when the agent is done

the /run endpoint creates a background task and returns the receipt id immediately

To receive those webhook calls, I run a separate lightweight FastAPI service on port 8001 (which I call the “board”). It exposes a POST /webhook endpoint that logs incoming status updates from the agent and stores them in SQLite so we can track tasks in a table.

We can then wrap our RSS agent like this:

app = to_async_app( agent=root_agent, app_name=APP_NAME, session_service=InMemorySessionService(), webhook_url="http://127.0.0.1:8001/webhook",)

Send a request to your agent via curl, and see what happens:

The agent immediately replies with POST /run HTTP/1.1 202 Accepted, and we get the receipt back with status=”created”.

The connection closes. Our terminal is free!

The agent does the work in the background.

In the board terminal (8001), we receive the agent’s report after 1–2 min:

Received {'message': '(truncated)', 'session_id': 'd39d6d66–58c5–4fad-aeb1-b6b2db203542', 'app_name': 'daily_news', 'interrupt_id': '', 'status': 'completed'}INFO: 127.0.0.1:63610 - "POST /webhook HTTP/1.1" 200 OK

It works, but it’s fragile:

If the board dies (8001), the agent still does the work, but its report has nowhere to go and is lost.

Kill the agent (Ctrl+C) right after sending a task, and the board never hears from it again.

Running this agent on Cloud Run might break if the instance scales to zero.

In this minimal version the agent only reports once: when it succeeds. The runtime in the next part reports running, paused, completed and failed, which is what a supervisor needs to follow a task. Noticing tasks that have gone silent is a topic for later.

Summary of an async agent:

Human-in-the-Loop (HITL) in Google ADK: Pausing and Resuming Workflows

Human validation and Long-running Operations

The nice thing about ADK is that it handles interruptions the same way whether you’re waiting for human intervention (HITL) or an external system.

A pause requiring human intervention can be triggered with a RequestInput response inside a workflow.

A pause requiring the completion of a long-running operation is triggered by calling a LongRunningFunctionTool

Both interruptions will yield a FunctionCall event, with an interruption_id associated with it. This event does two things:

it stops the execution. The workflow exits.

it tells the user “This is the id you need to provide if you want me to resume from where I stopped”.

The RSS agent only needed a single tool call. We could just re-run it if it failed. But sometimes our agents are multi-step workflows where each step can require a pause/human validation.

Imagine a workflow where an agent performs dozens of Google searches to write a report on a topic: before burning tokens, we might want to validate the research plan before the agent actually starts searching. Running research on a topic for 10 minutes just to realize you forgot to mention something in the topic is a massive waste of time and money.

To illustrate our point, we will write a deep research agent that proceeds in several steps:

The agent drafts a plan in three sections based on user input

The agent submits the draft to the user -> This is the HITL part!

If the user wants to edit the draft or add some feedback, the agent returns to 2. Otherwise, the user accepts and we move to the next step

The agent spins several Google search tasks to fetch content

The agent assembles the sections in a final report

The agent sends it back to the user

Here is the actual communication between the user, the supervisor (called the “board”), and the agent:

The full code for the agent is in the repo, I’ll just provide the pipeline part to explain how I wired my agent:

@node(rerun_on_resume=True)async def pipeline_orchestrator(ctx: Context, node_input): """ rerun_on_resume=True tells ADK to re-enter this function on each resumption. Completed child nodes (step1, approve1, etc.) fast-forward from session checkpoints, while the while-loop cleanly controls retry/progression. """ plan_approved = False while not plan_approved: # 1. Ask or get topic from ctx.state s1 = await ctx.run_node(plan_generator, node_input) # 2. Approve (Pauses for human validation; returns user text on resume) user_validation = await ctx.run_node(validate_plan, s1) # 3. Validation Agent parses decision decision = await ctx.run_node(validation_agent, user_validation) # 4. If validated -> exit the loop; otherwise repeat step 1 if isinstance(decision, dict): plan_approved = decision.get("move_next", False) else: plan_approved = getattr(decision, "move_next", False) # 5. Start research return await ctx.run_node(run_research, None)

I use the dynamic graph creation from ADK 2.0 since it gives me better control over the flow. The current pattern is easily replicable:

The first step is getting the initial research topic and generate a plan out of it

A validate_plan then asks the user for confirmation. This is where the interruption happens.

The user feedback is parsed using an LLM to disambiguate the response and collect the feedback.

If the plan is approved, we move on, else we restart from the plan generation WITH the feedback

In many tutorials I have read, HITL only asks for a binary response. The worst implementations I’ve seen use keyword matching to interpret the user’s response, e.g.: response in (‘ok’, ‘yes’, ‘approve’). I really believe the LLM here adds some value in understanding responses in plain language and also allows us to collect feedback at the same time. Otherwise, we would have to chain a binary approval step, get the answer, yield another interrupt to ask for feedback if the answer is negative, etc.

Here is our validation agent:

class ProceedSchema(BaseModel): move_next: bool feedback: strvalidation_agent = Agent( name="validation_agent", description="Reads and validates user input", instruction=""" You are a routing agent. You receive a feedback from the user. Based on this feedback, compare it with {{ research_plan }} If the feedback is positive and no changes are made to the plan, proceed to next step. Otherwise, go back to previous step. """, output_schema=ProceedSchema, output_key="feedback")

Why the loop can be plain Python with ADK 2.0

Steps 1–4 are encapsulated in a while loop. While the decision node (which is an LLM) does not output a user validation, it repeats the steps by adding feedback. Feedback is stored in the state variable (cf concepts explained earlier). See how it is used in the plan generator:

plan_generator = Agent( # ... instruction=f""" You are a research strategist. Your job is to create a high-level RESEARCH PLAN, not a summary. If there is already a RESEARCH PLAN in the session state, improve upon it based on the user feedback. RESEARCH PLAN(SO FAR): {{ research_plan? }} USER FEEDBACK: {{ feedback? }} ← HERE ALWAYS FORMAT THE PLAN AS 3 BULLET POINTS WITH THE GOAL DESCRIPTION FOR EACH Current date: {datetime.datetime.now().strftime("%Y-%m-%d")} """, # ...)

The rerun_on_resume=True tells ADK to rerun the function every time the workflow is interrupted and resumed. When rerunning the function, it skips the nodes already executed (their results come back from the session’s checkpoints) to resume where it stopped. This is why the loop can be plain Python: after a resume, the while loop replays quickly up to the point where it was paused.

Interrupt & Human-in-the-loop

Step 2 is really where the HITL happens, in the following function that returns a RequestInput

@node(rerun_on_resume=False)async def validate_plan(ctx: Context, node_input: PlanOutput): plan = ... yield RequestInput( message=f"{plan}\n\nDo you want to proceed with the plan or do you have feedback?" )

When ADK reaches the RequestInput line, the run stops. The Runner emits one last event: a FunctionCall carrying your message, plus a long_running_tool_ids attribute that contains the interrupt id. Nothing is running anymore, and the open question is saved in the session.

But before we can resume, we also need to persist our session in a database. Remember we had a choice between InMemorySessionService and DatabaseSessionService? Using the first one means the session history will be lost once the event loop ends with the interruption, or if the agent dies.

Let’s create a to_hitl_app following those two snippets:

Setup & Resuming a Session

def to_hitl_app( agent, app_name: str, session_service: DatabaseSessionService, webhook_url: str, initial_state: dict | None=None): app = App( name=app_name, root_agent=agent, resumability_config=ResumabilityConfig(is_resumable=True), ) api = FastAPI(title=app_name) async def _run( session_id: str, message: str="Start", interrupt_id: str | None = None ): # 1. Load existing session from DB (on resume), or create a new one (on start) session = await session_service.get_session(app_name=app_name, user_id="admin", session_id=session_id) if session is None: await session_service.create_session( app_name=app_name, user_id="admin", session_id=session_id, state=initial_state ) # 2. If resuming from an interrupt, send a FunctionResponse matching the interrupt_id if interrupt_id: content = types.Content( role='user', parts=[types.Part(function_response=types.FunctionResponse( id=interrupt_id, name='adk_request_input', response={'result': message}, ))], ) else: content = types.Content( role='user', parts=[types.Part(text=message)], )

Notice that the session_service is now a DatabaseSessionService(DB_URL). We also need to pass a ResumabilityConfig(is_resumable=True) to the app to be able to resume it later.

2. Catching the interrupt in the event loop

What about the interruption itself? Where do we catch the interruption_id? In the _run function, we can listen for events with a long_running_tool_ids:

async for event in events: if event.long_running_tool_ids: iid = next(iter(event.long_running_tool_ids)) message = event.content.parts[0].function_call.args.get('message') await report_progress( webhook_url=webhook_url, session_id=session_id, app_name=app_name, status="paused", interrupt_id=iid, message=message) return if event.output is not None: final_output = event.output elif event.is_final_response() and event.content and event.content.parts: text = event.content.parts[0].text if text: final_output = text.strip()

Let’s try running this agent. Keep the board running on port 8001, and from the agents/ folder start it with:

uv run uvicorn hitl.agent:app - port 8002

Send a request to it, for example:

curl -X POST http://127.0.0.1:8002/run -H "Content-Type: application/json" -d '{"message": "write a report on small language models"}'

It immediately returns a 202 with {“status”:”created”,”session_id”:”e3c737c8"}. Note the session_id: you will need it to resume.

Let’s now look at the board’s terminal:

Received {'message': '(truncated)', 'session_id': 'e3c737c8', 'app_name': 'deepresearch', 'interrupt_id': '17f77321–0c78–4b6c-b7a6-ae4940d0f512', 'status': 'paused'}INFO: 127.0.0.1:49857 - "POST /webhook HTTP/1.1" 200 OK

Ask the board for the task. This is where you read the interrupt_id needed to resume the workflow:

curl http://127.0.0.1:8001/tasks/e3c737c8# {"id": "e3c737c8", "agent": "deepresearch", "status": "paused", "interrupt_id": "17f77321–0c78–4b6c-b7a6-ae4940d0f512", "message": "…", "updated_at": "…"}

The plan is reproduced below. Notice how the status is now “paused”, with an interrupt_id that is our “receipt” to resume the agent.

→ Define Small Language Models (SLMs), exploring their architectural methodologies (such as distillation, pruning, and quantization) and key differences compared to Large Language Models (LLMs).
→ Analyze the current landscape of prominent SLMs (e.g., Phi, Llama, Gemma, Mistral, Qwen series), evaluating their performance benchmarks, resource efficiency, and hardware requirements.
→ Investigate real-world enterprise and consumer applications of SLMs, focusing on edge computing, on-device privacy, cost reduction, and inherent limitations.

Do you want to proceed with the plan or do you have feedback?

Kill the agent process to make sure nothing persists in memory. Restart it and send the following curl command:

curl -X POST http://127.0.0.1:8002/run \ -H "Content-Type: application/json" \ -d '{ "session_id": "e3c737c8", "interrupt_id": "17f77321-0c78-4b6c-b7a6-ae4940d0f512", "message": "replace the third section with something about small reasoning models" }'

The initial third section was → Investigate real-world enterprise and consumer applications of SLMs, focusing on edge computing, on-device privacy, cost reduction, and inherent limitations.. We ask our agent to change the focus to small reasoning models.

Let’s see if the agent updated the plan with our feedback!

Remember the interrupt_id AND the session_id:

session_id literally says “Resume from this conversation”, and interrupt_id says “In this conversation, resume from this specific point”.

If you forget session_id, you will hit an error.

Following our feedback, we can see that the plan has been updated:

→ Define Small Language Models (SLMs), exploring their architectural methodologies (such as distillation, pruning, and quantization) and key differences compared to Large Language Models (LLMs).
→ Analyze the current landscape of prominent SLMs (e.g., Phi, Llama, Gemma, Mistral, Qwen series), evaluating their performance benchmarks, resource efficiency, and hardware requirements.
→ Examine the emergence of small reasoning models, investigating how techniques like test-time compute, reinforcement learning, and chain-of-thought distillation enable complex problem-solving within compact parameter limits.

Do you want to proceed with the plan or do you have feedback?

The third bullet point has successfully taken our feedback into consideration! Reply to this message with a “proceed”, but be careful: the interrupt_id has changed! Make sure you use the last one!

curl -X POST http://127.0.0.1:8002/run \-H "Content-Type: application/json" \-d '{"message": "go ahead", "interrupt_id": "e0954e84–96c3–42a3-a45a-0fcfc0365e31", "session_id": "e3c737c8"}'

The session_id stays the same for the whole task, but each pause has its own interrupt_id: it identifies one specific question. The agent now runs the research (about 3 to 4 minutes in my run), and the board receives a last webhook with the status completed and the final report. Poll curl http://127.0.0.1:8001/tasks/e3c737c8 until status is completed.

Behind the scenes: how ADK manages interruptions and resumes

To really understand how ADK pauses, resumes and checkpoints, let’s have a look at the events that happen. Since all the events are persisted on the database we can open it to see the traces:

Let’s have a closer look at the “events” table, and specifically some fields which tell us which nodes are running and how the graph state is being modified. The table below recaps the events to explain how the interrupts and resumes are handled:

So how does ADK know which nodes to rerun and which ones to skip?

On every resume, ADK re-enters pipeline_orchestrator from the top and looks up each call by its path. If the path already completed (plan_generator@1), its result is read from the database and the node is skipped. If it doesn’t exist yet, it runs. That’s why plan_generator runs a second time: the loop calls it again, and the counter makes it plan_generator@2, a path that doesn’t exist yet.

ADK persists all events in a database when we use a DatabaseSessionService

The events table is append-only

A pause is a FunctionCall event with an interrupt id. The answer is a FunctionResponse event with the same id.

On resume, the orchestrator replays from the top. A path that already completed is skipped, while a new one runs.

We started with a synchronous HTTP agent that held connections open for 80+ seconds and lost all progress on a timeout. By combining three building blocks:

HTTP 202 + Webhooks to decouple request submission from completion,

DatabaseSessionService+ ResumabilityConfig to persist execution checkpoints across restarts, and

node(rerun_on_resume=True)+ RequestInput to pause and resume plain Python loops using FunctionCall& FunctionResponse ,

we showed how to build a resumable agent that can be made to scale down to zero while waiting for the user input, should it take minutes or months.

There is still one flaw, though: asyncio.create_task runs in-process, without retries, and on serverless platforms like Cloud Run, background tasks get CPU-throttled once the HTTP response returns.

In part 2, we’ll take this architecture to production using Cloud Run (scale-to-zero), Cloud Tasks (durable background execution and retries), and Cloud Scheduler.

Building a powerful polynomial engine for easy study and research

November 2, 20215 min read

Automating model tuning in Python with Gemini, LangGraph, and Streamlit for regression and classification improvements

August 20, 202511 min read

What worked, what broke, and why I did it

December 15, 20255 min read

A practical guide to PCA and Plotly.

September 12, 20203 min read

Deploy Ingress Controller on AWS EKS the right way

September 3, 20223 min read

Architectures, pitfalls, and patterns that work

April 17, 202611 min read

Accelerate coding with AI while staying in control and building reliable, production-ready software.

March 19, 202614 min read

Why rigidly constrained agents fail, and how to engineer token-efficient, self-adapting workflows.

The problem with agent memory today

April 16, 202615 min read

原文为英文,正文由自动抓取并保留原文。

本文由采集器自动同步

原文发布于 Towards Data Science(Google ADK Agents That Pause, Resume, and Wait Hours for a Human),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。

阅读原文 ↗