Long-running Agents with ADK

Speaker Introduction and the Long-Running Agent Problem

Nakul Galdra, AI and ML architect at Google Cloud, introduces the session's core challenge: building AI agents that run for days, weeks, or months without excessive token costs, compute spend, or context dilution. He provides a brief overview of what constitutes an AI agent — orchestration, LLM-tool connections, memory — and introduces ADK (Agent Development Kit) as the open-source, Python-native, LLM-agnostic framework that will be used throughout the talk.

Employee Onboarding as the Long-Running Agent Use Case

Nakul frames the employee onboarding process — spanning weeks and covering welcome emails, document signing, hardware provisioning, and day-one setup — as the target scenario for a long-running agent. He outlines the key requirements such an agent must meet: long-running capability, cost efficiency through sleep/shutdown, delegation to specialised sub-agents, and avoidance of context pollution and hallucination that plague chatbot-style interfaces.

Architecture of a Durable, Event-Driven Agent

Nakul describes the technical design of the solution: a durable, event-driven agent with a deterministic session state backed by a persistent database (Cloud SQL or SQLite locally). He walks through the logical flow — agent initialises, sends welcome packet, sleeps, wakes on webhook events (e.g. DocuSign completion, hardware receipt), completes the next task, and sleeps again. The architecture includes a FastAPI gateway, a root HR coordinator agent, specialised sub-agents, and persistent state management, with scaffolding handled by the agent CLI tool.

State Schema, Tool Context, and Persistent State Management

Nakul dives into the code-level design, showing explicitly defined onboarding states (start, welcome pack sent, documents signed, hardware delivered, hardware provisioned, completed) tracked via 'current step' and 'pending signals' variables. He explains how ADK's tool context allows agents to read and write state, how state is injected into system instructions to guide agent behaviour, and how saving state to a database enables full recovery if a container or agent crashes.

Webhook Resume Handlers and Agent Lifecycle in Action

Nakul explains how sleeping agents are re-awakened: FastAPI webhook endpoints trigger an 'onboarding resume handler' that hydrates state from the database, updates the current step, and launches the ADK async runner. He traces a complete cycle — document signed event arrives, sub-agent handles hardware and software provisioning, agent sleeps again awaiting hardware delivery, hardware receipt event re-triggers the handler — demonstrating how the pattern sustains long-running workflows with minimal token consumption.

Live Demo: Employee Onboarding Agent Walkthrough

Nakul demonstrates the open-sourced GitHub skeleton live, showing a fictitious employee (Olivia) moving through the onboarding workflow. He triggers document signing, which updates state to 'document signed' and advances to hardware provisioning; then triggers hardware receipt, which advances the agent to schedule day-one activities including login setup and team introductions — illustrating the full dormant-wake-act-sleep cycle in a realistic UI.

Production Readiness: Evaluation, Security, and Observability

Nakul covers what is needed to take the agent to production: a golden dataset eval plan, ADK's built-in user simulations for edge-case coverage, and online evaluations powered by OpenTelemetry-based agent observability on Google Cloud. He also highlights Model Armor for security guardrails including PII detection and prompt injection prevention, and notes that ADK's native OpenTelemetry support — including gen AI semantic conventions — keeps observability aligned with evolving standards automatically.

Hello, everyone. Thank you for your time today. So I'm Nakul Galdra. I'm an AI AI and ML architect at Google Cloud, based in Melbourne. The session I'm gonna be talking about today is, how you can run agents that run for days, weeks, even months, right, without burning a lot of tokens, without spending a lot of money on compute, and how you can do that without any sort of hallucinations or any sort of, context dilution.

So before we dive into code and examples, just wanted to set the scene with what an AI agent is. I'm pretty sure you're familiar with it, but just to set the scene, an AI agent is an autonomous system that can act on behalf of users and complete tasks. So when we think of agents, there are a couple of things that you need to look look out for.

One is the orchestration. So this could be any sort of framework, open source framework that you have. Today, we'll be talking about ADK as the orchestration framework here. Then this framework is supposed to connect the LLM models to tools and have some sort of a harness in terms of skills, profiles, and instructions there. And all of this is underpinned by memory, other sessions which is short term, or long term facts which could be the long term memory there. So a quick, you know, hands up in the room if anyone has played around with the ADK before.

Yep. Some people have. So what ADK is a quick, TLDR of A1 ADKs. ADK is an open source, agent framework that Google has open sourced. So it is available in a couple of languages Python, Java, Go, etcetera. So if you're an AI engineer or developer, I highly recommend this framework, especially because it makes it really easy, because it's modular, it's LLM agnostic, so you can plug and play any sort of models that you want.

And it's got a bunch of different features, such as state management, session management, etcetera as well. So local testing, user scenarios, everything pretty much built into the framework. So you're not hand rolling your own and can take advantage of the framework to do the heavy lifting for you. And educate covers the entire agent lifecycle, right from defining the scope all the way to deployment and everything in between.

So tool calling, memory management, user testing, simulations, pretty much everything that you would need. And I come from a Python native background, so it is very, very easy as a Python developer to get started. There's not a lot lot of configurations that you need to do. It's Python native, so it makes it very easy to understand and debug as well.

Okay. So today, we'll talk about a scenario for our long running agent, which is an onboarding scenario. Right? So generally, when you think of onboarding, we typically think often weeks. Right? So when we want to onboard a new employee, we basically send out a welcome email and for them to sign any sort of documents that they have.

Then provision hardware, any sort of software. Then an employee would confirm that they received the hardware. And then we would basically set them up for the first day. So introductions, calendar invites, all of that stuff as well. So generally this whole onboarding process would be typically a few weeks and we want an agent to take care of this.

So we want the agent to understand where the employees are in the journey and help them throughout the journey until they get onboarded. So if you have to build an agent to meet this, it has to have certain criteria. It has to be long running because again the horizon task is about weeks. It has to be cost efficient.

We don't want this agent to be running all the time. It has to sleep. When I say sleep, it has to completely shut down and still remember the context there. The next one is it should be able to delegate to sub agents, like specialized agents as needed as well. So we shouldn't have a single agent that does everything.

We should be able to chop and change and provide multi agent systems for it to run as well. So you might have seen like, hey, chatbots on all of these agents as well. So this wouldn't be a great fit for our use case mainly because the chatbot sort of interfaces are, you know, they can have a lot of sessions there, which can lead to context pollution, right? So when we want to know the exact state of where the employees are on their employee journey, if they have a lot of interactions, that context can get polluted and the agent can hallucinate or think, hey, the employee is actually on a different state when they are not.

Next is the token cost. So we want this agent to actually shut down when it's not in use. We don't want any sort of token cost to be used up, especially if you have a lot of sessions, a lot of state. Putting all of that together for every single query becomes quite expensive. And the hallucination as well.

So we don't want the agent to understand or forget or think that employee's on a different state when they actually know. So what we're looking at here is a long running agent that we can build out using the Python ADK framework, where we have a durable session state. So this session is deterministic, meaning that hey, there is no sort of, hallucination, that can happen.

There is a durable schema as well. So this is a predetermined schema rather than any sort of output that LLM can generate. It is event driven, which which means that the agent shuts down. And as soon as an event gets triggered, the agent wakes up, completes the task, goes back to sleep. And this agent is a multi agent system as well.

So we have a HR coordinator agent, then we have an IT specialist agent. So they can coordinate with each other. And we want to do all of this in a way that is robust, is observable, we can put in evaluation criteria, etcetera. So we'll talk about the logical architecture of if you had to build this agent, how would this look.

So first is we have to initialize the details for the new employee, so their email address, their credentials, whatever they need. Next, we send out a welcome packet to this employee. Then we wait for this welcome pack and the documents to be signed. So the agent shuts down. We have a webhook, which basically can be triggered on an event.

So maybe there's a DocuSign, they sign something. Based on that, we trigger off an alert. Then this webhook is caught by this agent. Agent wakes up. It will run through the process for that welcome part of the email. Then again, goes to sleep. Next, the hardware or software is starting to get provisioned. Once the employee gets the hardware, they confirm that they have received this hardware. That triggers off an event.

Event comes back to the agent. The agent wakes up. It does its thing. Then again, goes back to sleep. So that's the sort of logical architecture we're looking to build. And if you had to put this into, hey, how would we do this with ADK? First, we would have to have a fast API gateway or webhook that basically sends inbound requests.

Then we have a root agent, which is our HR coordinator agent. It has a bunch of different tools for it to complete the task. Then we have a sub agent, is specialized for a specific task. As example, hardware provisioning, software provisioning, etcetera. It's got tools dedicated to do that as well. Then we have a persistent state management.

So this is a database. We have used Cloud SQL. But again, ADK supports any sort of database that you want, price grace, AlloDB, etcetera. So you can put in any sort of database that you want there as well. So this is the technical architecture. So you have again, why I put the development tools here is you don't have to hand roll your own ADK code.

We have a CLI called agent CLI, which can take care of all the scaffolding for you. So the Terraform scripts, creating even the framework for the ADK itself, you can use agent CLI to do that. You can create evaluations using the agent CLI. And you can even use that within your ID of choice. It could be anti gravity, etcetera.

Then we have the framework itself, which is ADK. Then we have the persistent store, which is Cloud SQL in this case. Or you can use for local development SQLite, for example. Then you need to have a runtime where this agent runs. You can use other Cloud Run. You can even use your own Kubernetes cluster if you wanted to.

It doesn't really matter. In our case, we have used, agent runtime, which is our Google native service that manages the agent there. Cool. So now we'll dive into the code and how this would work. So this is the schema that we have defined. So we have explicitly defined states. So the start state, welcome pack is sent, documents assigned, hardware is delivered, hardware is provisioned, and finally completed.

So what we're going to do is we're going to use these state variables and have two couple of state gates called as current step and pending signals. So this is how we will track where the employee's at on their journey. And why this is important as well is if a container goes down, if an agent goes down, we have the state so we can always rebuild from the state and carry on as well. Next what we're going to do is we're going to take these states and inject them into our system instructions.

So if a certain step is there, this is what you would need to do, etcetera. So it's either calling tools, it could be calling sub agents, it could be shutting down as well. Next, within ADK, have something called as a tool context. So what tool context provides is a way for you to access the state variable. So within the ADK, we have something called a runner. And a runner manages the state.

But this state can be accessed using something called the tool context. So for example, you can see where the state is at at a certain point. And based on that, the agent will understand, hey, what's the next pending state to do? Because we can manage and access the state, we can actually save it in a database as well.

Right? So for example, if an agent goes down, if something happens catastrophic to the agent, the state is saved at a user level and a session level. So you would understand if I have to reboot, you understand exactly where the flow of this agent task is. This is great. Now we have an agent working with manager state, but how can we trigger this agent when it goes to sleep?

So for this, we can use the fast API endpoints or webhooks. And what this basically does is as soon as an event is triggered, it will run, what we call as the onboarding resume handler. What this does is basically hydrates the state. So for example, the the agent is down, completely shut off. As soon as an event comes through, this handler gets triggered.

It will hydrate the state from our database. So it will update the current state, and then it will actually trigger off the agent run. So we have something called as a runner, as I mentioned, with an ADK, runner async. Basically starts up the runner. And then it will hydrate the state so it understands exactly where, the employee is on their onboarding journey.

Again, based on the state, we have the system instructions the agent runs. It was able to look at the state variable and able to pick up what it needs to do from that state onwards and carry on. So here, for example, document signed, it delegates to a sub agent. The sub agent is able to, you know, start the hardware as well as the software provisioning.

Cool. After that is done, again, the agent goes back. It's wait waits for the hardware to be delivered. Once the hardware is del delivered, an event gets triggered, event comes through, the resume handlers gets kicked off, the state gets hydrated, the agent continues on this journey. So that's how we can build an agent that can run for for days, weeks, months without actually having to burn a lot of token cost because the agent goes down.

You have a way to handle those state changes that is deterministic in nature. You're able to handle those events as well. Okay. Let's see this in action. So we have open sourced this as a GitHub repo, so you can actually go in and and play around with this as well. So again, this is meant as a a skeleton or a framework for you to build upon.

And the use case is about employee onboarding, but you can take this for customer support, especially when you're doing async sort of chatbots. It could be for sales motions, for example, if you've put in a marketing campaign and you wanna check how effective that campaign was, it will take a long framework to to get those events in as well. So in this scenario, you're seeing that we have a new employee that's about to start.

And if you go and have a look, you have a hiring packet with the employee in this a fictitious employee called Olivia. We have a welcome email. As as you can see, there's a pending signature. Right? So what I can do is I can go and again, I'm triggering this with a click, but again, this could be through an API as well.

Right? So I'm gonna sign the packet. As as soon as you sign the packet, as you can see, packet has been signed. And again, the state has been updated to document signed. Now it goes to the next state, which is hardware provisioning. Now the hardware has been sent, the employee receives the hardware and they confirm either through like FedEx or through an email.

That would be triggered and then we can trigger off the hardware received as well. Now the hardware is received. The agent now goes to the next state, which is hardware received. Now is the day one welcome and schedule. As you can see, the agent is able to schedule day one for this employee. Welcome, log in setup, the meeting and greeting the team. And as you can see, has gone through that as well.

So this is how you can you can sort of build an agent, that is dormant and gets triggered at a certain point in time. You might be wondering, is great. This is a a demo. How can we actually deploy this to production? So the next step is actually putting in a robust eval plan in place. So it could be like golden dataset for a long running agent. It gets triggered.

Does actually the API endpoint gets triggered and stuff like that as well. We have a system called user simulations built into ADK as well, so you can catch edge cases that might not be captured within your golden data set. Then we have online evaluations as well. So if your agent is running in production on Google Cloud, for example, then our agent observability platform, because of OpenTelemetry logging, is able to capture the user prompt, the response, the tool calls, the tool trajectory, everything that you would need.

And all of that becomes an adaptive rubric, which is a dynamic rubric that gets generated by the platform itself. So you can catch errors as they happen in real time. Next, obviously, you're putting this in the wild, you want to have some security guardrails, so service such as Model Armor. It's an API that you can plug in.

You can look at PII information. You can look at prompt injection prevention, all of that stuff as well. So you would want to plug that in. And obviously, you want to look at logging. ADK natively supports OpenTelemetry, not just the JSON, but also the native primitive data structures as well. So gen AI underscore something which OpenTelemetry supports.

So as OpenTelemetry updates this native schema, ADK will update as well. So which is, you you don't have to worry about trying to match OpenTelemetry feature feature state because ADK natively will ensure that. Cool. Thank you for your time. I just wanted to share the blog, which goes into a lot more detail about this session that I talked about with sample code.

And also, we have a great ADK community as well because it's open

Long-running Agents with ADK

Nakul Gowdra - AI/ML Architect

Google Cloud

A graphic on the right features five overlapping black outline circles, each containing a different icon: a robot head with code symbols, a stylized 'M' or wave pattern, a broken chain link with dots, a robot head with horizontal lines, and a bar chart or data visualization.

Build, evaluate, and deploy sophisticated AI agents with code-first flexibility!

A stylized icon representing an AI agent or robot head in blue and green, with eyes as two dark blue dots. Below it, a yellow opening square bracket and red angle brackets (< >) are visible, symbolizing code.

Why ADK?

  • Easy to use interface
  • Modular and flexible
  • Instant local testing
  • Native multimodal support
  • Deployment ready

The ADK logo depicts a blue robot head with green antennae and two eyes, followed by yellow square brackets and red angle brackets.

  • A green snake icon illustrates "Easy to use interface".
  • A brick wall icon illustrates "Modular and flexible".
  • A yellow lightning bolt icon illustrates "Instant local testing".
  • A megaphone icon and a movie clapperboard icon illustrate "Native multimodal support".
  • A red and gray rocket ship icon illustrates "Deployment ready".

Multi-Agent

The system flow starts with a FastAPI Web Gateway (API Server) which receives an Inbound Request.

From the FastAPI Web Gateway, Asynchronous Webhooks (Signature/Logistics) are also sent.

The Inbound Request is directed to the Root Agent (HR Onboarding Coord). The Root Agent can perform Tool Calls to Global Tools (Welcome Packet, Day 1 Schedule).

Global Tools can interact with External APIs (DocuSign, FedEx etc).

The Root Agent also performs Task Delegation to a Sub-Agent (IT Agent).

The Sub-Agent makes Tool Calls to IT Provision Tools (provision_accounts).

IT Provision Tools interacts with the Database Session Service (sqlite+aiosqlite).

A flowchart diagram illustrating a multi-agent system architecture for HR onboarding. It shows interactions between a FastAPI Web Gateway, Root Agent (HR Onboarding Coord), Global Tools, External APIs, Sub-Agent (IT Agent), IT Provision Tools, and a Database Session Service.

Workflow Flowchart: Onboarding Process

Start: Onboarding Started

  1. Initialize Details
  2. Send Welcome Packet

State: WELCOME_SENT (WAITING)

  • IDLE TIME PAUSE (Days)
  • Waiting for local signature webhook callback.
  • Container scales down; state persisted.

Webhook Resume Callback: Documents Signed

  1. Provision Software Accounts

State: IT_PROVISIONED (WAITING)

  • IDLE TIME PAUSE (Days)
  • Waiting for carrier package delivery webhook.
  • Container scales down; state persisted.

Webhook Resume Callback: Hardware Delivered

  1. Send Day One Schedule

State: COMPLETED

End: Onboarding Completed

A flowchart illustrating the onboarding process, showing sequential steps, waiting states with idle time pauses, and webhook resume callbacks for documents signed and hardware delivered.

Logical Architecture

Key conditions for this Agent

  • Has to be long running ( Onboarding can take weeks)
  • Has to be cost effective
  • Has to be context aware
  • Able to delegate to specialized agents when needed

Typical Onboarding Process

  • STEP 01: Welcome Email and Onboarding documents
  • STEP 02: Provision hardware and services
  • STEP 03: Confirmation of hardware and onboarding documents
  • STEP 04: First day welcome and Introductions
  • Circular image next to Step 01 shows a woman at a desk using a laptop.
  • Circular image next to Step 02 shows a group of people collaborating around a table.
  • Circular image next to Step 03 shows a man in a hard hat reaching for something on a shelf in a warehouse.
  • Circular image next to Step 04 shows hands typing on a laptop displaying a bar chart with an upward trend.

Scenario: We need to build an Agent that can help on-board a new employee to our organization

ADK covers the entire agent lifecycle!

  • Define the Goal & Scope
  • Design the Agent & Interactions
  • Build Agents & Tools
  • Configure & Connect
  • Local Run & Debug
  • Evaluate & Iterate
  • Deploy
A process diagram illustrates the agent lifecycle. It shows seven steps represented by circular icons: Define the Goal & Scope (target icon), Design the Agent & Interactions (pencil icon), Build Agents & Tools (wrench icon), Configure & Connect (share icon), Local Run & Debug (bug icon), Evaluate & Iterate (checklist icon), and Deploy (airplane icon). Arrows indicate a linear flow through these steps, with feedback loops from Local Run & Debug and Evaluate & Iterate back to Design the Agent & Interactions.

Scenario: We need to build an Agent that can help on-board a new employee to our organization

Typical Onboarding Process

  • STEP 01: Welcome Email and Onboarding documents
  • STEP 02: Provision hardware and services
  • STEP 03: Confirmation of hardware and onboarding documents
  • STEP 04: First day welcome and Introductions
Four circular images illustrate the steps. The first shows a person working on a laptop. The second shows people collaborating around a table. The third shows a person checking inventory in a warehouse. The fourth shows hands typing on a laptop with a graph on the screen.

Key conditions for this Agent

  • Has to be long running ( Onboarding can take weeks)
  • Has to be cost effective
  • Has to be context aware
  • Able to delegate to specialized agents when needed

Architecture for Time: State Management for Multi-Day Agents

Stateless Agent

Fragile, Forgetful, Short-term
  • Context Pollution
    Irrelevant Chatter
  • Token Cost Explosion
    Replaying History
  • Reasoning Hallucinations
    During Idle Time
  • Can't Survive Idle Time
ADK Architectural Shift

Long-Running Agent

Durable, Context-Aware, Multi-Day Workflow
Use Case: HR Onboarding
  • Start Onboard Welcome Sent
  • Documents Signed
  • IT Provisioned
  • Hardware Delivered
  • Onboard Completed
  • Durable Memory Schemas
    Explicit State Checkpoints
  • Event-Driven Dormancy Gate
    Wake on Webhook/Signals
  • Multi-Agent Delegation
    Specialized Tasks
  • Survives Restarts & Pauses
A comparison diagram illustrating two approaches to agent state management over time. On the left, a "Stateless Agent" shows a user interacting with an LLM call requiring full history reply, depicted across a timeline from Day 1 to Day 14, highlighting issues like context pollution, token cost explosion, and reasoning hallucinations, concluding that it "Can't Survive Idle Time." An arrow in the middle indicates an "ADK Architectural Shift." On the right, a "Long-Running Agent" demonstrates a "Durable, Context-Aware, Multi-Day Workflow" with an HR onboarding use case, showing a series of hexagonal steps (Start Onboard Welcome Sent, Documents Signed, IT Provisioned, Hardware Delivered, Onboard Completed) over a timeline from Day 1 to Day 14, labeled "Persistent Session Storage." This approach lists solutions such as durable memory schemas, event-driven dormancy gates, and multi-agent delegation, concluding that it "Survives Restarts & Pauses."

Workflow Flowchart: Onboarding Process

  • Start: Onboarding Started
  • 1. Initialize Details
  • 2. Send Welcome Packet
  • State: WELCOME_SENT (WAITING)
    • IDLE TIME PAUSE (Days)
    • Waiting for local signature webhook callback.
    • Container scales down; state persisted.
  • Webhook Resume Callback: Documents Signed
  • 3. Provision Software Accounts
  • State: IT_PROVISIONED (WAITING)
    • IDLE TIME PAUSE (Days)
    • Waiting for carrier package delivery webhook.
    • Container scales down; state persisted.
  • Webhook Resume Callback: Hardware Delivered
  • 4. Send Day One Schedule
  • State: COMPLETED
  • End: Onboarding Completed
A flowchart illustrating an onboarding process, showing sequential steps and two waiting states that are resumed by webhook callbacks for document signing and hardware delivery.

Multi-Agent

  • FastAPI Web Gateway (API Server)
  • Inbound Request
  • Asynchronous Webhooks (Signature/Logistics)
  • Root Agent (HR Onboarding Coord)
  • External APIs (DocuSign, FedEx etc)
  • Tool Calls
  • Global Tools (Welcome Packet, Day 1 Schedule)
  • Task Delegation
  • Sub-Agent (IT Agent)
  • IT Provision Tools (provision_accounts)
  • Database Session Service (sqlite+aiosqlite)
A flow diagram illustrates a multi-agent system architecture. An Inbound Request is received by a FastAPI Web Gateway, which acts as an API Server. This request is processed by a Root Agent, specifically an HR Onboarding Coordinator. The Root Agent initiates Tool Calls to Global Tools, which manage tasks like preparing a Welcome Packet and a Day 1 Schedule. These Global Tools interact with External APIs, such as DocuSign and FedEx, which in turn send Asynchronous Webhooks (for signatures and logistics) back to the FastAPI Web Gateway. The Root Agent also performs Task Delegation to a Sub-Agent, identified as an IT Agent. The IT Agent makes Tool Calls to IT Provision Tools, specifically for provisioning accounts. A Database Session Service, utilizing sqlite and aiosqlite, is also shown as part of the overall system.

Development Tools

  • Agents CLI
  • CURSOR & More

Application Layer & Framework

  • ADK

Data & State Persistence

  • SQLite (Local)
  • Cloud SQL (Production)

Infrastructure & Runtime

  • Cloud Run
  • Agent Runtime
A layered architectural diagram illustrating a technology stack. The top layer, "Development Tools," includes Agents CLI, an icon resembling an 'A' shape, a sunburst icon, and a box with the CURSOR logo followed by "& More." Arrows show these tools connect to the "Application Layer & Framework" which contains the ADK. The ADK connects downwards to "Data & State Persistence," offering two options: SQLite (Local) and Cloud SQL (Production). SQLite (Local) connects to "Cloud Run" in the "Infrastructure & Runtime" layer, while Cloud SQL (Production) connects to "Agent Runtime" in the same layer.

Use states instead of conversation history

# app/state_schema.py

class OnboardingStep:
    START = "START"
    WELCOME_SENT = "WELCOME_SENT"
    DOCUMENTS_SIGNED = "DOCUMENTS_SIGNED"
    IT_PROVISIONED = "IT_PROVISIONED"
    HARDWARE_DELIVERED = "HARDWARE_DELIVERED"
    COMPLETED = "COMPLETED"

Current Step and Pending signals to track states

Use states in Agent instructions

async def initialize_onboarding_state(callback_context: CallbackContext) -> None:
    """Ensures all state machine keys are initialized to prevent errors."""
    state = callback_context.state
    if "current_step" not in state:
        state["current_step"] = OnboardingStep.START
    if "new_hire_details" not in state:
        state["new_hire_details"] = {}
    if "pending_signals" not in state:
        state["pending_signals"] = []

instruction = """You are an HR Onboarding Coordinator Agent.

Current Step: {current_step}
New Hire Details: {new_hire_details}
Pending Signals: {pending_signals}

Follow this state machine flow exactly:
1. If current_step is 'START': Ask for name, email, and start date. Then invoke 'send_welcome_email'.
2. If current_step is 'WELCOME_SENT': Inform the user you are paused waiting for documents to be signed.
3. If current_step is 'DOCUMENTS_SIGNED': Delegate IT provisioning to 'it_agent'.
4. If current_step is 'IT_PROVISIONED': Ask for the hardware tracking ID, then invoke 'check_hardware_status'.
5. If current_step is 'HARDWARE_DELIVERED': Invoke 'send_day_one_schedule'.
6. If current_step is 'COMPLETED': Confirm onboarding is done.

Always stay grounded in your tools and current state. Do not skip steps."""

Tool calls update - ADK's ToolContext.state

# app/tools.py

from google.adk.tools import ToolContext
from app.state_schema import OnboardingStep

def send_welcome_packet(
    name: str, email: str, start_date: str, tool_context: ToolContext
) -> dict:
    """Sends the welcome packet and transitions to WELCOME_SENT."""
    state = tool_context.state
    state["new_hire_details"] = {
        "name": name, "email": email, "start_date": start_date
    }
    state["current_step"] = OnboardingStep.WELCOME_SENT
    state["pending_signals"] = ["document_signed"]

    return {
        "status": "success",
        "message": f"Welcome packet sent to {name} ({email}). Documents pending signa"
    }

Save the STATE - ADK's DatabaseSessionService

# app/fast_api_app.py

from fastapi import FastAPI
from google.adk.cli.fast_api import get_fast_api_app
from google.adk.sessions.database_session_service import DatabaseSessionService

# Persistent SQLite session configuration
session_service_uri = "sqlite+aiosqlite:///sessions.db"

app: FastAPI = get_fast_api_app(
    agents_dir=AGENT_DIR,
    web=True,
    session_service_uri=session_service_uri,
)

Expose FastAPI endpoints

# app/fast_api_app.py

from pydantic import BaseModel
from app.resume_handler import OnboardingResumeHandler

db_session_service = DatabaseSessionService(db_url=session_service_uri)
webhook_runner = Runner(app=agent_app, session_service=db_session_service)
resume_handler = OnboardingResumeHandler(runner=webhook_runner)

class WebhookPayload(BaseModel):
    user_id: str
    session_id: str

@app.post("/webhooks/document_signed")
async def trigger_document_signed_webhook(payload: WebhookPayload) -> dict[str, str]:
    """Wakes up the onboarding agent when the employee signs their contract."""
    await resume_handler.receive_signed_documents_callback(
        user_id=payload.user_id, session_id=payload.session_id
    )
    return {"status": "success", "message": "Document signature processed, agent resumed."}
A Python code snippet for a FastAPI application is shown. An orange rectangle highlights the `app.post` decorator and the `trigger_document_signed_webhook` function definition, including its docstring, function body, and return statement.

The resume handler - wakes the agent and hydrates state

import json
import logging

from google.adk.runners import Runner
from google.genai import types
from app.state_schema import OnboardingStep

logger = logging.getLogger(__name__)

class OnboardingResumeHandler:
    def __init__(self, runner: Runner):
        self.runner = runner

    async def receive_signed_documents_callback(
        self, user_id: str, session_id: str
    ) -> None:
        """Hydrates the session, transitions to DOCUMENTS_SIGNED, and
        wakes the agent.
        """
        async for event in self.runner.run_async(
            user_id=user_id,
            session_id=session_id,
            new_message=types.Content(
                role="user",
                parts=[types.Part.from_text(
                    text="Resume onboarding: Contract has been signed"
                )],
            ),
            state_delta={
                "current_step": OnboardingStep.DOCUMENTS_SIGNED,
                "pending_signals": [],
            },
        ):
            logger.info(json.dumps({
                "severity": "INFO",
                "message": f"Wake-up execution event: {event}",
                "event": "runner_event",
                "session_id": session_id,
            }))
The Python code block has two orange rectangular highlights. The first highlight encircles the `async for event in self.runner.run_async(...)` call, specifically the `user_id`, `session_id`, and `new_message` arguments. The second highlight surrounds the `state_delta` argument, which sets `current_step` to `OnboardingStep.DOCUMENTS_SIGNED` and `pending_signals` to an empty list.

Remember !!! Delegate to Sub-Agent

# app/agent.py

from google.adk.agents import Agent
from google.adk.agents.callback_context import CallbackContext
from google.adk.models import Gemini
from app.state_schema import OnboardingStep
from app.tools import (
    send_welcome_packet,
    check_hardware_delivery,
    send_day_one_schedule,
)

async def initialize_onboarding_state(callback_context: CallbackContext):
    """Ensures all state machine keys are initialized to prevent erro
    state = callback_context.state
    if "current_step" not in state:
        state["current_step"] = OnboardingStep.START
    if "new_hire_details" not in state:
        state["new_hire_details"] = {}
    if "pending_signals" not in state:
        state["pending_signals"] = []

instruction = """You are an HR Onboarding Coordinator Agent.
Current Step: {current_step}
New Hire Details: {new_hire_details}
Pending Signals: {pending_signals}"""

Follow this state machine flow exactly:

  1. If current_step is 'START': Ask for name, email, and start date. T
  2. If current_step is 'WELCOME_SENT': Inform the user you are paused
  3. If current_step is 'DOCUMENTS_SIGNED': Delegate IT provisioning to
  4. If current_step is 'IT_PROVISIONED': Ask for the hardware tracking
  5. If current_step is 'HARDWARE_DELIVERED': Invoke 'send_day_one_sche
  6. If current_step is 'COMPLETED': Confirm onboarding is done.

Always stay grounded in your tools and current state. Do not skip ste

Screenshot of Python code in an IDE, showing an `initialize_onboarding_state` asynchronous function and related imports. Below the code, a multi-line agent instruction and a numbered list outline a state machine flow for onboarding, with one item highlighted by a red box.

Sub-agent: IT agent to provision software and hardware

# app/agent.py

from app.tools import provision_software_accounts

it_agent = Agent(
    name="it_agent",
    model=Gemini(model="gemini-3.1-flash-lite"),
    instruction="""You are an IT Provisioning Agent. Provision corporate
               accounts (email, Slack) for the new hire.

               Current Step: {current_step}
               New Hire Details: {new_hire_details}

               1. Collect the desired corporate username prefix.
               2. Invoke 'provision_software_accounts'.
               3. After provisioning, transfer control back to the coordinator."
    tools=[provision_software_accounts],
)

root_agent = Agent(
    name="hr_onboarding_coordinator",
    model=Gemini(model="gemini-3.1-flash-lite"),
    instruction=instruction,
    tools=[send_welcome_packet, check_hardware_delivery, send_day_one_
    sub_agents=[it_agent],
    before_agent_callback=initialize_onboarding_state,
)
A red rectangular box highlights the line `sub_agents=[it_agent],` in the Python code.

Transfer back to Root agent ( Co-ordinator) and wait for hardware delivery .........

Live Onboarding Desk

Current Workflow

Waiting for employee signature

  • Current step: WELCOME_SENT
  • Waiting on: document_signed
  • Artifacts: 1
  • ADK runner: session_ready

Active Case State

Waiting for employee signature: Paused until the employee signs the generated packet.

HR Command Center

Everything on this side is hydrated from backend case state.

  • Employee: Olivia Bennett, Product Manager, Platform Systems
  • Start Date: 2026-06-01

Employee Portal

Review the packet and sign it as Olivia.

Selected Artifact

Unsigned onboarding packet: welcome_packet.html is served by FastAPI from the local artifact store.

Action Needed

Signature: Click once to store a signed local packet and wake the ADK session.

Screenshot of the "Live Onboarding Desk" application interface, displaying an employee onboarding workflow paused at the "Waiting for employee signature" stage. The interface shows current workflow details, active case state, HR command center information for Olivia Bennett, and an employee portal section with an unsigned onboarding packet and an action for signature.

Live Onboarding Desk

Screenshot of a "Live Onboarding Desk" application interface.

Live Onboarding Desk

Screenshot of a web application interface for an onboarding desk, displaying a workflow for an employee signature, an HR command center, and an employee portal.

Waiting for employee signature

Screenshot of an onboarding workflow management system displaying a 'Waiting for employee signature' state, with sections for an HR command center and an employee portal showing an unsigned onboarding packet. A Google Calendar notification is visible in the bottom right corner of the screen.

about:blank

Screenshot of a Google Chrome browser interface with multiple open tabs and a bookmarks bar, displaying a blank page.

New Hire Onboarding Packet

Packet ID: ab5ec4f8-62b0-468a-bf26-2a03e5c9bcca

Session ID: ab5ec4f8-62b0-468a-bf26-2a03e5c9bcca

This local packet is generated for the demo workflow. It is not a legal contract or e-signature integration.

Generated locally

EMPLOYEE
Olivia Bennett
EMAIL
olivia.bennett@example.com
ROLE
Product Manager
START DATE
2026-06-01
TEAM
Platform Systems
MANAGER
Avery Stone

Welcome

Welcome to Platform Systems. This packet confirms the onboarding details that the HR onboarding coordinator will use to prepare access, equipment, and the Day One schedule.

Employee acknowledgements

  • I confirm that my onboarding profile is accurate.
  • I acknowledge that IT access and hardware delivery depend on completing this packet.
  • I understand this demo stores a local signed artifact for inspection by HR.

Signature

Pending employee signature

Live Onboarding Application

Screenshot of a dark-themed web application dashboard for employee onboarding. The dashboard shows an "Active Case State" of "Waiting for employee signature," an "HR command center" with details for employee Olivia Bennett, and an "Employee portal" with sections for an "Unsigned onboarding packet," "Signature," and "Hardware" delivery confirmation. An "Agent activity" and "Agent path" also display the progress of the onboarding process.

Day One Schedule for Olivia Bennett

Screenshot of a web application dashboard displaying an employee onboarding process, showing agent activity, agent path, a detailed Day One schedule for Olivia Bennett, hardware delivery status, employee state, and results.

Live Onboarding Desk

Screenshot of a "Live Onboarding Desk" dashboard interface, displaying current workflow status as "Waiting for employee signature", active case state, an HR command center with agent details (Olivia Bennett), and an employee portal showing an "Unsigned onboarding packet" and a "Signature" option.

Loading...

Loading...

Screenshot of docs.google.com showing a loading state.

Live Onboarding Desk

Long-running ADK agents that can pause and resume

Backend case live

Waiting for employee signature

Current step
WELCOME_SENT
Waiting on
<

Final Steps

  • Evaluate the Agent with eval dataset or User simulations
  • Online Evaluation using Agent Platform observability
  • Security guardrails via Model armor
  • Logging via OTel

Resources

Three QR codes providing links to the ADK Blog, Github Repo, and ADK Community.

Technologies & Tools

  • ADK
  • Agent CLI
  • Agent Runtime
  • AlloyDB
  • Cloud Run
  • Cloud SQL
  • FastAPI
  • Go
  • Java
  • Kubernetes
  • Model Armor
  • Python
  • SQLite
  • Terraform
  • User simulations

Standards & Specs

  • OpenTelemetry

Concepts & Methods

  • Multi-agent systems
  • Prompt injection

Organisations & Products

  • DocuSign
  • GitHub
  • Google Cloud