aiml

Lesson 19 of 20Module 5

Deploy an ADK agent to Agent Runtime

Deploy an ADK agent with the native CLI, call Agent Runtime session and streaming methods, and distinguish endpoint mistakes from user-session errors.

Prerequisites

The course’s managed-session lesson, a Google Cloud project with deployment approval, gcloud and jq.

By the end, you can

  • Deploy an ADK agent package with the native Agent Runtime command.
  • Use ordinary and streaming runtime methods with the matching user and session.
  • Distinguish SDK session checks from application authorization.
Runtime
Python 3.12+, gcloud and jq; Google Cloud access for the recorded integration
Dependencies
google-adk[gcp] 2.12.0; google-cloud-aiplatform 2.6.0

Lab code, tests and fixtures (ZIP, 17 KB)Quiz check your understanding

Progress is saved in this browser.

adk deploy agent_engine deploys an ADK agent directory to Agent Runtime, the managed runtime within Google Cloud Agent Platform. The command copies the agent source, reads .agent_engine_config.json, generates requirements.txt and creates a new Agent Runtime instance, or updates an existing one when you pass --agent_engine_id. Unlike the previous lesson’s generated application project, this path starts from the agent directory and an ADK deployment configuration. Here we inspect the recorded deployment and use the runtime REST methods to create sessions, stream answers and add a completed conversation to Memory Bank.

The agent_engine CLI subcommand and the reasoningEngines REST resource keep their earlier names. Both still refer to Agent Runtime.

When you need this. A service already has an ADK agent package and its own build conventions. You want the managed runtime without adopting the Agents CLI’s generated application layout. The deployment is only half the interface: the caller also needs to choose the right runtime method and keep user and session IDs associated.

One recorded deployed-agent conversationRecorded output (excerpt) · textFull output
# 1. Connection check: the methods this deployment serves
get_session, list_sessions, create_session, delete_session, async_get_session, async_list_sessions, async_create_session, async_delete_session, async_add_session_to_memory, async_search_memory, async_save_artifact, async_load_artifact, async_list_artifact_keys, async_delete_artifact, async_list_versions, async_list_artifact_versions, async_get_artifact_version, stream_query, async_stream_query, streaming_agent_run_with_events

# 2. Conversation 1, in a new session
# 2 s
session 5114326006718529536
> I run docuctl 1.x. How do I undo release r42 in production?
# 6 s
call   read_page {"page":"rollback"}
result read_page
answer In docuctl 1.x, use the `release revert` command:

```bash
docuctl release revert r42
```

Note that this rolls back to the previous state without rebuilding, but database migrations are not automatically reverted—if r42 ran migrations, you must write a new migration to reverse them.
data flowreturnartifact hand-offfailureagent.pyADK deploy configadk deploy agent_enginesourcefilesAdkAppAgent RuntimeRunner + LlmAgentdeployquery.sh:queryordinary methods:streamQueryasync_stream_queryJSONstreamwrong method surfacerecorded failed requestVertexAiSessionServiceeventsdata flowreturnartifact hand-offfailureagent.pyADK deploy configadk deploy agent_enginesource filesAdkAppAgent Runtime / Runnerdeployquery.sh:queryordinary:streamQuerystreamingJSONstreamstream method on queryrequest failswrong surfaceVertexAiSessionServiceevents
ADK packages the agent and deployment configuration for Agent Runtime. The caller uses query for ordinary methods and streamQuery for the streaming agent method. Sending a streaming method to query failed in the recorded run. User/session association is a service check; the caller still supplies user_id and must authorize it.

Lab setup. Download the complete lab ZIP, extract it and open a terminal in adk-agent-runtime/. Keep its code, tests and fixtures together. Create the pinned environment for local checks:

Create the lab environmentTerminal · bash
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-lock.txt

You can read the saved cloud results without creating any Google Cloud resources. To run the cloud steps yourself, you need the project access listed in the prerequisites.

1. Package the same docs assistant for the managed runtime

The agent is still the docuctl docs assistant. Its model uses a global endpoint, while the runtime and its managed data stay in the selected region. The configuration file sets resource limits and the Memory Bank topic from the managed-services lesson:

docs_helper/.agent_engine_config.jsonSource · jsonDownload
{
  "display_name": "docs-helper",
  "description": "docuctl docs assistant",
  "labels": {"aiml-lesson": "deploy-an-adk-agent-to-agent-runtime"},
  "min_instances": 0,
  "max_instances": 1,
  "resource_limits": {"cpu": "1", "memory": "1Gi"},
  "context_spec": {"memory_bank_config": {
    "ttl_config": {"default_ttl": "86400s"},
    "customization_configs": [{"memory_topics": [
      {"managed_memory_topic": {"managed_topic_enum": "USER_PREFERENCES"}},
      {"custom_memory_topic": {"label": "tool_versions",
        "description": "Which version of a CLI, SDK or service the developer runs, for example 'runs docuctl 1.x'."}}
    ]}]
  }}
}

These values are settings, not measured capacity. Check the official service limits and your workload before you change them. The saved output comes from deploying this agent source with the lab’s pinned dependencies.

2. Deploy with the native ADK command

Deploy the agent directory with adk deploy agent_engine. ADK copies the source, reads .agent_engine_config.json, generates requirements.txt and creates the Agent Runtime instance:

Deploy the agent to Agent RuntimeTerminal · bash
adk deploy agent_engine --project $GOOGLE_CLOUD_PROJECT \
  --region us-central1 --display_name docs-helper docs_helper
Recorded adk deploy agent_engine outputRecorded output (excerpt) · textFull output
$ /private/tmp/docuctl-adk-venv/bin/adk deploy agent_engine --project vertex-ai-experminent --region us-central1 --display_name docuctl-runtime-3c36cf84 --service_account docuctl-rt-3c36cf84@vertex-ai-experminent.iam.gserviceaccount.com --agent_engine_config_file /private/tmp/docuctl-recordings/runtime-config.json --temp_folder /private/tmp/docuctl-runtime-build-3c36cf84 docs_helper
Copying agent source code...
Copying agent source code complete.
Resolving files and dependencies...
Reading agent platform config from /private/tmp/docuctl-recordings/runtime-config.json
Overriding display_name in agent platform config with docuctl-runtime-3c36cf84
Creating /private/tmp/docuctl-runtime-build-3c36cf84/agents/docs_helper/requirements.txt...
Using google-adk[a2a]==2.12.0 in requirements
Created /private/tmp/docuctl-runtime-build-3c36cf84/agents/docs_helper/requirements.txt
Initializing Agent Platform client...
Agent Platform client initialized with project and region.
Deploying to Agent Platform...
/private/tmp/site-teaching-adk-test-venv/lib/python3.12/site-packages/google/auth/_default.py:113: UserWarning: Your application has authenticated using end user credentials from Google Cloud SDK without a quota project. You might receive a "quota exceeded" or "API not enabled" error. See the following page for troubleshooting: https://cloud.google.com/docs/authentication/adc-troubleshooting/user-creds. 
  warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)
Created a new instance: projects/913703049174/locations/us-central1/reasoningEngines/3761845168894902272
Creating Dockerfile...
Dockerfile created at /private/tmp/docuctl-runtime-build-3c36cf84/Dockerfile.

--agent_engine_id selects an existing instance to update; without it, the command creates a new instance. The installed help marks --staging_bucket as deprecated and unused. Check both flags when you adapt an older deployment script.

The recorded run used an existing project with deployment approval. Read its output before you adapt the command to another project or region.

3. Call session methods and stream an agent turn

query.sh obtains an access token from gcloud, calls ordinary methods through :query, and sends the streaming method to :streamQuery?alt=sse. It prints the available methods before using them, so an SDK or deployment change is visible to the caller.

query.shSource · bashDownload
#!/usr/bin/env bash
# Talk to the deployed docs assistant over the Agent Runtime REST API.
# Usage: PROJECT_ID=... RESOURCE_ID=... ./query.sh
set -euo pipefail
LOCATION_ID=${LOCATION_ID:-us-central1}
URL="https://${LOCATION_ID}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION_ID}/reasoningEngines/${RESOURCE_ID}"
AUTH="Authorization: Bearer $(gcloud auth print-access-token)"

query() {  # query CLASS_METHOD INPUT_JSON: one JSON response
  curl -s -H "$AUTH" -H "Content-Type: application/json" "$URL:query" \
    -d "{\"class_method\": \"$1\", \"input\": $2}"
}
stream() {  # stream USER SESSION MESSAGE: one JSON event per line
  curl -s -H "$AUTH" -H "Content-Type: application/json" "$URL:streamQuery?alt=sse" \
    -d "$(jq -n --arg u "$1" --arg s "$2" --arg m "$3" \
      '{class_method: "async_stream_query", input: {user_id: $u, session_id: $s, message: $m, run_config: {max_llm_calls: 4}}}')"
}
show() {  # print tool calls and the final text of a stream
  jq -r '.content.parts[]? | if .function_call then "call   \(.function_call.name) \(.function_call.args|tojson)"
    elif .function_response then "result \(.function_response.name)"
    elif (.text and (.thought|not)) then "answer \(.text)" else empty end'
}
timed() { local s=$(date +%s); "$@"; echo "# $(( $(date +%s) - s )) s" >&2; }

echo "# 1. Connection check: the methods this deployment serves"
curl -s -H "$AUTH" "$URL" | jq -r '[.spec.classMethods[].name] | join(", ")'

echo; echo "# 2. Conversation 1, in a new session"
S1=$(timed query async_create_session '{"user_id": "dana"}' | jq -r '.output.id')
echo "session $S1"
echo "> I run docuctl 1.x. How do I undo release r42 in production?"
timed stream dana "$S1" "I run docuctl 1.x. How do I undo release r42 in production?" | show

echo; echo "# 3. Add the finished session to Memory Bank"
SESSION=$(query async_get_session "{\"user_id\": \"dana\", \"session_id\": \"$S1\"}" | jq -c '.output')
query async_add_session_to_memory "{\"session\": $SESSION}" | jq -c '.'
for i in $(seq 1 40); do  # memories are extracted in the background
  FOUND=$(query async_search_memory '{"user_id": "dana", "query": "docuctl version"}' | jq -c '[.output.memories[]?.content.parts[0].text]')
  [ "$FOUND" != "[]" ] && break; sleep 5
done
echo "memories after about $(( i * 5 )) s: $FOUND"

echo; echo "# 4. Conversation 2, in another new session"
S2=$(query async_create_session '{"user_id": "dana"}' | jq -r '.output.id')
echo "> How do I undo the last production release?"
timed stream dana "$S2" "How do I undo the last production release?" | show

The wrapper’s input is {class_method, input}. async_create_session returns an ID; async_stream_query needs that ID, the user ID and a message. A stream is not an ordinary JSON return value, so streaming methods use a separate endpoint. Keep request construction and response parsing explicit when diagnosing a failed call.

A streaming method on the ordinary query surface. Select the endpoint from the runtime’s registered streaming operations.

A missing user session. The SDK raises an error when its session service finds no matching conversation. The local test uses the in-memory session service; the saved cloud log shows the deployed runtime’s error.

Recorded endpoint and user-session failuresRecorded output (excerpt) · textFull output
# 1. A streaming method sent to :query
{"code":400,"message":"Reasoning Engine Execution failed.\nPlease refer to our documentation (https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/troubleshooting/use) for checking logs and other troubleshooting tips.\nError Details: Internal Server Error","status":"FAILED_PRECONDITION"}

# 2. Dana's session id sent with another user id


# Actual service error summaries
ValueError: Session 4024454896894869504 does not belong to user lee.
ValueError: [TypeError("'async_generator' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
TypeError: vars() argument must have __dict__ attribute
TypeError: 'async_generator' object is not iterable

Sending async_stream_query to :query produced a failed request and a service log about an async generator. The fix is the streaming endpoint, not a retry of the same JSON request. A request that sent the session ID with a different user ID also failed, as the service log shows.

The user-ID check stops accidental mixing of sessions, but it does not authenticate anyone. An authorized runtime caller supplies the user_id field. Your application must set that field from its authenticated user, not from a value that a client sends.

Offline SDK and configuration checksRecorded output · textDownload
test_a_missing_user_session_does_not_return_another_users_history (test_runtime.RuntimeConfiguration.test_a_missing_user_session_does_not_return_another_users_history) ... ok
test_deployment_resource_limits_are_explicit (test_runtime.RuntimeConfiguration.test_deployment_resource_limits_are_explicit) ... ok
test_model_and_regional_services_can_use_different_locations (test_runtime.RuntimeConfiguration.test_model_and_regional_services_can_use_different_locations) ... ok
test_read_page_rejects_a_path_outside_the_docs (test_runtime.RuntimeConfiguration.test_read_page_rejects_a_path_outside_the_docs) ... ok
test_streaming_method_is_registered_on_the_stream_surface (test_runtime.RuntimeConfiguration.test_streaming_method_is_registered_on_the_stream_surface) ... ok

----------------------------------------------------------------------
Ran 5 tests in 0.381s

OK

4. Add the completed conversation to Memory Bank

After the first turn, the script retrieves the session and calls async_add_session_to_memory. It polls async_search_memory before opening another session. The second answer used the recalled CLI version, as the saved output shows:

Recorded memory ingestion and new conversationRecorded output (excerpt) · textFull output
 Add the finished session to Memory Bank
{"output":null}
memories after about 10 s: ["I run docuctl 1.x."]

# 4. Conversation 2, in another new session
> How do I undo the last production release?
# 6 s
call   load_memory {"query":"docuctl version"}
call   read_page {"page":"rollback"}
result load_memory
result read_page
answer Since you are using docuctl 1.x, use `docuctl release revert <release>` to undo a release and point traffic back to an earlier release ID. 

Note that database migrations are not automatically rolled back; any migrations must be reversed with a new migration.

This is the same managed-memory mechanism as in the earlier lesson; here the managed runtime exposes it through registered methods. An ingestion response does not mean the memory is searchable yet. The polling loop stops after a fixed number of tries. Report an empty result to the caller instead of treating it as remembered data.

Remove only the lesson deployment

The recorded instance was deleted with force=true, which also removed its sessions and memories. For your own run, check the project, region, resource ID and lesson label before you delete anything, then wait for the delete operation to finish. A deployment name alone does not show that you own the resource. The saved delete output shows the completed deletion and the HTTP 404 that confirms it.

What’s next

Deploy an ADK agent to Cloud Run uses the API server’s HTTP interface behind Cloud Run IAM and makes the session-store choice explicit.

Read the unchanged docs assistant
docs_helper/agent.pySource · pythonDownload
"""The docs assistant on Gemini Enterprise Agent Platform: Gemini through Vertex, recall through Memory Bank."""
import os
from pathlib import Path

from google.adk import Agent
from google.adk.models.google_llm import Gemini
from google.adk.tools import load_memory
from google.genai import types

DOCS = Path(__file__).resolve().parent / "docs"
PAGES = sorted(p.stem for p in DOCS.glob("*.md"))
# The recorded run uses global for this model. Sessions and Memory Bank stay regional
# (GOOGLE_CLOUD_LOCATION), so the model client gets its own location.
MODEL_LOCATION = os.environ.get("DOCS_MODEL_LOCATION", "global")


def read_page(page: str) -> dict:
    """Read one page of the docuctl documentation: config, deploy, rollback or tokens."""
    if page not in PAGES:
        return {"error": f"No page {page!r}. Pages: {', '.join(PAGES)}."}
    return {"page": page, "text": (DOCS / f"{page}.md").read_text(encoding="utf-8")}


INSTRUCTION = """You answer questions from developers about docuctl, the team's deploy CLI.
Read the relevant page with read_page before you answer. Answers depend on the developer's
docuctl major version (1.x or 2.x). If the developer has not said it in this conversation,
call load_memory to look for it in earlier conversations before you ask. Keep the answer
under 80 words."""

root_agent = Agent(
    name="docs_helper",
    model=Gemini(model="gemini-3.8-flash", client_kwargs={"location": MODEL_LOCATION}),
    instruction=INSTRUCTION,
    tools=[read_page, load_memory],
    generate_content_config=types.GenerateContentConfig(
        temperature=0.2, max_output_tokens=1024, thinking_config=types.ThinkingConfig(thinking_level="low")),
)

Check your understanding

A registered async_stream_query method fails when sent to :query. What should you correct first?

Choose one answer, then check your reasoning.

Read the explanation

The script routes streaming operations through :streamQuery?alt=sse. An async stream is not an ordinary JSON query result.

References

Official documentation and installed ADK / Google Cloud AI Platform APIs checked October 22, 2026.

Written by Arjun Prabhulal.

Module 5

Deploy agents on Google Cloud