-
Notifications
You must be signed in to change notification settings - Fork 1.9k
fix: resolve Memory Bank Service agent ID extraction issue #2940 #2941
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
ishanrajsingh
wants to merge
11
commits into
google:main
Choose a base branch
from
ishanrajsingh:improve-memory-bank-docs
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.
+523
−24
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
e1567ff
fix: resolve Memory Bank Service agent ID extraction issue #2940
ishanrajsingh 1a78e73
Update src/google/adk/__init__.py
ishanrajsingh f7634f3
Update src/google/adk/examples/memory_bank_complete_setup.py
ishanrajsingh 1e29475
fix: address code review feedback from Gemini Code Assist
ishanrajsingh c68e3d9
Merge branch 'improve-memory-bank-docs' of https://github.com/ishanra…
ishanrajsingh 34c7047
fix: address code review feedback from Gemini Code Assist
ishanrajsingh 5a32651
Merge branch 'main' into improve-memory-bank-docs
ishanrajsingh 6ad91ea
Merge branch 'main' into improve-memory-bank-docs
ishanrajsingh c610a3a
Merge branch 'main' into improve-memory-bank-docs
ishanrajsingh 7fff0cf
Merge branch 'main' into improve-memory-bank-docs
ishanrajsingh 31876c7
Merge branch 'main' into improve-memory-bank-docs
ishanrajsingh 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
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,189 @@ | ||
""" | ||
Complete Memory Bank Service setup example - Issue #2940 Solution | ||
|
||
This example demonstrates the correct way to: | ||
1. Create an Agent Engine | ||
2. Extract the Agent ID from the resource name | ||
3. Setup Memory Bank Service with the correct ID | ||
|
||
Common Error: Using api_resource.name directly instead of extracting the ID | ||
Solution: Use .split("/")[-1] to extract the ID from the full resource path | ||
""" | ||
|
||
import os | ||
import sys | ||
import logging | ||
import vertexai | ||
from google.adk.memory import VertexAiMemoryBankService | ||
from google.adk.sessions import VertexAiSessionService | ||
from google.adk.agents import Agent | ||
from google.adk.tools.preload_memory_tool import PreloadMemoryTool | ||
import google.adk as adk | ||
|
||
# Import our utility function | ||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))) | ||
from google.adk.utils.resource_utils import extract_agent_engine_id, validate_agent_engine_resource_name | ||
|
||
# Setup logging | ||
logging.basicConfig(level=logging.INFO) | ||
logger = logging.getLogger(__name__) | ||
|
||
class MemoryBankSetup: | ||
"""Complete Memory Bank Service setup with proper agent ID extraction.""" | ||
|
||
def __init__(self, project_id: str, location: str = "us-central1"): | ||
self.project_id = project_id | ||
self.location = location | ||
self.agent_engine = None | ||
self.agent_engine_id = None | ||
self.memory_service = None | ||
self.session_service = None | ||
|
||
def create_agent_engine(self): | ||
"""Create Vertex AI Agent Engine and extract ID correctly.""" | ||
try: | ||
# Create Vertex AI client | ||
client = vertexai.Client(project=self.project_id, location=self.location) | ||
|
||
# Create Agent Engine | ||
self.agent_engine = client.agent_engines.create() | ||
resource_name = self.agent_engine.api_resource.name | ||
|
||
logger.info(f"Created Agent Engine: {resource_name}") | ||
|
||
# CRITICAL: Extract Agent ID from resource name (Issue #2940 fix) | ||
if validate_agent_engine_resource_name(resource_name): | ||
self.agent_engine_id = extract_agent_engine_id(resource_name) | ||
logger.info(f"Extracted Agent Engine ID: {self.agent_engine_id}") | ||
else: | ||
raise ValueError(f"Invalid Agent Engine resource name format: {resource_name}") | ||
|
||
return self.agent_engine_id | ||
|
||
except Exception as e: | ||
logger.error(f"Failed to create Agent Engine: {str(e)}") | ||
raise | ||
|
||
def setup_memory_service(self): | ||
"""Setup Memory Bank Service with correct agent ID.""" | ||
if not self.agent_engine_id: | ||
raise ValueError("Agent Engine ID not available. Call create_agent_engine() first.") | ||
|
||
try: | ||
# Create Memory Bank Service using extracted agent ID | ||
self.memory_service = VertexAiMemoryBankService( | ||
project=self.project_id, | ||
location=self.location, | ||
agent_engine_id=self.agent_engine_id # Use extracted ID, NOT full resource name | ||
) | ||
|
||
logger.info("Memory Bank Service setup complete") | ||
return self.memory_service | ||
|
||
except Exception as e: | ||
logger.error(f"Failed to setup Memory Bank Service: {str(e)}") | ||
raise | ||
|
||
def setup_session_service(self): | ||
"""Setup Session Service with correct agent ID.""" | ||
if not self.agent_engine_id: | ||
raise ValueError("Agent Engine ID not available. Call create_agent_engine() first.") | ||
|
||
try: | ||
# Create Session Service using extracted agent ID | ||
self.session_service = VertexAiSessionService( | ||
project_id=self.project_id, | ||
location=self.location, | ||
agent_engine_id=self.agent_engine_id # Use extracted ID | ||
) | ||
|
||
logger.info("Session Service setup complete") | ||
return self.session_service | ||
|
||
except Exception as e: | ||
logger.error(f"Failed to setup Session Service: {str(e)}") | ||
raise | ||
|
||
def create_agent_with_memory(self): | ||
"""Create an agent with memory capabilities.""" | ||
if not self.memory_service or not self.session_service: | ||
raise ValueError("Memory and Session services must be setup first") | ||
|
||
try: | ||
# Create agent with memory tools | ||
agent = adk.Agent( | ||
model="gemini-2.5-flash", | ||
name="memory-enabled-agent", | ||
instruction="You are an AI assistant with persistent memory. Remember user preferences and conversation history.", | ||
description="Agent with Memory Bank capabilities for persistent conversations", | ||
tools=[PreloadMemoryTool()] | ||
) | ||
|
||
# Create runner with memory and session services | ||
runner = adk.Runner( | ||
agent=agent, | ||
app_name="memory-bank-demo-app", | ||
session_service=self.session_service, | ||
memory_service=self.memory_service | ||
) | ||
|
||
logger.info("Agent with Memory Bank created successfully") | ||
return runner | ||
|
||
except Exception as e: | ||
logger.error(f"Failed to create agent with memory: {str(e)}") | ||
raise | ||
|
||
def main(): | ||
"""Main function demonstrating complete setup.""" | ||
# Configuration | ||
project_id = os.getenv("GOOGLE_CLOUD_PROJECT") | ||
location = os.getenv("GOOGLE_CLOUD_LOCATION", "us-central1") | ||
|
||
if not project_id: | ||
print("Error: GOOGLE_CLOUD_PROJECT environment variable not set") | ||
print("Set it with: export GOOGLE_CLOUD_PROJECT='your-project-id'") | ||
return | ||
|
||
print(f"Starting Memory Bank Service setup for project: {project_id}") | ||
print(f"Location: {location}") | ||
print("-" * 60) | ||
|
||
try: | ||
# Initialize setup class | ||
setup = MemoryBankSetup(project_id=project_id, location=location) | ||
|
||
# Step 1: Create Agent Engine and extract ID | ||
print("Creating Agent Engine...") | ||
agent_id = setup.create_agent_engine() | ||
print(f" Agent Engine ID: {agent_id}") | ||
|
||
# Step 2: Setup Memory Bank Service | ||
print("Setting up Memory Bank Service...") | ||
setup.setup_memory_service() | ||
|
||
# Step 3: Setup Session Service | ||
print("Setting up Session Service...") | ||
setup.setup_session_service() | ||
|
||
# Step 4: Create Agent with Memory | ||
print("Creating Agent with Memory...") | ||
runner = setup.create_agent_with_memory() | ||
|
||
print("-" * 60) | ||
print("SUCCESS! Memory Bank Service setup complete!") | ||
print(f"Agent Engine ID: {agent_id}") | ||
print("Agent is ready for conversations with persistent memory") | ||
print("-" * 60) | ||
|
||
# Optional: Test the setup | ||
print("Testing memory capabilities...") | ||
response = runner.run("Hello! Please remember that my favorite color is blue.") | ||
print(f"Agent: {response}") | ||
|
||
except Exception as e: | ||
print(f"Setup failed: {str(e)}") | ||
sys.exit(1) | ||
|
||
if __name__ == "__main__": | ||
main() |
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.