Skip to content
Draft
Show file tree
Hide file tree
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 Jan 12, 2026
9174c1a
feat(memory): export RedisAgentMemoryService from memory module
nkanu17 Jan 12, 2026
d3194e5
build(deps): add redis-agent-memory optional dependency
nkanu17 Jan 12, 2026
0972101
test(memory): add unit tests for RedisAgentMemoryService
nkanu17 Jan 12, 2026
ee368c8
docs(samples): add redis_agent_memory sample application
nkanu17 Jan 12, 2026
05a382a
Add Pydantic dependency
vishal-bala Jan 15, 2026
8000484
Constrain `agent-memory-client` dependency to Python 3.10+
vishal-bala Jan 15, 2026
c3efa93
dataclass -> Pydantic; lazy-load client
vishal-bala Jan 15, 2026
ed2abcc
Remove frivolous tests
vishal-bala Jan 15, 2026
1494a81
Formatting
vishal-bala Jan 15, 2026
65155a2
Fix Python version range for agent-memory-server
vishal-bala Jan 15, 2026
471e62d
refactor(memory): rename RedisAgentMemoryService to RedisLongTermMemo…
nkanu17 Jan 27, 2026
0f92029
tests(memory): rename test_redis_agent_memory_service.py to test_redi…
nkanu17 Jan 27, 2026
e5eb662
formatting utils.py
nkanu17 Jan 27, 2026
dacffc8
feat(sessions): add RedisWorkingMemorySessionService for working memory
nkanu17 Jan 27, 2026
114046b
refactor(samples): redis_agent_memory sample with working and longter…
nkanu17 Jan 27, 2026
3a77986
readme(samples): Add instructions for setup to run ADK with Redis, Ag…
nkanu17 Jan 27, 2026
df82aba
Update contributing/samples/redis_agent_memory/README.md
nkanu17 Jan 27, 2026
be82159
Update contributing/samples/redis_agent_memory/README.md
nkanu17 Jan 27, 2026
c2c0b9b
fix: address code review feedback - consistent cached_property cleanu…
nkanu17 Jan 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions contributing/samples/redis_agent_memory/README.md
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.

133 changes: 133 additions & 0 deletions contributing/samples/redis_agent_memory/main.py
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)
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
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],
)
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies = [
"google-genai>=1.21.1, <2.0.0", # Google GenAI SDK
"google-adk", # Google ADK
"httpx>=0.27.0, <1.0.0", # For OpenMemory service
"pydantic>=2.0, <3.0.0", # For data validation/models
"redis>=5.0.0, <6.0.0", # Redis for session storage
# go/keep-sorted end
"orjson>=3.11.3",
Expand All @@ -45,7 +46,9 @@ test = [
"pytest>=8.4.2",
"pytest-asyncio>=1.2.0",
]

redis-agent-memory = [
"agent-memory-client>=0.13.0; python_version >= '3.10'",
]

[tool.pyink]
# Format py files following Google style-guide
Expand Down
Loading