-
Notifications
You must be signed in to change notification settings - Fork 54
Add MongoDB session service integration for ADK community #32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jorge-jrzz
wants to merge
15
commits into
google:main
Choose a base branch
from
jorge-jrzz:feat/31-add-mongo-integration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
34aa299
feat: add MongoDB-backed session service to ADK community extensions
jorge-jrzz 34ee137
docs: add MongoDB session service sample and agent implementation exa…
d-clemc a8fb905
test: add unit tests for MongoSessionService functionality
jorge-jrzz 5b657ad
refactor: improve docstrings and streamline agent initialization in m…
jorge-jrzz eb9fb9d
fix: Attend Gemini Code Review
jorge-jrzz 3f151d9
fix: Enhance MongoDB session service sample and error handling
jorge-jrzz e34923e
fix: Update default app name in README and improve tax calculation in…
jorge-jrzz 072fa5f
fix: Remove unnecessary events field from session documents and updat…
jorge-jrzz 23693c8
fix: Use get method for state deltas and session document fields to a…
jorge-jrzz d4819aa
fix: Change database_name parameter type to str in MongoSessionServic…
jorge-jrzz a719211
Update src/google/adk_community/sessions/mongo_session_service.py
jorge-jrzz a22ce94
Update src/google/adk_community/sessions/mongo_session_service.py
jorge-jrzz 599c65e
Update src/google/adk_community/sessions/mongo_session_service.py
jorge-jrzz 63a7120
Update src/google/adk_community/sessions/__init__.py
jorge-jrzz a1b7987
refactor: Simplify session_id assignment in MongoSessionService
jorge-jrzz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| # MongoDB Session Service Sample | ||
|
|
||
| This sample shows how to persist ADK sessions and state in MongoDB using the | ||
| community `MongoSessionService`. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - 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` | ||
|
|
||
| ## Setup | ||
|
|
||
| ### 1. Install dependencies | ||
|
|
||
| ```bash | ||
| pip install google-adk google-adk-community | ||
| ``` | ||
|
|
||
| ### 2. Configure environment variables | ||
|
|
||
| Create a `.env` in this directory: | ||
|
|
||
| ```bash | ||
| # 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 reads | ||
| the URI directly in `main.py`; you can swap in `os.environ["MONGODB_URI"]` to | ||
| load it from the environment. | ||
|
jorge-jrzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| ### 3. Pick a database name | ||
|
|
||
| By default the sample uses `adk_sessions_db`. Collections are created | ||
| automatically if they do not exist. | ||
|
|
||
| ## Usage | ||
|
|
||
| ### Option 1: Run the included sample | ||
|
|
||
| ```bash | ||
| python main.py | ||
| ``` | ||
|
|
||
| `main.py`: | ||
| - Creates a `MongoSessionService` with a connection string | ||
| - Creates a session for the demo user | ||
| - Runs the `financial_advisor_agent` with `Runner.run_async` | ||
| - Prints the agent's final response | ||
|
|
||
| ### Option 2: Use `MongoSessionService` with your own runner | ||
|
|
||
| ```python | ||
| import os | ||
| from google.adk.runners import Runner | ||
| from google.adk_community.sessions import MongoSessionService | ||
|
|
||
| session_service = MongoSessionService( | ||
| connection_string=os.environ["MONGODB_URI"] | ||
| ) | ||
|
|
||
| await session_service.create_session( | ||
| app_name="my_app", user_id="user1", session_id="demo" | ||
| ) | ||
|
|
||
| runner = Runner(app_name="my_app", agent=root_agent, session_service=session_service) | ||
|
jorge-jrzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| async for event in runner.run_async( | ||
| user_id="user1", | ||
| session_id="demo", | ||
| new_message=content, | ||
| ): | ||
|
jorge-jrzz marked this conversation as resolved.
Outdated
|
||
| if event.is_final_response(): | ||
| print(event.content.parts[0].text) | ||
| ``` | ||
|
|
||
| If you already have an `AsyncMongoClient`, pass it instead of a connection | ||
| string: | ||
|
|
||
| ```python | ||
| from pymongo import AsyncMongoClient | ||
|
|
||
| client = AsyncMongoClient(host="localhost", port=27017) | ||
| session_service = MongoSessionService(client=client) | ||
| ``` | ||
|
|
||
| ## Collections and indexing | ||
|
|
||
| `MongoSessionService` writes to two collections (configurable): | ||
| - `sessions`: conversation history and session-level state | ||
| - `session_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)` | ||
|
|
||
| ## Sample structure | ||
|
|
||
| ``` | ||
| 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 | ||
| ``` | ||
|
|
||
| ## Sample agent | ||
|
|
||
| The agent (`mongo_service_agent/agent.py`) includes: | ||
| - `get_invoice_status(service)` tool for simple invoice lookups | ||
| - `calculate_service_tax(amount)` tool for tax calculations | ||
| - Gemini model (`gemini-2.0-flash`) with instructions to route to the tools | ||
|
|
||
| ## Sample query | ||
|
|
||
| ``` | ||
| What is the status of my university invoice? Also, calculate the tax for a service amount of 9500 MXN. | ||
| ``` | ||
|
|
||
| ## Configuration options (`MongoSessionService`) | ||
|
|
||
| - `database_name` (str, required): Mongo database to store session data | ||
|
jorge-jrzz marked this conversation as resolved.
Outdated
|
||
| - `connection_string` (str, optional): Mongo URI (mutually exclusive with `client`) | ||
| - `client` (AsyncMongoClient, optional): Provide your own client/connection pool | ||
| - `session_collection` (str, default `sessions`): Collection for session docs | ||
| - `state_collection` (str, default `session_state`): Collection for shared state | ||
| - `default_app_name` (str, optional): Fallback app name when not provided per call | ||
| - `mongo_appname` (str, default `adk-cosmos-session-service`): App name tag for Mongo driver telemetry | ||
|
jorge-jrzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| ## Tips | ||
|
|
||
| - Use `runner.run_async` (as in `main.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. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Example of using MongoDB for Session Service.""" | ||
|
|
||
| import asyncio | ||
|
|
||
| from google.adk.runners import Runner | ||
| from google.genai import types | ||
| from mongo_service_agent import root_agent | ||
|
|
||
| from google.adk_community.sessions import MongoSessionService | ||
|
|
||
| APP_NAME = "financial_advisor_agent" | ||
| USER_ID = "juante_jc_11" | ||
| SESSION_ID = "session_07" | ||
|
|
||
|
|
||
| async def main(): | ||
| """Main function to run the agent asynchronously.""" | ||
| # You can create the MongoSessionService in two ways: | ||
| # 1. With an existing AsyncMongoClient instance | ||
| # 2. By providing a connection string directly | ||
| # from pymongo import AsyncMongoClient | ||
| # client = AsyncMongoClient(host="localhost", port=27017) | ||
| # session_service = MongoSessionService(client=client) | ||
| session_service = MongoSessionService( | ||
| connection_string="mongodb+srv://<user>:<db_password>@<cluster-url>/" | ||
| ) | ||
|
jorge-jrzz marked this conversation as resolved.
Outdated
|
||
| await session_service.create_session( | ||
| app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID | ||
| ) | ||
|
jorge-jrzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| runner = Runner( | ||
| agent=root_agent, app_name=APP_NAME, session_service=session_service | ||
| ) | ||
|
|
||
| query = ( | ||
| "What is the status of my university invoice? Also, calculate the tax for" | ||
| " a service amount of 9500 MXN." | ||
| ) | ||
| print(f"User Query -> {query}") | ||
| content = types.Content(role="user", parts=[types.Part(text=query)]) | ||
|
|
||
| async for event in runner.run_async( | ||
| user_id=USER_ID, | ||
| session_id=SESSION_ID, | ||
| new_message=content, | ||
| ): | ||
| if event.is_final_response(): | ||
| print(f"Agent Response -> {event.content.parts[0].text}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) | ||
15 changes: 15 additions & 0 deletions
15
contributing/samples/mongodb_service/mongo_service_agent/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from .agent import root_agent |
87 changes: 87 additions & 0 deletions
87
contributing/samples/mongodb_service/mongo_service_agent/agent.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from dotenv import load_dotenv | ||
| from google.adk.agents import Agent | ||
| from google.adk.tools import FunctionTool | ||
|
|
||
| load_dotenv() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
|
|
||
| # Tool 1 | ||
| def get_invoice_status(service: str) -> dict: | ||
| """Return the invoice status details for the requested service. | ||
|
|
||
| Args: | ||
| service: Business category to query (for example 'gas' or 'restaurant'). | ||
|
|
||
| Returns: | ||
| dict: Contains a ``status`` entry with the invoice state and a ``report`` | ||
| entry that gives the relevant context for that status. | ||
| """ | ||
| if service == "university": | ||
| return {"status": "success", "report": "All TEC invoices are paid."} | ||
| elif service == "gas": | ||
| return {"status": "pending", "report": "Gas invoice due in 5 days."} | ||
| elif service == "restaurant": | ||
| return { | ||
| "status": "overdue", | ||
| "report": "Restaurant invoice is overdue by 10 days.", | ||
| } | ||
| else: | ||
| return {"status": "error", "report": "Service not recognized."} | ||
|
|
||
|
|
||
| invoice_tool = FunctionTool(func=get_invoice_status) | ||
|
|
||
|
|
||
| # Tool 2 | ||
| def calculate_service_tax(amount: float) -> dict: | ||
| """Calculate tax for a service amount using a fixed rate. | ||
|
|
||
| Args: | ||
| amount: Untaxed amount that needs a tax calculation. | ||
|
|
||
| Returns: | ||
| dict: Keys ``amount``, ``tax_amount``, and ``total_amount`` capturing the | ||
| original value, the computed tax, and the amount plus tax respectively. | ||
| """ | ||
| tax_rate = 0.16 | ||
|
jorge-jrzz marked this conversation as resolved.
Outdated
|
||
| tax_amount = amount * tax_rate | ||
| total_amount = amount + tax_amount | ||
| return { | ||
| "amount": amount, | ||
| "tax_amount": tax_amount, | ||
| "total_amount": total_amount, | ||
| } | ||
|
|
||
|
|
||
| tax_tool = FunctionTool(func=calculate_service_tax) | ||
|
|
||
| # Agent | ||
| root_agent = Agent( | ||
| model="gemini-2.0-flash", | ||
| name="financial_advisor_agent", | ||
| description="Financial advisor agent for managing invoices and calculating service taxes.", | ||
| instruction=( | ||
| "You are an AI agent designed to assist users with financial" | ||
| " inquiries related to invoices and service tax calculations.\n" | ||
| "**Available Tools:**\n" | ||
| "1. get_invoice_status(service): Retrieves the status of invoices\n" | ||
| "2. calculate_service_tax(amount): Calculates the tax for a given amount\n" | ||
| "Use these tools to assist users with their financial inquiries.\n" | ||
| "If the user asks about other financial topics, respond politely" | ||
| " that you can only assist with invoice status and tax calculations.\n" | ||
| ), | ||
| tools=[invoice_tool, tax_tool], | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.