Starting April 29, 2025, Gemini 1.5 Pro and Gemini 1.5 Flash models are not available in projects that have no prior usage of these models, including new projects. For details, see Model versions and lifecycle.
Stay organized with collections
Save and categorize content based on your preferences.
This page describes how you can connect an Agent Development Kit (ADK) agent with Vertex AI Agent Engine Sessions and use managed sessions in the local and production environment.
To access Vertex AI Agent Engine Sessions, you first need to create an Vertex AI Agent Engine instance. You don't need to deploy any code to start using Sessions. Without code deployment, creating an Vertex AI Agent Engine instance only takes a few seconds.
importvertexaifromvertexaiimportagent_engines# Create an agent engine instanceagent_engine=agent_engines.create()
Develop your ADK agent
To create your ADK agent, follow the instructions in Agent Development Kit, or use the following code to create an agent that greets a user with fixed greetings:
fromgoogleimportadkdefgreetings(query:str):"""Tool to greet user."""if'hello'inquery.lower():return{"greeting":"Hello, world"}else:return{"greeting":"Goodbye, world"}# Define an ADK agentroot_agent=adk.Agent(model="gemini-2.0-flash",name='my_agent',instruction="You are an Agent that greet users, always use greetings tool to respond.",tools=[greetings])
Set up the ADK runner
The ADK Runtime orchestrates the execution of your agents, tools, and callbacks, and orchestrates calls to read and write sessions. Initialize the Runner with VertexAiSessionService, which connects with Vertex AI Agent Engine Sessions.
fromgoogle.adk.sessionsimportVertexAiSessionServiceapp_name="AGENT_ENGINE_ID"user_id="USER_ID"# Create the ADK runner with VertexAiSessionServicesession_service=VertexAiSessionService("PROJECT_ID","LOCATION")runner=adk.Runner(agent=root_agent,app_name=app_name,session_service=session_service)# Helper method to send query to the runnerdefcall_agent(query,session_id,user_id):content=types.Content(role='user',parts=[types.Part(text=query)])events=runner.run(user_id=user_id,session_id=session_id,new_message=content)foreventinevents:ifevent.is_final_response():final_response=event.content.parts[0].textprint("Agent Response: ",final_response)
Replace the following:
PROJECT_ID: Your project ID.
LOCATION: Your region.
AGENT_ENGINE_ID: The resource ID of a Vertex AI Agent Engine instance.
For deployed agents, the resource ID is listed as the GOOGLE_CLOUD_AGENT_ENGINE_ID environment variable
For local agents, you can retrieve the resource ID using agent_engine.name.split("/")[-1].
USER_ID: A non-empty unique identifier for the user, with a maximum length of 128 characters.
Interact with your agent
After defining your agent and setting up Vertex AI Agent Engine Sessions, you can interact with your agent to check that the session history and states persist.
ADK UI
Test your agent with the ADK user interface and connect to Vertex AI Agent Engine Session using the session_db_url command line option:
agent_engine_id="AGENT_ENGINE_ID"adk web --session_db_url=agentengine://${agent_engine_id}# Sample output+-----------------------------------------------------------------------------+| ADK Web Server started || || For local testing, access at http://localhost:8000. |+-----------------------------------------------------------------------------+INFO: Application startup complete.INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Python
Use ADK Python code to manage sessions and states.
Create a session and query the agent
Use the following code to create a session and send a query to your agent:
After the session is created and passed to the runner, ADK uses the session to store events from the current interaction. You can also resume a previous session by providing the ID for that session.
List existing sessions
List all existing sessions associated with a given user ID.
# List sessionsawaitsession_service.list_sessions(app_name=app_name,user_id=user_id)# ListSessionsResponse(session_ids=['1122334455', '9988776655'])
Manage session states
States hold information that the agent needs for a conversation. You can provide an initial state as a dictionary when you create a session:
# Create a session with statesession=awaitsession_service.create_session(app_name=app_name,user_id=user_id,state={'key':'value'})print(session.state['key'])# value
To update the session state outside the runner, append a new event to the session using state_delta:
fromgoogle.adk.eventsimportEvent,EventActionsimporttime# Define state changesstate_changes={'key':'new_value'}# Create event with actionsactions_with_update=EventActions(state_delta=state_changes)system_event=Event(invocation_id="invocation_id",author="system",# Or 'agent', 'tool' etc.actions=actions_with_update,timestamp=time.time())# Append the eventawaitsession_service.append_event(session,system_event)# Check updated stateupdated_session=awaitsession_service.get_session(app_name=app_name,user_id=user_id,session_id=session.id)# State is updated to new valueprint(updated_session.state['key'])# new_value
Delete a session
Delete a specific session associated with a user ID:
AGENT: The application that implements the query / stream_query method (for example, AdkApp for an ADK agent). For more information, see Deployment considerations.
Clean up
To clean up all resources used in this project, you can delete the Vertex AI Agent Engine instance along with its child resources:
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-28 UTC."],[],[],null,["# Manage sessions with Agent Development Kit\n\n| **Preview**\n|\n|\n| This feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\nThis page describes how you can connect an Agent Development Kit (ADK) agent with Vertex AI Agent Engine Sessions and use managed sessions in the local and production environment.\n| **Note:** If you've already followed the instructions in [Develop an Agent Development Kit agent](/vertex-ai/generative-ai/docs/agent-engine/develop/adk), you don't need to follow this guide, since the `AdkApp` template is already connected to Vertex AI Agent Engine Sessions through `session_service`.\n\nBefore you begin\n----------------\n\nMake sure your environment is set up by following\nthe [Get the required roles](/vertex-ai/generative-ai/docs/agent-engine/set-up#get_the_required_roles) and [Authentication](/vertex-ai/generative-ai/docs/agent-engine/set-up#authentication) steps in [Set up your environment](/vertex-ai/generative-ai/docs/agent-engine/set-up).\n\nCreate a Vertex AI Agent Engine instance\n----------------------------------------\n\nTo access Vertex AI Agent Engine Sessions, you first need to create an Vertex AI Agent Engine instance. You don't need to deploy any code to start using Sessions. Without code deployment, creating an Vertex AI Agent Engine instance only takes a few seconds. \n\n import https://cloud.google.com/python/docs/reference/vertexai/latest/\n from vertexai import agent_engines\n\n # Create an agent engine instance\n agent_engine = agent_engines.create()\n\nDevelop your ADK agent\n----------------------\n\n| **Note:** Make sure you have installed ADK version **1.0.0** or later. This version is included in `google-cloud-aiplatform[adk,agent_engine]`.\n\nTo create your ADK agent, follow the instructions in [Agent Development Kit](https://google.github.io/adk-docs/), or use the following code to create an agent that greets a user with fixed greetings: \n\n from google import adk\n\n def greetings(query: str):\n \"\"\"Tool to greet user.\"\"\"\n if 'hello' in query.lower():\n return {\"greeting\": \"Hello, world\"}\n else:\n return {\"greeting\": \"Goodbye, world\"}\n\n # Define an ADK agent\n root_agent = adk.Agent(\n model=\"gemini-2.0-flash\",\n name='my_agent',\n instruction=\"You are an Agent that greet users, always use greetings tool to respond.\",\n tools=[greetings]\n )\n\nSet up the ADK runner\n---------------------\n\nThe [ADK Runtime](https://google.github.io/adk-docs/runtime/) orchestrates the execution of your agents, tools, and callbacks, and orchestrates calls to read and write sessions. Initialize the Runner with [`VertexAiSessionService`](https://google.github.io/adk-docs/sessions/session/#sessionservice-implementations), which connects with Vertex AI Agent Engine Sessions. \n\n from google.adk.sessions import VertexAiSessionService\n\n app_name=\"\u003cvar translate=\"no\"\u003eAGENT_ENGINE_ID\u003c/var\u003e\"\n user_id=\"\u003cvar translate=\"no\"\u003eUSER_ID\u003c/var\u003e\"\n\n # Create the ADK runner with VertexAiSessionService\n session_service = VertexAiSessionService(\n \"\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\", \"\u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e\")\n runner = adk.Runner(\n agent=root_agent,\n app_name=app_name,\n session_service=session_service)\n\n # Helper method to send query to the runner\n def call_agent(query, session_id, user_id):\n content = types.Content(role='user', parts=[types.Part(text=query)])\n events = runner.run(\n user_id=user_id, session_id=session_id, new_message=content)\n\n for event in events:\n if event.is_final_response():\n final_response = event.content.parts[0].text\n print(\"Agent Response: \", final_response)\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: Your project ID.\n\n- \u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e: Your region.\n\n- \u003cvar translate=\"no\"\u003eAGENT_ENGINE_ID\u003c/var\u003e: The resource ID of a Vertex AI Agent Engine instance.\n\n - For deployed agents, the resource ID is listed as the `GOOGLE_CLOUD_AGENT_ENGINE_ID` environment variable\n\n - For local agents, you can retrieve the resource ID using `agent_engine.name.split(\"/\")[-1]`.\n\n- \u003cvar translate=\"no\"\u003eUSER_ID\u003c/var\u003e: A non-empty unique identifier for the user, with a maximum length of 128 characters.\n\nInteract with your agent\n------------------------\n\nAfter defining your agent and setting up Vertex AI Agent Engine Sessions, you can interact with your agent to check that the session history and states persist. \n\n### ADK UI\n\nTest your agent with the ADK user interface and connect to Vertex AI Agent Engine Session using the `session_db_url` command line option: \n\n agent_engine_id=\"\u003cvar translate=\"no\"\u003eAGENT_ENGINE_ID\u003c/var\u003e\"\n\n adk web --session_db_url=agentengine://${agent_engine_id}\n\n # Sample output\n +-----------------------------------------------------------------------------+\n | ADK Web Server started |\n | |\n | For local testing, access at http://localhost:8000. |\n +-----------------------------------------------------------------------------+\n\n INFO: Application startup complete.\n INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)\n\n### Python\n\nUse ADK Python code to manage sessions and states.\n\n### Create a session and query the agent\n\nUse the following code to create a session and send a query to your agent: \n\n # Create a session\n session = await session_service.create_session(\n app_name=app_name,\n user_id=user_id)\n\n call_agent(\"Hello!\", session.id, user_id)\n # Agent response: \"Hello, world\"\n\n call_agent(\"Thanks!\", session.id, user_id)\n # Agent response: \"Goodbye, world\"\n\nAfter the session is created and passed to the runner, ADK uses the session to store events from the current interaction. You can also resume a previous session by providing the ID for that session.\n\n### List existing sessions\n\nList all existing sessions associated with a given user ID. \n\n # List sessions\n await session_service.list_sessions(app_name=app_name,user_id=user_id)\n\n # ListSessionsResponse(session_ids=['1122334455', '9988776655'])\n\n### Manage session states\n\nStates hold information that the agent needs for a conversation. You can provide an initial state as a dictionary when you create a session: \n\n # Create a session with state\n session = await session_service.create_session(\n app_name=app_name,\n user_id=user_id,\n state={'key': 'value'})\n\n print(session.state['key'])\n # value\n\nTo update the session state outside the runner, append a new event to the session using `state_delta`: \n\n from google.adk.events import Event, EventActions\n import time\n\n # Define state changes\n state_changes = {'key': 'new_value'}\n\n # Create event with actions\n actions_with_update = EventActions(state_delta=state_changes)\n system_event = Event(\n invocation_id=\"invocation_id\",\n author=\"system\", # Or 'agent', 'tool' etc.\n actions=actions_with_update,\n timestamp=time.time()\n )\n\n # Append the event\n await session_service.append_event(session, system_event)\n\n # Check updated state\n updated_session = await session_service.get_session(\n app_name=app_name,\n user_id=user_id,\n session_id=session.id)\n # State is updated to new value\n print(updated_session.state['key'])\n # new_value\n\n### Delete a session\n\nDelete a specific session associated with a user ID: \n\n await session_service.delete_session(app_name=app_name, user_id=user_id, session_id=session.id)\n\nDeploy your agent to Vertex AI Agent Engine\n-------------------------------------------\n\nAfter you test your agent locally, you can deploy the agent to production by updating the Vertex AI Agent Engine instance with parameters: \n\n agent_engines.update(resource_name=agent_engine.name, agent_engine=\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eAGENT\u003c/span\u003e\u003c/var\u003e, requirements=REQUIREMENTS)\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003eAGENT\u003c/var\u003e: The application that implements the `query / stream_query` method (for example, `AdkApp` for an ADK agent). For more information, see [Deployment considerations](/vertex-ai/generative-ai/docs/agent-engine/deploy#deployment-considerations).\n\nClean up\n--------\n\nTo clean up all resources used in this project, you can delete the Vertex AI Agent Engine instance along with its child resources: \n\n agent_engine.delete(force=True)\n\nWhat's next\n-----------\n\n- [Manage sessions using API calls](/vertex-ai/generative-ai/docs/agent-engine/sessions/manage-sessions-api)."]]