-
Notifications
You must be signed in to change notification settings - Fork 31
Feat/46-redis-agent memory-server-for-dynamic-session-and-long-term-memory #47
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
Draft
nkanu17
wants to merge
20
commits into
google:main
Choose a base branch
from
nkanu17:feat/redis-agent-memory-service-v2
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.
+1,779
−20
Draft
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
18cd263
feat(memory): add RedisAgentMemoryService for Agent Memory Server int…
nkanu17 9174c1a
feat(memory): export RedisAgentMemoryService from memory module
nkanu17 d3194e5
build(deps): add redis-agent-memory optional dependency
nkanu17 0972101
test(memory): add unit tests for RedisAgentMemoryService
nkanu17 ee368c8
docs(samples): add redis_agent_memory sample application
nkanu17 05a382a
Add Pydantic dependency
vishal-bala 8000484
Constrain `agent-memory-client` dependency to Python 3.10+
vishal-bala c3efa93
dataclass -> Pydantic; lazy-load client
vishal-bala ed2abcc
Remove frivolous tests
vishal-bala 1494a81
Formatting
vishal-bala 65155a2
Fix Python version range for agent-memory-server
vishal-bala 471e62d
refactor(memory): rename RedisAgentMemoryService to RedisLongTermMemo…
nkanu17 0f92029
tests(memory): rename test_redis_agent_memory_service.py to test_redi…
nkanu17 e5eb662
formatting utils.py
nkanu17 dacffc8
feat(sessions): add RedisWorkingMemorySessionService for working memory
nkanu17 114046b
refactor(samples): redis_agent_memory sample with working and longter…
nkanu17 3a77986
readme(samples): Add instructions for setup to run ADK with Redis, Ag…
nkanu17 df82aba
Update contributing/samples/redis_agent_memory/README.md
nkanu17 be82159
Update contributing/samples/redis_agent_memory/README.md
nkanu17 c2c0b9b
fix: address code review feedback - consistent cached_property cleanu…
nkanu17 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
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,153 @@ | ||
| # Redis Agent Memory Sample | ||
|
|
||
| This sample demonstrates the **complete two-tier memory architecture** using Redis Agent Memory Server with ADK: | ||
|
|
||
| 1. **RedisWorkingMemorySessionService** - Session management with auto-summarization | ||
| 2. **RedisLongTermMemoryService** - Persistent long-term memory with semantic search | ||
|
|
||
| ## Architecture | ||
|
|
||
| ``` | ||
| ┌────────────────────────────────────────────────────────────────┐ | ||
| │ ADK Agent │ | ||
| ├──────────────────────────────┬─────────────────────────────────┤ | ||
| │ TIER 1: Working Memory │ TIER 2: Long-Term Memory │ | ||
| ├──────────────────────────────┼─────────────────────────────────┤ | ||
| │ • Current session messages │ • Extracted facts & preferences │ | ||
| │ • Auto-summarization │ • Semantic vector search │ | ||
| │ • Context window management │ • Cross-session persistence │ | ||
| │ • TTL support │ • Recency-boosted retrieval │ | ||
| ├──────────────────────────────┴─────────────────────────────────┤ | ||
| │ Agent Memory Server API │ | ||
| ├────────────────────────────────────────────────────────────────┤ | ||
| │ Redis Stack │ | ||
| └────────────────────────────────────────────────────────────────┘ | ||
| ``` | ||
|
|
||
| ## Example Flow | ||
|
|
||
| ``` | ||
| User Message | ||
| │ | ||
| ▼ | ||
| ┌─────────────┐ store ┌──────────────────────┐ | ||
| │ ADK Agent │─────────────▶│ Working Memory │ | ||
| └─────────────┘ │ (current session) │ | ||
| │ └──────────┬───────────┘ | ||
| │ │ extract | ||
| │ search ▼ | ||
| │ ┌──────────────────────┐ | ||
| └──────────────────────▶│ Long-Term Memory │ | ||
| │ (all sessions) │ | ||
| └──────────────────────┘ | ||
| ``` | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - Python 3.10+ | ||
| - Docker (for Redis Stack and Agent Memory Server) | ||
|
|
||
| ## Setup | ||
|
|
||
| ### 1. Install Dependencies | ||
|
|
||
| ```bash | ||
| pip install "google-adk-community[redis-agent-memory]" | ||
| ``` | ||
|
|
||
| > **Important**: The server is NOT installed via pip - it's a separate service that must be running. The pip package only installs the client to communicate with it. | ||
|
|
||
| ### 2. Start Redis Stack | ||
|
|
||
| ```bash | ||
| docker run -d --name redis-stack -p 6379:6379 redis/redis-stack:latest | ||
| ``` | ||
|
|
||
| ### 3. Start Agent Memory Server | ||
|
|
||
| ```bash | ||
| docker run -d --name agent-memory-server -p 8000:8000 \ | ||
| -e REDIS_URL=redis://host.docker.internal:6379 \ | ||
| -e OPENAI_API_KEY=your-openai-key \ | ||
| redislabs/agent-memory-server:latest \ | ||
| agent-memory api --host 0.0.0.0 --port 8000 --task-backend=asyncio | ||
| ``` | ||
|
|
||
| > **Note**: The memory server requires an OpenAI API key for embeddings by default. See the [Agent Memory Server docs](https://redis.github.io/agent-memory-server/) for alternative embedding providers. | ||
|
|
||
| ### 4. Verify Setup | ||
|
|
||
| ```bash | ||
| curl http://localhost:8000/health | ||
| ``` | ||
|
|
||
| ### 5. Configure Environment | ||
|
|
||
| Create `.env` in this directory: | ||
|
|
||
| ```bash | ||
| GOOGLE_API_KEY=your-google-api-key | ||
| REDIS_MEMORY_SERVER_URL=http://localhost:8000 | ||
| REDIS_MEMORY_NAMESPACE=adk_agent_memory | ||
| REDIS_MEMORY_EXTRACTION_STRATEGY=discrete | ||
| REDIS_MEMORY_CONTEXT_WINDOW=8000 | ||
| REDIS_MEMORY_RECENCY_BOOST=true | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| ```bash | ||
| python main.py | ||
| ``` | ||
|
|
||
| Open http://localhost:8080 in your browser. | ||
|
|
||
| ## Test Conversation | ||
|
|
||
| **Session 1** - Share information: | ||
| ``` | ||
| User: Hi, I'm Nitin. I'm a Machine Learning Engineer working on ML projects. | ||
| User: I love coffee, especially Berliner Frühstück Coffee from Berliner Kaffeerösterei. | ||
| User: My favorite programming language is Python. | ||
| ``` | ||
|
|
||
| **Session 2** - Test memory recall: | ||
| ``` | ||
| User: What do you remember about me? | ||
| User: What's my favorite coffee? | ||
| ``` | ||
|
|
||
| ## Features | ||
|
|
||
| | Feature | Working Memory (Tier 1) | Long-Term Memory (Tier 2) | | ||
| |---------|------------------------|---------------------------| | ||
| | Scope | Current session | All sessions | | ||
| | Auto-summarization | ✅ Yes | No | | ||
| | Semantic search | No | ✅ Yes | | ||
| | Fact extraction | Background | ✅ Persistent | | ||
| | TTL support | ✅ Yes | No | | ||
|
|
||
| ## Configuration | ||
|
|
||
| | Variable | Default | Description | | ||
| |----------|---------|-------------| | ||
| | `REDIS_MEMORY_SERVER_URL` | `http://localhost:8000` | Memory server URL | | ||
| | `REDIS_MEMORY_NAMESPACE` | `adk_agent_memory` | Namespace for isolation | | ||
| | `REDIS_MEMORY_EXTRACTION_STRATEGY` | `discrete` | `discrete`, `summary`, `preferences` | | ||
| | `REDIS_MEMORY_CONTEXT_WINDOW` | `8000` | Max tokens before summarization | | ||
| | `REDIS_MEMORY_RECENCY_BOOST` | `true` | Boost recent memories in search | | ||
|
|
||
| ## Memory Server Configuration | ||
|
|
||
| The Redis Agent Memory Server has important settings that affect memory extraction: | ||
|
|
||
| | Setting | Default | Description | | ||
| |---------|---------|-------------| | ||
| | `EXTRACTION_DEBOUNCE_SECONDS` | `300` (5 min) | Time between extraction runs per session | | ||
| | `LONG_TERM_MEMORY` | `true` | Enable long-term memory storage | | ||
| | `ENABLE_DISCRETE_MEMORY_EXTRACTION` | `true` | Enable fact extraction from messages | | ||
|
|
||
| **Note on Debouncing**: The memory server debounces extraction to avoid constantly re-extracting | ||
| from the same conversation. For testing, you can reduce `EXTRACTION_DEBOUNCE_SECONDS` to `5` in | ||
| the memory server's `.env` file. | ||
|
|
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,133 @@ | ||
| # 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. | ||
|
|
||
| """Full Redis Memory Sample: Working Memory Sessions + Long-Term Memory. | ||
|
|
||
| This sample demonstrates using BOTH Redis Agent Memory Server services: | ||
| 1. RedisWorkingMemorySessionService - For session management with auto-summarization | ||
| 2. RedisLongTermMemoryService - For persistent long-term memory search | ||
|
|
||
| This provides the complete two-tier memory architecture: | ||
| - Working Memory (Tier 1): Session state, messages, auto-summarization | ||
| - Long-Term Memory (Tier 2): Persistent facts, preferences, semantic search | ||
| """ | ||
|
|
||
| import os | ||
| from urllib.parse import urlparse | ||
|
|
||
| from dotenv import load_dotenv | ||
| from fastapi import FastAPI | ||
| from google.adk.cli.fast_api import get_fast_api_app | ||
| from google.adk.cli.service_registry import get_service_registry | ||
| import uvicorn | ||
|
|
||
| from google.adk_community.memory import RedisLongTermMemoryService | ||
| from google.adk_community.memory import RedisLongTermMemoryServiceConfig | ||
| from google.adk_community.sessions import RedisWorkingMemorySessionService | ||
| from google.adk_community.sessions import RedisWorkingMemorySessionServiceConfig | ||
|
|
||
| load_dotenv() | ||
|
|
||
|
|
||
| def parse_base_url(uri: str) -> str: | ||
| """Parse URI to extract base URL.""" | ||
| parsed = urlparse(uri) | ||
| location = parsed.netloc + parsed.path | ||
| return ( | ||
| location | ||
| if location.startswith(("http://", "https://")) | ||
| else f"http://{location}" | ||
| ) | ||
|
|
||
|
|
||
| def redis_session_factory(uri: str, **kwargs): | ||
| """Factory function for creating RedisWorkingMemorySessionService from URI.""" | ||
| base_url = parse_base_url(uri) | ||
| config = RedisWorkingMemorySessionServiceConfig( | ||
| api_base_url=base_url, | ||
| default_namespace=os.getenv("REDIS_MEMORY_NAMESPACE", "adk_agent_memory"), | ||
| model_name=os.getenv("REDIS_MEMORY_MODEL_NAME", "gpt-4o"), | ||
| context_window_max=int(os.getenv("REDIS_MEMORY_CONTEXT_WINDOW", "8000")), | ||
| extraction_strategy=os.getenv( | ||
| "REDIS_MEMORY_EXTRACTION_STRATEGY", "discrete" | ||
| ), | ||
| ) | ||
| return RedisWorkingMemorySessionService(config=config) | ||
|
|
||
|
|
||
| def redis_memory_factory(uri: str, **kwargs): | ||
| """Factory function for creating RedisLongTermMemoryService from URI.""" | ||
| base_url = parse_base_url(uri) | ||
| config = RedisLongTermMemoryServiceConfig( | ||
| api_base_url=base_url, | ||
| default_namespace=os.getenv("REDIS_MEMORY_NAMESPACE", "adk_agent_memory"), | ||
| extraction_strategy=os.getenv( | ||
| "REDIS_MEMORY_EXTRACTION_STRATEGY", "discrete" | ||
| ), | ||
| recency_boost=os.getenv("REDIS_MEMORY_RECENCY_BOOST", "true").lower() | ||
| == "true", | ||
| semantic_weight=float(os.getenv("REDIS_MEMORY_SEMANTIC_WEIGHT", "0.7")), | ||
| recency_weight=float(os.getenv("REDIS_MEMORY_RECENCY_WEIGHT", "0.3")), | ||
| ) | ||
| return RedisLongTermMemoryService(config=config) | ||
|
|
||
|
|
||
| # Register both service factories | ||
| registry = get_service_registry() | ||
| registry.register_session_service("redis-working-memory", redis_session_factory) | ||
| registry.register_memory_service("redis-long-term-memory", redis_memory_factory) | ||
|
|
||
| # Build URIs from environment | ||
| server_url = ( | ||
| os.getenv("REDIS_MEMORY_SERVER_URL", "http://localhost:8000") | ||
| .replace("http://", "") | ||
| .replace("https://", "") | ||
| ) | ||
| SESSION_SERVICE_URI = f"redis-working-memory://{server_url}" | ||
| MEMORY_SERVICE_URI = f"redis-long-term-memory://{server_url}" | ||
|
|
||
| # Create the FastAPI app with both services | ||
| app: FastAPI = get_fast_api_app( | ||
| agents_dir=".", | ||
| session_service_uri=SESSION_SERVICE_URI, | ||
| memory_service_uri=MEMORY_SERVICE_URI, | ||
| web=True, | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| port = int(os.environ.get("PORT", 8080)) | ||
| namespace = os.getenv("REDIS_MEMORY_NAMESPACE", "adk_agent_memory") | ||
| server = os.getenv("REDIS_MEMORY_SERVER_URL", "http://localhost:8000") | ||
| extraction = os.getenv("REDIS_MEMORY_EXTRACTION_STRATEGY", "discrete") | ||
| context_window = os.getenv("REDIS_MEMORY_CONTEXT_WINDOW", "8000") | ||
|
|
||
| print(f""" | ||
| Starting Redis Agent Memory Sample | ||
| ======================== | ||
| ADK Server: http://localhost:{port} | ||
| Memory Server: {server} | ||
| Namespace: {namespace} | ||
| Extraction Strategy: {extraction} | ||
| Context Window: {context_window} tokens | ||
|
|
||
| Services: | ||
| - Session: RedisWorkingMemorySessionService (auto-summarization) | ||
| - Memory: RedisLongTermMemoryService (semantic search) | ||
|
|
||
| Two-Tier Architecture: | ||
| Tier 1 (Working Memory): Session messages, state, auto-summarization | ||
| Tier 2 (Long-Term Memory): Extracted facts, preferences, semantic search | ||
| """) | ||
| uvicorn.run(app, host="0.0.0.0", port=port) | ||
15 changes: 15 additions & 0 deletions
15
contributing/samples/redis_agent_memory/redis_agent_memory_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 . import agent |
75 changes: 75 additions & 0 deletions
75
contributing/samples/redis_agent_memory/redis_agent_memory_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,75 @@ | ||
| # 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. | ||
|
|
||
| """Agent with full Redis memory: Working Memory + Long-Term Memory. | ||
|
|
||
| This agent demonstrates the complete two-tier memory architecture: | ||
| - Working Memory: Automatic session summarization when context grows large | ||
| - Long-Term Memory: Persistent facts extracted and searchable across sessions | ||
| """ | ||
|
|
||
| from datetime import datetime | ||
|
|
||
| from google.adk import Agent | ||
| from google.adk.agents.callback_context import CallbackContext | ||
| from google.adk.tools import load_memory | ||
| from google.adk.tools import preload_memory | ||
|
|
||
|
|
||
| def before_agent(callback_context: CallbackContext): | ||
| """Update state before agent runs.""" | ||
| callback_context.state["_time"] = datetime.now().isoformat() | ||
|
|
||
|
|
||
| async def after_agent(callback_context: CallbackContext): | ||
| """Store session to long-term memory after agent completes.""" | ||
| # This triggers memory extraction to long-term memory | ||
| await callback_context.add_session_to_memory() | ||
|
|
||
|
|
||
| root_agent = Agent( | ||
| model="gemini-2.5-flash", | ||
| name="redis_agent_memory_agent", | ||
| description=( | ||
| "Agent with full two-tier Redis memory: working memory for sessions," | ||
| " long-term memory for persistence." | ||
| ), | ||
| before_agent_callback=before_agent, | ||
| after_agent_callback=after_agent, | ||
| instruction="""You are a helpful assistant with a powerful two-tier memory system. | ||
|
|
||
| ## Your Memory Capabilities | ||
|
|
||
| 1. **Working Memory** (automatic): Your current conversation is automatically managed. | ||
| When the conversation gets long, older messages are summarized to keep context efficient. | ||
|
|
||
| 2. **Long-Term Memory** (persistent): Important facts and preferences are automatically | ||
| extracted and stored. You can search this memory across sessions. | ||
|
|
||
| ## How to Use Memory | ||
|
|
||
| - Use `load_memory` to search for information from past conversations | ||
| - When users share personal info (name, preferences, facts), acknowledge it - | ||
| it will be automatically saved to long-term memory | ||
| - If a search doesn't find results, try different keywords | ||
|
|
||
| ## Conversation Guidelines | ||
|
|
||
| - Be conversational and remember details the user shares | ||
| - Reference past interactions when relevant | ||
| - Ask clarifying questions to learn more about the user | ||
|
|
||
| Current time: {_time}""", | ||
| tools=[preload_memory, load_memory], | ||
| ) |
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.