Wrap memory backends with Redis caching for improved performance on frequently accessed conversations.
Installation
Install the required packages:
pip install hypertic[redis]
Setup
Set your Redis connection string:
export REDIS_URL = redis :// localhost : 6379
Usage
Redis Cache wraps other memory backends to provide caching. It works with both PostgreSQL and MongoDB, and supports both sync and async operations:
PostgreSQL Sync
MongoDB Sync
Async
import os
from dotenv import load_dotenv
from hypertic.agents import Agent
from hypertic.models import OpenAIChat
from hypertic.memory import PostgresServer, RedisCache
load_dotenv()
DB_URL = os.getenv( "DATABASE_URL" , "postgresql://postgres:password@localhost:5432/postgres" )
REDIS_URL = os.getenv( "REDIS_URL" , "redis://localhost:6379" )
def main ():
# Step 1: Create base memory backend (PostgreSQL)
postgres_memory = PostgresServer( db_url = DB_URL , table_name = "cache_memory" )
# Step 2: Wrap with Redis cache
# TTL: 1 hour (3600 seconds)
cached_memory = RedisCache(
store = postgres_memory,
redis_url = REDIS_URL ,
ttl = 3600 ,
key_prefix = "trial"
)
# Step 3: Use with Agent
agent = Agent(
model = OpenAIChat(
model = "gpt-4o-mini"
),
memory = cached_memory
)
user_id = "user_123"
session_id = "session_001"
# Non-streaming response
response = agent.run( "My favorite color is blue." , session_id = session_id, user_id = user_id)
print (response.content)
# Streaming response
for event in agent.stream( "what is my favorite colour?" , session_id = session_id, user_id = user_id):
if event.type == "content" :
print (event.content, end = "" , flush = True )
if __name__ == "__main__" :
main()
Configuration Options
store - The base memory backend to wrap (PostgresServer, MongoServer, or their async equivalents)
redis_url - Redis connection string
ttl - Time-to-live for cached entries in seconds (default: 3600)
key_prefix - Prefix for Redis keys (default: “agent”)
Redis Cache can wrap any memory backend (PostgreSQL or MongoDB) to provide a caching layer. For async operations, use AsyncRedisCache with AsyncPostgresServer or AsyncMongoServer. You can inspect cached data using Redis CLI commands like KEYS trial:* or GET trial:key.