- Fix circular dependencies in agent/tools - Migrate from custom JSON to OpenAI tool calls format - Add async streaming (step_stream, complete_stream) - Simplify prompt system and remove token counting - Add 5 new API endpoints (/health, /v1/models, /api/memory/*) - Add 3 new tools (get_torrent_by_index, add_torrent_by_index, set_language) - Fix all 500 tests and add coverage config (80% threshold) - Add comprehensive docs (README, pytest guide) BREAKING: LLM interface changed, memory injection via get_memory()
80 lines
1.7 KiB
Python
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 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
|