Files
alfred/alfred/infrastructure/persistence/context.py

80 lines
1.7 KiB
Python

"""
Memory context using contextvars.
Provides thread-safe and async-safe access to the Memory instance
without passing it explicitly through all function calls.
Usage:
# At application startup
from alfred.infrastructure.persistence import init_memory, get_memory
init_memory("memory_data")
# Anywhere in the code
memory = get_memory()
memory.ltm.set_config("key", "value")
"""
from contextvars import ContextVar
from .memory import Memory
_memory_ctx: ContextVar[Memory | None] = ContextVar("memory", default=None)
def init_memory(storage_dir: str = "memory_data") -> Memory:
"""
Initialize the memory and set it in the context.
Call this once at application startup.
Args:
storage_dir: Directory for persistent storage.
Returns:
The initialized Memory instance.
"""
memory = Memory(storage_dir=storage_dir)
_memory_ctx.set(memory)
return memory
def set_memory(memory: Memory) -> None:
"""
Set an existing Memory instance in the context.
Useful for testing or when injecting a specific instance.
Args:
memory: Memory instance to set.
"""
_memory_ctx.set(memory)
def get_memory() -> Memory:
"""
Get the Memory instance from the context.
Returns:
The Memory instance.
Raises:
RuntimeError: If memory has not been initialized.
"""
memory = _memory_ctx.get()
if memory is None:
raise RuntimeError(
"Memory not initialized. Call init_memory() at application startup."
)
return memory
def has_memory() -> bool:
"""
Check if memory has been initialized.
Returns:
True if memory is available, False otherwise.
"""
return _memory_ctx.get() is not None