Download tfa_agents/shared/memory.py from VAH6002/TFA: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/spaces/VAH6002/TFA/resolve/main/tfa_agents/shared/memory.py
- Command line
-
hf download hf://spaces/VAH6002/TFA/tfa_agents/shared/memory.py
-
curl -L -o memory.py https://huggingface.co/spaces/VAH6002/TFA/resolve/main/tfa_agents/shared/memory.py
10.6 kB
| """Temporary Memory Store for TFA Pipeline. | |
| This module provides in-memory storage for: | |
| - Cross-agent data sharing within a single analysis | |
| - Caching of API responses to reduce redundant calls | |
| - Pattern learning from recent failures | |
| - Session-level context persistence | |
| Memory is temporary and cleared between analysis runs unless | |
| explicitly persisted. | |
| """ | |
| from dataclasses import dataclass, field | |
| from typing import Any, Optional | |
| from datetime import datetime, timedelta | |
| from collections import OrderedDict | |
| import threading | |
| class MemoryEntry: | |
| """A single memory entry with metadata.""" | |
| key: str | |
| value: Any | |
| created_at: datetime = field(default_factory=datetime.now) | |
| expires_at: Optional[datetime] = None | |
| access_count: int = 0 | |
| tags: list[str] = field(default_factory=list) | |
| def is_expired(self) -> bool: | |
| """Check if this entry has expired.""" | |
| if self.expires_at is None: | |
| return False | |
| return datetime.now() > self.expires_at | |
| def touch(self): | |
| """Update access count.""" | |
| self.access_count += 1 | |
| class TFAMemoryStore: | |
| """Thread-safe temporary memory store for TFA pipeline. | |
| Provides multiple memory namespaces: | |
| - analysis: Current analysis context (cleared per run) | |
| - cache: API response cache (TTL-based expiration) | |
| - patterns: Learned failure patterns (persists across runs) | |
| - session: Session-level data (persists within session) | |
| Usage: | |
| memory = TFAMemoryStore() | |
| # Store analysis data | |
| memory.set("analysis", "invocation_data", data) | |
| # Retrieve with default | |
| data = memory.get("cache", "api_response", default={}) | |
| # Store with TTL | |
| memory.set("cache", "sponge_result", result, ttl_seconds=300) | |
| """ | |
| def __init__(self, max_cache_size: int = 1000): | |
| """Initialize the memory store. | |
| Args: | |
| max_cache_size: Maximum entries in cache namespace (LRU eviction) | |
| """ | |
| self._lock = threading.RLock() | |
| self._max_cache_size = max_cache_size | |
| # Separate namespaces for different purposes | |
| self._namespaces: dict[str, OrderedDict[str, MemoryEntry]] = { | |
| "analysis": OrderedDict(), # Current analysis context | |
| "cache": OrderedDict(), # API response cache | |
| "patterns": OrderedDict(), # Learned patterns | |
| "session": OrderedDict(), # Session-level data | |
| } | |
| def set( | |
| self, | |
| namespace: str, | |
| key: str, | |
| value: Any, | |
| ttl_seconds: Optional[int] = None, | |
| tags: Optional[list[str]] = None, | |
| ) -> None: | |
| """Store a value in memory. | |
| Args: | |
| namespace: Memory namespace (analysis, cache, patterns, session) | |
| key: Unique key for the value | |
| value: Value to store | |
| ttl_seconds: Optional time-to-live in seconds | |
| tags: Optional tags for categorization | |
| """ | |
| with self._lock: | |
| if namespace not in self._namespaces: | |
| self._namespaces[namespace] = OrderedDict() | |
| expires_at = None | |
| if ttl_seconds is not None: | |
| expires_at = datetime.now() + timedelta(seconds=ttl_seconds) | |
| entry = MemoryEntry( | |
| key=key, | |
| value=value, | |
| expires_at=expires_at, | |
| tags=tags or [], | |
| ) | |
| # LRU eviction for cache namespace | |
| if namespace == "cache" and len(self._namespaces[namespace]) >= self._max_cache_size: | |
| self._namespaces[namespace].popitem(last=False) | |
| self._namespaces[namespace][key] = entry | |
| def get( | |
| self, | |
| namespace: str, | |
| key: str, | |
| default: Any = None, | |
| ) -> Any: | |
| """Retrieve a value from memory. | |
| Args: | |
| namespace: Memory namespace | |
| key: Key to retrieve | |
| default: Default value if not found or expired | |
| Returns: | |
| Stored value or default | |
| """ | |
| with self._lock: | |
| if namespace not in self._namespaces: | |
| return default | |
| entry = self._namespaces[namespace].get(key) | |
| if entry is None: | |
| return default | |
| if entry.is_expired(): | |
| del self._namespaces[namespace][key] | |
| return default | |
| entry.touch() | |
| # Move to end for LRU | |
| self._namespaces[namespace].move_to_end(key) | |
| return entry.value | |
| def has(self, namespace: str, key: str) -> bool: | |
| """Check if a key exists and is not expired.""" | |
| return self.get(namespace, key, default=None) is not None | |
| def delete(self, namespace: str, key: str) -> bool: | |
| """Delete a specific key. | |
| Returns: | |
| True if key was deleted, False if not found | |
| """ | |
| with self._lock: | |
| if namespace in self._namespaces and key in self._namespaces[namespace]: | |
| del self._namespaces[namespace][key] | |
| return True | |
| return False | |
| def clear_namespace(self, namespace: str) -> int: | |
| """Clear all entries in a namespace. | |
| Returns: | |
| Number of entries cleared | |
| """ | |
| with self._lock: | |
| if namespace in self._namespaces: | |
| count = len(self._namespaces[namespace]) | |
| self._namespaces[namespace].clear() | |
| return count | |
| return 0 | |
| def clear_analysis(self) -> int: | |
| """Clear analysis namespace (call between analysis runs).""" | |
| return self.clear_namespace("analysis") | |
| def clear_expired(self) -> int: | |
| """Remove all expired entries from all namespaces. | |
| Returns: | |
| Number of entries removed | |
| """ | |
| removed = 0 | |
| with self._lock: | |
| for namespace in self._namespaces.values(): | |
| expired_keys = [ | |
| key for key, entry in namespace.items() | |
| if entry.is_expired() | |
| ] | |
| for key in expired_keys: | |
| del namespace[key] | |
| removed += 1 | |
| return removed | |
| def get_by_tag(self, namespace: str, tag: str) -> list[Any]: | |
| """Get all values with a specific tag. | |
| Args: | |
| namespace: Memory namespace | |
| tag: Tag to filter by | |
| Returns: | |
| List of values with the tag | |
| """ | |
| with self._lock: | |
| if namespace not in self._namespaces: | |
| return [] | |
| results = [] | |
| for entry in self._namespaces[namespace].values(): | |
| if not entry.is_expired() and tag in entry.tags: | |
| results.append(entry.value) | |
| return results | |
| def stats(self) -> dict: | |
| """Get memory statistics. | |
| Returns: | |
| Dict with stats per namespace | |
| """ | |
| with self._lock: | |
| stats = {} | |
| for name, namespace in self._namespaces.items(): | |
| valid_count = sum( | |
| 1 for entry in namespace.values() | |
| if not entry.is_expired() | |
| ) | |
| stats[name] = { | |
| "total_entries": len(namespace), | |
| "valid_entries": valid_count, | |
| "expired_entries": len(namespace) - valid_count, | |
| } | |
| return stats | |
| # Global memory instance for the TFA system | |
| _global_memory: Optional[TFAMemoryStore] = None | |
| _memory_lock = threading.Lock() | |
| def get_memory() -> TFAMemoryStore: | |
| """Get the global TFA memory store instance. | |
| Returns: | |
| Singleton TFAMemoryStore instance | |
| """ | |
| global _global_memory | |
| with _memory_lock: | |
| if _global_memory is None: | |
| _global_memory = TFAMemoryStore() | |
| return _global_memory | |
| def reset_memory() -> None: | |
| """Reset the global memory store (for testing).""" | |
| global _global_memory | |
| with _memory_lock: | |
| _global_memory = None | |
| # Convenience functions for common operations | |
| def cache_api_response(key: str, response: Any, ttl_seconds: int = 300) -> None: | |
| """Cache an API response with TTL. | |
| Args: | |
| key: Cache key (e.g., "invocation_fe3e0b7f") | |
| response: API response to cache | |
| ttl_seconds: Time-to-live (default 5 minutes) | |
| """ | |
| get_memory().set("cache", key, response, ttl_seconds=ttl_seconds) | |
| def get_cached_response(key: str) -> Optional[Any]: | |
| """Get a cached API response. | |
| Args: | |
| key: Cache key | |
| Returns: | |
| Cached response or None if not found/expired | |
| """ | |
| return get_memory().get("cache", key) | |
| def store_analysis_context(key: str, value: Any) -> None: | |
| """Store data in the current analysis context. | |
| Args: | |
| key: Context key (e.g., "classification_result") | |
| value: Value to store | |
| """ | |
| get_memory().set("analysis", key, value) | |
| def get_analysis_context(key: str, default: Any = None) -> Any: | |
| """Get data from the current analysis context. | |
| Args: | |
| key: Context key | |
| default: Default value if not found | |
| Returns: | |
| Stored value or default | |
| """ | |
| return get_memory().get("analysis", key, default=default) | |
| def store_failure_pattern(pattern_name: str, pattern_data: dict) -> None: | |
| """Store a learned failure pattern. | |
| Args: | |
| pattern_name: Unique pattern identifier | |
| pattern_data: Pattern details (indicators, category, etc.) | |
| """ | |
| get_memory().set( | |
| "patterns", | |
| pattern_name, | |
| pattern_data, | |
| tags=[pattern_data.get("category", "unknown")], | |
| ) | |
| def get_similar_patterns(category: str) -> list[dict]: | |
| """Get all patterns for a category. | |
| Args: | |
| category: Failure category to filter by | |
| Returns: | |
| List of pattern data dicts | |
| """ | |
| return get_memory().get_by_tag("patterns", category) | |