This sample shows how to persist ADK sessions and state in MongoDB using the
community MongoSessionService.
- Python 3.9+ (Python 3.11+ recommended)
- A running MongoDB instance (local or Atlas) and a connection string with create/read/write permissions
- ADK and ADK Community installed
- Google API key for the sample agent (Gemini), set as
GOOGLE_API_KEY
pip install google-adk google-adk-community python-dotenvCreate a .env in this directory:
# Required: Google API key for the agent
GOOGLE_API_KEY=your-google-api-key
# Recommended: Mongo connection string (Atlas or local)
MONGODB_URI=mongodb+srv://<user>:<password>@<cluster-url>/Note: Keep your Mongo credentials out of source control. The sample loads the connection string from the MONGODB_URI environment variable, which is loaded from the .env file at runtime.
By default the sample uses adk_sessions_db. Collections are created
automatically if they do not exist.
python main.pymain.py:
- Creates a
MongoSessionServicewith a connection string - Creates a session for the demo user
- Runs the
financial_advisor_agentwithRunner.run_async - Prints the agent's final response
import os
from google.adk.runners import Runner
from google.genai import types
from google.adk_community.sessions import MongoSessionService
session_service = MongoSessionService(
connection_string=os.environ.get("MONGODB_URI")
)
await session_service.create_session(
app_name="my_app", user_id="user1", session_id="demo"
)
runner = Runner(app_name="my_app", agent=your_agent, session_service=session_service)
query = "Hello, can you help me with my account?"
content = types.Content(role="user", parts=[types.Part(text=query)])
async for event in runner.run_async(
user_id="user1",
session_id="demo",
new_message=content,
):
if event.is_final_response():
print(event.content.parts[0].text)If you already have an AsyncMongoClient, pass it instead of a connection
string:
from pymongo import AsyncMongoClient
client = AsyncMongoClient(host="localhost", port=27017)
session_service = MongoSessionService(client=client)MongoSessionService writes to two collections (configurable):
sessions: conversation history and session-level statesession_state: shared app/user state across sessions
Indexes are created on first use:
- Unique session identity:
(app_name, user_id, id) - Last update for recency queries:
(app_name, user_id, last_update_time)
mongodb_service/
├── main.py # Runs the sample with Mongo-backed sessions
├── mongo_service_agent/
│ ├── __init__.py # Agent package init
│ └── agent.py # Financial advisor agent with two tools
└── README.md # This file
The agent (mongo_service_agent/agent.py) includes:
get_invoice_status(service)tool for simple invoice lookupscalculate_service_tax(amount)tool for tax calculations- Gemini model (
gemini-2.0-flash) with instructions to route to the tools
What is the status of my university invoice? Also, calculate the tax for a service amount of 9500 MXN.
database_name(str, defaultadk_sessions_db): Mongo database to store session data.connection_string(str, optional): Mongo URI (mutually exclusive withclient)client(AsyncMongoClient, optional): Provide your own client/connection poolsession_collection(str, defaultsessions): Collection for session docsstate_collection(str, defaultsession_state): Collection for shared statedefault_app_name(str, optional): Fallback app name when not provided per call (defaults toadk-mongo-session-service)
- Use
runner.run_async(as inmain.py) to keep the Mongo client on the same event loop and avoid loop-bound client errors. - For production, prefer environment variables or secrets managers for the connection string and database credentials.