Compare commits
3 Commits
whip/322-1
...
fix/479-ha
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f32d33836f | ||
| 954fd992eb | |||
|
|
f35f56e397 |
@@ -1,171 +0,0 @@
|
||||
"""Memory Backend Interface — pluggable cross-session user modeling.
|
||||
|
||||
Provides a common interface for memory backends that persist user
|
||||
preferences and patterns across sessions. Two implementations:
|
||||
|
||||
1. LocalBackend (default): SQLite-based, zero cloud dependency
|
||||
2. HonchoBackend (opt-in): Honcho AI-native memory, requires API key
|
||||
|
||||
Both are zero-overhead when disabled — the interface returns empty
|
||||
results and no writes occur.
|
||||
|
||||
Usage:
|
||||
from agent.memory import get_memory_backend
|
||||
|
||||
backend = get_memory_backend() # returns configured backend
|
||||
backend.store_preference("user", "prefers_python", "True")
|
||||
context = backend.query_context("user", "What does this user prefer?")
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MemoryEntry:
|
||||
"""A single memory entry."""
|
||||
key: str
|
||||
value: str
|
||||
user_id: str
|
||||
created_at: float = 0
|
||||
updated_at: float = 0
|
||||
metadata: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
now = time.time()
|
||||
if not self.created_at:
|
||||
self.created_at = now
|
||||
if not self.updated_at:
|
||||
self.updated_at = now
|
||||
|
||||
|
||||
class MemoryBackend(ABC):
|
||||
"""Abstract interface for memory backends."""
|
||||
|
||||
@abstractmethod
|
||||
def is_available(self) -> bool:
|
||||
"""Check if this backend is configured and usable."""
|
||||
|
||||
@abstractmethod
|
||||
def store(self, user_id: str, key: str, value: str, metadata: Dict = None) -> bool:
|
||||
"""Store a memory entry."""
|
||||
|
||||
@abstractmethod
|
||||
def retrieve(self, user_id: str, key: str) -> Optional[MemoryEntry]:
|
||||
"""Retrieve a single memory entry."""
|
||||
|
||||
@abstractmethod
|
||||
def query(self, user_id: str, query_text: str, limit: int = 10) -> List[MemoryEntry]:
|
||||
"""Query memories relevant to a text query."""
|
||||
|
||||
@abstractmethod
|
||||
def list_keys(self, user_id: str) -> List[str]:
|
||||
"""List all keys for a user."""
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, user_id: str, key: str) -> bool:
|
||||
"""Delete a memory entry."""
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def backend_name(self) -> str:
|
||||
"""Human-readable backend name."""
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def is_cloud(self) -> bool:
|
||||
"""Whether this backend requires cloud connectivity."""
|
||||
|
||||
|
||||
class NullBackend(MemoryBackend):
|
||||
"""No-op backend when memory is disabled. Zero overhead."""
|
||||
|
||||
def is_available(self) -> bool:
|
||||
return True # always "available" as null
|
||||
|
||||
def store(self, user_id: str, key: str, value: str, metadata: Dict = None) -> bool:
|
||||
return True # no-op
|
||||
|
||||
def retrieve(self, user_id: str, key: str) -> Optional[MemoryEntry]:
|
||||
return None
|
||||
|
||||
def query(self, user_id: str, query_text: str, limit: int = 10) -> List[MemoryEntry]:
|
||||
return []
|
||||
|
||||
def list_keys(self, user_id: str) -> List[str]:
|
||||
return []
|
||||
|
||||
def delete(self, user_id: str, key: str) -> bool:
|
||||
return True
|
||||
|
||||
@property
|
||||
def backend_name(self) -> str:
|
||||
return "null (disabled)"
|
||||
|
||||
@property
|
||||
def is_cloud(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Singleton
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_backend: Optional[MemoryBackend] = None
|
||||
|
||||
|
||||
def get_memory_backend() -> MemoryBackend:
|
||||
"""Get the configured memory backend.
|
||||
|
||||
Priority:
|
||||
1. If HONCHO_API_KEY is set and honcho-ai is installed -> HonchoBackend
|
||||
2. If memory_backend config is 'local' -> LocalBackend
|
||||
3. Default -> NullBackend (zero overhead)
|
||||
"""
|
||||
global _backend
|
||||
if _backend is not None:
|
||||
return _backend
|
||||
|
||||
# Check config
|
||||
backend_type = os.getenv("HERMES_MEMORY_BACKEND", "").lower().strip()
|
||||
|
||||
if backend_type == "honcho" or os.getenv("HONCHO_API_KEY"):
|
||||
try:
|
||||
from agent.memory.honcho_backend import HonchoBackend
|
||||
backend = HonchoBackend()
|
||||
if backend.is_available():
|
||||
_backend = backend
|
||||
logger.info("Memory backend: Honcho (cloud)")
|
||||
return _backend
|
||||
except ImportError:
|
||||
logger.debug("Honcho not installed, falling back")
|
||||
|
||||
if backend_type == "local":
|
||||
try:
|
||||
from agent.memory.local_backend import LocalBackend
|
||||
_backend = LocalBackend()
|
||||
logger.info("Memory backend: Local (SQLite)")
|
||||
return _backend
|
||||
except Exception as e:
|
||||
logger.warning("Local backend failed: %s", e)
|
||||
|
||||
# Default: null (zero overhead)
|
||||
_backend = NullBackend()
|
||||
return _backend
|
||||
|
||||
|
||||
def reset_backend():
|
||||
"""Reset the singleton (for testing)."""
|
||||
global _backend
|
||||
_backend = None
|
||||
@@ -1,263 +0,0 @@
|
||||
"""Memory Backend Evaluation Framework.
|
||||
|
||||
Provides structured evaluation for comparing memory backends on:
|
||||
1. Latency (store/retrieve/query operations)
|
||||
2. Relevance (does query return useful results?)
|
||||
3. Privacy (where is data stored?)
|
||||
4. Reliability (availability, error handling)
|
||||
5. Cost (API calls, cloud dependency)
|
||||
|
||||
Usage:
|
||||
from agent.memory.evaluation import evaluate_backends
|
||||
report = evaluate_backends()
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BackendEvaluation:
|
||||
"""Evaluation results for a single backend."""
|
||||
backend_name: str
|
||||
is_cloud: bool
|
||||
available: bool
|
||||
|
||||
# Latency (milliseconds)
|
||||
store_latency_ms: float = 0
|
||||
retrieve_latency_ms: float = 0
|
||||
query_latency_ms: float = 0
|
||||
|
||||
# Functionality
|
||||
store_success: bool = False
|
||||
retrieve_success: bool = False
|
||||
query_returns_results: bool = False
|
||||
query_result_count: int = 0
|
||||
|
||||
# Privacy
|
||||
data_location: str = "unknown"
|
||||
requires_api_key: bool = False
|
||||
|
||||
# Overall
|
||||
score: float = 0 # 0-100
|
||||
recommendation: str = ""
|
||||
notes: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _measure_latency(func, *args, **kwargs) -> tuple:
|
||||
"""Measure function latency in milliseconds."""
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
elapsed = (time.perf_counter() - start) * 1000
|
||||
return elapsed, result, None
|
||||
except Exception as e:
|
||||
elapsed = (time.perf_counter() - start) * 1000
|
||||
return elapsed, None, e
|
||||
|
||||
|
||||
def evaluate_backend(backend, test_user: str = "eval_user") -> BackendEvaluation:
|
||||
"""Evaluate a single memory backend."""
|
||||
from agent.memory import MemoryBackend
|
||||
|
||||
eval_result = BackendEvaluation(
|
||||
backend_name=backend.backend_name,
|
||||
is_cloud=backend.is_cloud,
|
||||
available=backend.is_available(),
|
||||
)
|
||||
|
||||
if not eval_result.available:
|
||||
eval_result.notes.append("Backend not available")
|
||||
eval_result.score = 0
|
||||
eval_result.recommendation = "NOT AVAILABLE"
|
||||
return eval_result
|
||||
|
||||
# Privacy assessment
|
||||
if backend.is_cloud:
|
||||
eval_result.data_location = "cloud (external)"
|
||||
eval_result.requires_api_key = True
|
||||
else:
|
||||
eval_result.data_location = "local (~/.hermes/)"
|
||||
|
||||
# Test store
|
||||
latency, success, err = _measure_latency(
|
||||
backend.store,
|
||||
test_user,
|
||||
"eval_test_key",
|
||||
"eval_test_value",
|
||||
{"source": "evaluation"},
|
||||
)
|
||||
eval_result.store_latency_ms = latency
|
||||
eval_result.store_success = success is True
|
||||
if err:
|
||||
eval_result.notes.append(f"Store error: {err}")
|
||||
|
||||
# Test retrieve
|
||||
latency, result, err = _measure_latency(
|
||||
backend.retrieve,
|
||||
test_user,
|
||||
"eval_test_key",
|
||||
)
|
||||
eval_result.retrieve_latency_ms = latency
|
||||
eval_result.retrieve_success = result is not None
|
||||
if err:
|
||||
eval_result.notes.append(f"Retrieve error: {err}")
|
||||
|
||||
# Test query
|
||||
latency, results, err = _measure_latency(
|
||||
backend.query,
|
||||
test_user,
|
||||
"eval_test",
|
||||
5,
|
||||
)
|
||||
eval_result.query_latency_ms = latency
|
||||
eval_result.query_returns_results = bool(results)
|
||||
eval_result.query_result_count = len(results) if results else 0
|
||||
if err:
|
||||
eval_result.notes.append(f"Query error: {err}")
|
||||
|
||||
# Cleanup
|
||||
try:
|
||||
backend.delete(test_user, "eval_test_key")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Score calculation (0-100)
|
||||
score = 0
|
||||
|
||||
# Availability (20 points)
|
||||
score += 20
|
||||
|
||||
# Functionality (40 points)
|
||||
if eval_result.store_success:
|
||||
score += 15
|
||||
if eval_result.retrieve_success:
|
||||
score += 15
|
||||
if eval_result.query_returns_results:
|
||||
score += 10
|
||||
|
||||
# Latency (20 points) — lower is better
|
||||
avg_latency = (
|
||||
eval_result.store_latency_ms +
|
||||
eval_result.retrieve_latency_ms +
|
||||
eval_result.query_latency_ms
|
||||
) / 3
|
||||
if avg_latency < 10:
|
||||
score += 20
|
||||
elif avg_latency < 50:
|
||||
score += 15
|
||||
elif avg_latency < 200:
|
||||
score += 10
|
||||
else:
|
||||
score += 5
|
||||
|
||||
# Privacy (20 points) — local is better for sovereignty
|
||||
if not backend.is_cloud:
|
||||
score += 20
|
||||
else:
|
||||
score += 5 # cloud has privacy trade-offs
|
||||
|
||||
eval_result.score = score
|
||||
|
||||
# Recommendation
|
||||
if score >= 80:
|
||||
eval_result.recommendation = "RECOMMENDED"
|
||||
elif score >= 60:
|
||||
eval_result.recommendation = "ACCEPTABLE"
|
||||
elif score >= 40:
|
||||
eval_result.recommendation = "MARGINAL"
|
||||
else:
|
||||
eval_result.recommendation = "NOT RECOMMENDED"
|
||||
|
||||
return eval_result
|
||||
|
||||
|
||||
def evaluate_backends() -> Dict[str, Any]:
|
||||
"""Evaluate all available memory backends.
|
||||
|
||||
Returns a comparison report.
|
||||
"""
|
||||
from agent.memory import NullBackend
|
||||
from agent.memory.local_backend import LocalBackend
|
||||
|
||||
backends = []
|
||||
|
||||
# Always evaluate Null (baseline)
|
||||
backends.append(NullBackend())
|
||||
|
||||
# Evaluate Local
|
||||
try:
|
||||
backends.append(LocalBackend())
|
||||
except Exception as e:
|
||||
logger.warning("Local backend init failed: %s", e)
|
||||
|
||||
# Try Honcho if configured
|
||||
import os
|
||||
if os.getenv("HONCHO_API_KEY"):
|
||||
try:
|
||||
from agent.memory.honcho_backend import HonchoBackend
|
||||
backends.append(HonchoBackend())
|
||||
except ImportError:
|
||||
logger.debug("Honcho not installed, skipping evaluation")
|
||||
|
||||
evaluations = []
|
||||
for backend in backends:
|
||||
try:
|
||||
evaluations.append(evaluate_backend(backend))
|
||||
except Exception as e:
|
||||
logger.warning("Evaluation failed for %s: %s", backend.backend_name, e)
|
||||
|
||||
# Build report
|
||||
report = {
|
||||
"timestamp": time.time(),
|
||||
"backends_evaluated": len(evaluations),
|
||||
"evaluations": [asdict(e) for e in evaluations],
|
||||
"recommendation": _build_recommendation(evaluations),
|
||||
}
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def _build_recommendation(evaluations: List[BackendEvaluation]) -> str:
|
||||
"""Build overall recommendation from evaluations."""
|
||||
if not evaluations:
|
||||
return "No backends evaluated"
|
||||
|
||||
# Find best non-null backend
|
||||
viable = [e for e in evaluations if e.backend_name != "null (disabled)" and e.available]
|
||||
if not viable:
|
||||
return "No viable backends found. Use NullBackend (default)."
|
||||
|
||||
best = max(viable, key=lambda e: e.score)
|
||||
|
||||
parts = [f"Best backend: {best.backend_name} (score: {best.score})"]
|
||||
|
||||
if best.is_cloud:
|
||||
parts.append(
|
||||
"WARNING: Cloud backend has privacy trade-offs. "
|
||||
"Data leaves your machine. Consider LocalBackend for sovereignty."
|
||||
)
|
||||
|
||||
# Compare local vs cloud if both available
|
||||
local = [e for e in viable if not e.is_cloud]
|
||||
cloud = [e for e in viable if e.is_cloud]
|
||||
if local and cloud:
|
||||
local_score = max(e.score for e in local)
|
||||
cloud_score = max(e.score for e in cloud)
|
||||
if local_score >= cloud_score:
|
||||
parts.append(
|
||||
f"Local backend (score {local_score}) matches or beats "
|
||||
f"cloud (score {cloud_score}). RECOMMEND: stay local for sovereignty."
|
||||
)
|
||||
else:
|
||||
parts.append(
|
||||
f"Cloud backend (score {cloud_score}) outperforms "
|
||||
f"local (score {local_score}) but adds cloud dependency."
|
||||
)
|
||||
|
||||
return " ".join(parts)
|
||||
@@ -1,171 +0,0 @@
|
||||
"""Honcho memory backend — opt-in cloud-based user modeling.
|
||||
|
||||
Requires:
|
||||
- pip install honcho-ai
|
||||
- HONCHO_API_KEY environment variable (from app.honcho.dev)
|
||||
|
||||
Provides dialectic user context queries via Honcho's AI-native memory.
|
||||
Zero runtime overhead when not configured — get_memory_backend() falls
|
||||
back to LocalBackend or NullBackend if this fails to initialize.
|
||||
|
||||
This is the evaluation wrapper. It adapts the Honcho SDK to our
|
||||
MemoryBackend interface so we can A/B test against LocalBackend.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from agent.memory import MemoryBackend, MemoryEntry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HonchoBackend(MemoryBackend):
|
||||
"""Honcho AI-native memory backend.
|
||||
|
||||
Wraps the honcho-ai SDK to provide cross-session user modeling
|
||||
with dialectic context queries.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._client = None
|
||||
self._api_key = os.getenv("HONCHO_API_KEY", "")
|
||||
self._app_id = os.getenv("HONCHO_APP_ID", "hermes-agent")
|
||||
self._base_url = os.getenv("HONCHO_BASE_URL", "https://api.honcho.dev")
|
||||
|
||||
def _get_client(self):
|
||||
"""Lazy-load Honcho client."""
|
||||
if self._client is not None:
|
||||
return self._client
|
||||
|
||||
if not self._api_key:
|
||||
return None
|
||||
|
||||
try:
|
||||
from honcho import Honcho
|
||||
self._client = Honcho(
|
||||
api_key=self._api_key,
|
||||
app_id=self._app_id,
|
||||
base_url=self._base_url,
|
||||
)
|
||||
return self._client
|
||||
except ImportError:
|
||||
logger.warning("honcho-ai not installed. Install with: pip install honcho-ai")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("Failed to initialize Honcho client: %s", e)
|
||||
return None
|
||||
|
||||
def is_available(self) -> bool:
|
||||
if not self._api_key:
|
||||
return False
|
||||
client = self._get_client()
|
||||
if client is None:
|
||||
return False
|
||||
# Try a simple API call to verify connectivity
|
||||
try:
|
||||
# Honcho uses sessions — verify we can list them
|
||||
client.get_sessions(limit=1)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.debug("Honcho not available: %s", e)
|
||||
return False
|
||||
|
||||
def store(self, user_id: str, key: str, value: str, metadata: Dict = None) -> bool:
|
||||
client = self._get_client()
|
||||
if client is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Honcho stores messages in sessions
|
||||
# We create a synthetic message to store the preference
|
||||
session_id = f"hermes-prefs-{user_id}"
|
||||
message_content = json.dumps({
|
||||
"type": "preference",
|
||||
"key": key,
|
||||
"value": value,
|
||||
"metadata": metadata or {},
|
||||
"timestamp": time.time(),
|
||||
})
|
||||
client.add_message(
|
||||
session_id=session_id,
|
||||
role="system",
|
||||
content=message_content,
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("Honcho store failed: %s", e)
|
||||
return False
|
||||
|
||||
def retrieve(self, user_id: str, key: str) -> Optional[MemoryEntry]:
|
||||
# Honcho doesn't have direct key-value retrieval
|
||||
# We query for the key and return the latest match
|
||||
results = self.query(user_id, key, limit=1)
|
||||
for entry in results:
|
||||
if entry.key == key:
|
||||
return entry
|
||||
return None
|
||||
|
||||
def query(self, user_id: str, query_text: str, limit: int = 10) -> List[MemoryEntry]:
|
||||
client = self._get_client()
|
||||
if client is None:
|
||||
return []
|
||||
|
||||
try:
|
||||
session_id = f"hermes-prefs-{user_id}"
|
||||
# Use Honcho's dialectic query
|
||||
result = client.chat(
|
||||
session_id=session_id,
|
||||
message=f"Find preferences related to: {query_text}",
|
||||
)
|
||||
|
||||
# Parse the response into memory entries
|
||||
entries = []
|
||||
if isinstance(result, dict):
|
||||
content = result.get("content", "")
|
||||
try:
|
||||
data = json.loads(content)
|
||||
if isinstance(data, list):
|
||||
for item in data[:limit]:
|
||||
entries.append(MemoryEntry(
|
||||
key=item.get("key", ""),
|
||||
value=item.get("value", ""),
|
||||
user_id=user_id,
|
||||
metadata=item.get("metadata", {}),
|
||||
))
|
||||
elif isinstance(data, dict) and data.get("key"):
|
||||
entries.append(MemoryEntry(
|
||||
key=data.get("key", ""),
|
||||
value=data.get("value", ""),
|
||||
user_id=user_id,
|
||||
metadata=data.get("metadata", {}),
|
||||
))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return entries
|
||||
except Exception as e:
|
||||
logger.warning("Honcho query failed: %s", e)
|
||||
return []
|
||||
|
||||
def list_keys(self, user_id: str) -> List[str]:
|
||||
# Query all and extract keys
|
||||
results = self.query(user_id, "", limit=100)
|
||||
return list(dict.fromkeys(e.key for e in results if e.key))
|
||||
|
||||
def delete(self, user_id: str, key: str) -> bool:
|
||||
# Honcho doesn't support deletion of individual entries
|
||||
# This is a limitation of the cloud backend
|
||||
logger.info("Honcho does not support individual entry deletion")
|
||||
return False
|
||||
|
||||
@property
|
||||
def backend_name(self) -> str:
|
||||
return "honcho (cloud)"
|
||||
|
||||
@property
|
||||
def is_cloud(self) -> bool:
|
||||
return True
|
||||
@@ -1,156 +0,0 @@
|
||||
"""Local SQLite memory backend.
|
||||
|
||||
Zero cloud dependency. Stores user preferences and patterns in a
|
||||
local SQLite database at ~/.hermes/memory.db.
|
||||
|
||||
Provides basic key-value storage with simple text search.
|
||||
No external dependencies beyond Python stdlib.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from hermes_constants import get_hermes_home
|
||||
from agent.memory import MemoryBackend, MemoryEntry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LocalBackend(MemoryBackend):
|
||||
"""SQLite-backed local memory storage."""
|
||||
|
||||
def __init__(self, db_path: Path = None):
|
||||
self._db_path = db_path or (get_hermes_home() / "memory.db")
|
||||
self._init_db()
|
||||
|
||||
def _init_db(self):
|
||||
"""Initialize the database schema."""
|
||||
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with sqlite3.connect(str(self._db_path)) as conn:
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
user_id TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
metadata TEXT,
|
||||
created_at REAL NOT NULL,
|
||||
updated_at REAL NOT NULL,
|
||||
PRIMARY KEY (user_id, key)
|
||||
)
|
||||
""")
|
||||
conn.execute("""
|
||||
CREATE INDEX IF NOT EXISTS idx_memories_user
|
||||
ON memories(user_id)
|
||||
""")
|
||||
conn.commit()
|
||||
|
||||
def is_available(self) -> bool:
|
||||
try:
|
||||
with sqlite3.connect(str(self._db_path)) as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def store(self, user_id: str, key: str, value: str, metadata: Dict = None) -> bool:
|
||||
try:
|
||||
now = time.time()
|
||||
meta_json = json.dumps(metadata) if metadata else None
|
||||
with sqlite3.connect(str(self._db_path)) as conn:
|
||||
conn.execute("""
|
||||
INSERT INTO memories (user_id, key, value, metadata, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(user_id, key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
metadata = excluded.metadata,
|
||||
updated_at = excluded.updated_at
|
||||
""", (user_id, key, value, meta_json, now, now))
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("Failed to store memory: %s", e)
|
||||
return False
|
||||
|
||||
def retrieve(self, user_id: str, key: str) -> Optional[MemoryEntry]:
|
||||
try:
|
||||
with sqlite3.connect(str(self._db_path)) as conn:
|
||||
row = conn.execute(
|
||||
"SELECT key, value, user_id, created_at, updated_at, metadata "
|
||||
"FROM memories WHERE user_id = ? AND key = ?",
|
||||
(user_id, key),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return MemoryEntry(
|
||||
key=row[0],
|
||||
value=row[1],
|
||||
user_id=row[2],
|
||||
created_at=row[3],
|
||||
updated_at=row[4],
|
||||
metadata=json.loads(row[5]) if row[5] else {},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to retrieve memory: %s", e)
|
||||
return None
|
||||
|
||||
def query(self, user_id: str, query_text: str, limit: int = 10) -> List[MemoryEntry]:
|
||||
"""Simple LIKE-based search on keys and values."""
|
||||
try:
|
||||
pattern = f"%{query_text}%"
|
||||
with sqlite3.connect(str(self._db_path)) as conn:
|
||||
rows = conn.execute("""
|
||||
SELECT key, value, user_id, created_at, updated_at, metadata
|
||||
FROM memories
|
||||
WHERE user_id = ? AND (key LIKE ? OR value LIKE ?)
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ?
|
||||
""", (user_id, pattern, pattern, limit)).fetchall()
|
||||
return [
|
||||
MemoryEntry(
|
||||
key=r[0],
|
||||
value=r[1],
|
||||
user_id=r[2],
|
||||
created_at=r[3],
|
||||
updated_at=r[4],
|
||||
metadata=json.loads(r[5]) if r[5] else {},
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to query memories: %s", e)
|
||||
return []
|
||||
|
||||
def list_keys(self, user_id: str) -> List[str]:
|
||||
try:
|
||||
with sqlite3.connect(str(self._db_path)) as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT key FROM memories WHERE user_id = ? ORDER BY updated_at DESC",
|
||||
(user_id,),
|
||||
).fetchall()
|
||||
return [r[0] for r in rows]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def delete(self, user_id: str, key: str) -> bool:
|
||||
try:
|
||||
with sqlite3.connect(str(self._db_path)) as conn:
|
||||
conn.execute(
|
||||
"DELETE FROM memories WHERE user_id = ? AND key = ?",
|
||||
(user_id, key),
|
||||
)
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@property
|
||||
def backend_name(self) -> str:
|
||||
return "local (SQLite)"
|
||||
|
||||
@property
|
||||
def is_cloud(self) -> bool:
|
||||
return False
|
||||
@@ -15,7 +15,7 @@ import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
_HERMES_HOME = Path(os.environ.get("HERMES_HOME", Path.home() / ".hermes"))
|
||||
_HERMES_HOME = Path(os.environ.get("HERMES_HOME", str(Path.home() / ".hermes")))
|
||||
DATA_DIR = _HERMES_HOME / "skills" / "productivity" / "memento-flashcards" / "data"
|
||||
CARDS_FILE = DATA_DIR / "cards.json"
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ class OwnedTwilioNumber:
|
||||
|
||||
|
||||
def _hermes_home() -> Path:
|
||||
return Path(os.environ.get("HERMES_HOME", "~/.hermes")).expanduser()
|
||||
return Path(os.environ.get("HERMES_HOME", str(Path.home() / ".hermes")))
|
||||
|
||||
|
||||
def _env_path() -> Path:
|
||||
|
||||
28
run_agent.py
28
run_agent.py
@@ -1001,30 +1001,10 @@ class AIAgent:
|
||||
self._session_db = session_db
|
||||
self._parent_session_id = parent_session_id
|
||||
self._last_flushed_db_idx = 0 # tracks DB-write cursor to prevent duplicate writes
|
||||
if self._session_db:
|
||||
try:
|
||||
self._session_db.create_session(
|
||||
session_id=self.session_id,
|
||||
source=self.platform or os.environ.get("HERMES_SESSION_SOURCE", "cli"),
|
||||
model=self.model,
|
||||
model_config={
|
||||
"max_iterations": self.max_iterations,
|
||||
"reasoning_config": reasoning_config,
|
||||
"max_tokens": max_tokens,
|
||||
},
|
||||
user_id=None,
|
||||
parent_session_id=self._parent_session_id,
|
||||
)
|
||||
except Exception as e:
|
||||
# Transient SQLite lock contention (e.g. CLI and gateway writing
|
||||
# concurrently) must NOT permanently disable session_search for
|
||||
# this agent. Keep _session_db alive — subsequent message
|
||||
# flushes and session_search calls will still work once the
|
||||
# lock clears. The session row may be missing from the index
|
||||
# for this run, but that is recoverable (flushes upsert rows).
|
||||
logger.warning(
|
||||
"Session DB create_session failed (session_search still available): %s", e
|
||||
)
|
||||
# Lazy session creation: defer until first message flush (#314).
|
||||
# _flush_messages_to_session_db() calls ensure_session() which uses
|
||||
# INSERT OR IGNORE — creating the row only when messages arrive.
|
||||
# This eliminates 32% of sessions that are created but never used.
|
||||
|
||||
# In-memory todo list for task planning (one per agent/session)
|
||||
from tools.todo_tool import TodoStore
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
"""Tests for memory backend system (#322)."""
|
||||
|
||||
import json
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.memory import (
|
||||
MemoryEntry,
|
||||
NullBackend,
|
||||
get_memory_backend,
|
||||
reset_backend,
|
||||
)
|
||||
from agent.memory.local_backend import LocalBackend
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def isolated_local_backend(tmp_path, monkeypatch):
|
||||
"""Create a LocalBackend with temp DB."""
|
||||
db_path = tmp_path / "test_memory.db"
|
||||
return LocalBackend(db_path=db_path)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def reset_memory():
|
||||
"""Reset the memory backend singleton."""
|
||||
reset_backend()
|
||||
yield
|
||||
reset_backend()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MemoryEntry
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestMemoryEntry:
|
||||
def test_creation(self):
|
||||
entry = MemoryEntry(key="pref", value="python", user_id="u1")
|
||||
assert entry.key == "pref"
|
||||
assert entry.value == "python"
|
||||
assert entry.created_at > 0
|
||||
|
||||
def test_defaults(self):
|
||||
entry = MemoryEntry(key="k", value="v", user_id="u1")
|
||||
assert entry.metadata == {}
|
||||
assert entry.updated_at == entry.created_at
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# NullBackend
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestNullBackend:
|
||||
def test_always_available(self):
|
||||
backend = NullBackend()
|
||||
assert backend.is_available() is True
|
||||
|
||||
def test_store_noop(self):
|
||||
backend = NullBackend()
|
||||
assert backend.store("u1", "k", "v") is True
|
||||
|
||||
def test_retrieve_returns_none(self):
|
||||
backend = NullBackend()
|
||||
assert backend.retrieve("u1", "k") is None
|
||||
|
||||
def test_query_returns_empty(self):
|
||||
backend = NullBackend()
|
||||
assert backend.query("u1", "test") == []
|
||||
|
||||
def test_not_cloud(self):
|
||||
backend = NullBackend()
|
||||
assert backend.is_cloud is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LocalBackend
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestLocalBackend:
|
||||
def test_available(self, isolated_local_backend):
|
||||
assert isolated_local_backend.is_available() is True
|
||||
|
||||
def test_store_and_retrieve(self, isolated_local_backend):
|
||||
assert isolated_local_backend.store("u1", "lang", "python")
|
||||
entry = isolated_local_backend.retrieve("u1", "lang")
|
||||
assert entry is not None
|
||||
assert entry.value == "python"
|
||||
assert entry.key == "lang"
|
||||
|
||||
def test_store_with_metadata(self, isolated_local_backend):
|
||||
assert isolated_local_backend.store("u1", "k", "v", {"source": "test"})
|
||||
entry = isolated_local_backend.retrieve("u1", "k")
|
||||
assert entry.metadata == {"source": "test"}
|
||||
|
||||
def test_update_existing(self, isolated_local_backend):
|
||||
isolated_local_backend.store("u1", "k", "v1")
|
||||
isolated_local_backend.store("u1", "k", "v2")
|
||||
entry = isolated_local_backend.retrieve("u1", "k")
|
||||
assert entry.value == "v2"
|
||||
|
||||
def test_query(self, isolated_local_backend):
|
||||
isolated_local_backend.store("u1", "pref_python", "True")
|
||||
isolated_local_backend.store("u1", "pref_editor", "vim")
|
||||
isolated_local_backend.store("u1", "theme", "dark")
|
||||
|
||||
results = isolated_local_backend.query("u1", "pref")
|
||||
assert len(results) == 2
|
||||
keys = {r.key for r in results}
|
||||
assert "pref_python" in keys
|
||||
assert "pref_editor" in keys
|
||||
|
||||
def test_list_keys(self, isolated_local_backend):
|
||||
isolated_local_backend.store("u1", "a", "1")
|
||||
isolated_local_backend.store("u1", "b", "2")
|
||||
keys = isolated_local_backend.list_keys("u1")
|
||||
assert set(keys) == {"a", "b"}
|
||||
|
||||
def test_delete(self, isolated_local_backend):
|
||||
isolated_local_backend.store("u1", "k", "v")
|
||||
assert isolated_local_backend.delete("u1", "k")
|
||||
assert isolated_local_backend.retrieve("u1", "k") is None
|
||||
|
||||
def test_retrieve_nonexistent(self, isolated_local_backend):
|
||||
assert isolated_local_backend.retrieve("u1", "nope") is None
|
||||
|
||||
def test_not_cloud(self, isolated_local_backend):
|
||||
assert isolated_local_backend.is_cloud is False
|
||||
|
||||
def test_separate_users(self, isolated_local_backend):
|
||||
isolated_local_backend.store("u1", "k", "user1_value")
|
||||
isolated_local_backend.store("u2", "k", "user2_value")
|
||||
assert isolated_local_backend.retrieve("u1", "k").value == "user1_value"
|
||||
assert isolated_local_backend.retrieve("u2", "k").value == "user2_value"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Singleton
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSingleton:
|
||||
def test_default_is_null(self, reset_memory, monkeypatch):
|
||||
monkeypatch.delenv("HERMES_MEMORY_BACKEND", raising=False)
|
||||
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
|
||||
backend = get_memory_backend()
|
||||
assert isinstance(backend, NullBackend)
|
||||
|
||||
def test_local_when_configured(self, reset_memory, monkeypatch):
|
||||
monkeypatch.setenv("HERMES_MEMORY_BACKEND", "local")
|
||||
backend = get_memory_backend()
|
||||
assert isinstance(backend, LocalBackend)
|
||||
|
||||
def test_caches_instance(self, reset_memory, monkeypatch):
|
||||
monkeypatch.setenv("HERMES_MEMORY_BACKEND", "local")
|
||||
b1 = get_memory_backend()
|
||||
b2 = get_memory_backend()
|
||||
assert b1 is b2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HonchoBackend (mocked)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestHonchoBackend:
|
||||
def test_not_available_without_key(self, monkeypatch):
|
||||
monkeypatch.delenv("HONCHO_API_KEY", raising=False)
|
||||
from agent.memory.honcho_backend import HonchoBackend
|
||||
backend = HonchoBackend()
|
||||
assert backend.is_available() is False
|
||||
|
||||
def test_is_cloud(self):
|
||||
from agent.memory.honcho_backend import HonchoBackend
|
||||
backend = HonchoBackend()
|
||||
assert backend.is_cloud is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Evaluation framework
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestEvaluation:
|
||||
def test_evaluate_null_backend(self):
|
||||
from agent.memory.evaluation import evaluate_backend
|
||||
result = evaluate_backend(NullBackend())
|
||||
assert result.backend_name == "null (disabled)"
|
||||
assert result.available is True
|
||||
assert result.score > 0
|
||||
assert result.is_cloud is False
|
||||
|
||||
def test_evaluate_local_backend(self, isolated_local_backend):
|
||||
from agent.memory.evaluation import evaluate_backend
|
||||
result = evaluate_backend(isolated_local_backend)
|
||||
assert result.backend_name == "local (SQLite)"
|
||||
assert result.available is True
|
||||
assert result.store_success is True
|
||||
assert result.retrieve_success is True
|
||||
assert result.score >= 80 # local should score well
|
||||
|
||||
def test_evaluate_backends_returns_report(self, reset_memory, monkeypatch):
|
||||
monkeypatch.setenv("HERMES_MEMORY_BACKEND", "local")
|
||||
from agent.memory.evaluation import evaluate_backends
|
||||
report = evaluate_backends()
|
||||
assert "backends_evaluated" in report
|
||||
assert report["backends_evaluated"] >= 2 # null + local
|
||||
assert "recommendation" in report
|
||||
@@ -1,165 +0,0 @@
|
||||
"""Memory Backend Tool — manage cross-session memory backends.
|
||||
|
||||
Provides store/retrieve/query/evaluate/list actions for the
|
||||
pluggable memory backend system.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from tools.registry import registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def memory_backend(
|
||||
action: str,
|
||||
user_id: str = "default",
|
||||
key: str = None,
|
||||
value: str = None,
|
||||
query_text: str = None,
|
||||
metadata: dict = None,
|
||||
) -> str:
|
||||
"""Manage cross-session memory backends.
|
||||
|
||||
Actions:
|
||||
store — store a user preference/pattern
|
||||
retrieve — retrieve a specific memory by key
|
||||
query — search memories by text
|
||||
list — list all keys for a user
|
||||
delete — delete a memory entry
|
||||
info — show current backend info
|
||||
evaluate — run evaluation framework comparing backends
|
||||
"""
|
||||
from agent.memory import get_memory_backend
|
||||
|
||||
backend = get_memory_backend()
|
||||
|
||||
if action == "info":
|
||||
return json.dumps({
|
||||
"success": True,
|
||||
"backend": backend.backend_name,
|
||||
"is_cloud": backend.is_cloud,
|
||||
"available": backend.is_available(),
|
||||
})
|
||||
|
||||
if action == "store":
|
||||
if not key or value is None:
|
||||
return json.dumps({"success": False, "error": "key and value are required for 'store'."})
|
||||
success = backend.store(user_id, key, value, metadata)
|
||||
return json.dumps({"success": success, "key": key})
|
||||
|
||||
if action == "retrieve":
|
||||
if not key:
|
||||
return json.dumps({"success": False, "error": "key is required for 'retrieve'."})
|
||||
entry = backend.retrieve(user_id, key)
|
||||
if entry is None:
|
||||
return json.dumps({"success": False, "error": f"No memory found for key '{key}'."})
|
||||
return json.dumps({
|
||||
"success": True,
|
||||
"key": entry.key,
|
||||
"value": entry.value,
|
||||
"metadata": entry.metadata,
|
||||
"updated_at": entry.updated_at,
|
||||
})
|
||||
|
||||
if action == "query":
|
||||
if not query_text:
|
||||
return json.dumps({"success": False, "error": "query_text is required for 'query'."})
|
||||
results = backend.query(user_id, query_text)
|
||||
return json.dumps({
|
||||
"success": True,
|
||||
"results": [
|
||||
{"key": e.key, "value": e.value, "metadata": e.metadata}
|
||||
for e in results
|
||||
],
|
||||
"count": len(results),
|
||||
})
|
||||
|
||||
if action == "list":
|
||||
keys = backend.list_keys(user_id)
|
||||
return json.dumps({"success": True, "keys": keys, "count": len(keys)})
|
||||
|
||||
if action == "delete":
|
||||
if not key:
|
||||
return json.dumps({"success": False, "error": "key is required for 'delete'."})
|
||||
success = backend.delete(user_id, key)
|
||||
return json.dumps({"success": success})
|
||||
|
||||
if action == "evaluate":
|
||||
from agent.memory.evaluation import evaluate_backends
|
||||
report = evaluate_backends()
|
||||
return json.dumps({
|
||||
"success": True,
|
||||
**report,
|
||||
})
|
||||
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"error": f"Unknown action '{action}'. Use: store, retrieve, query, list, delete, info, evaluate",
|
||||
})
|
||||
|
||||
|
||||
MEMORY_BACKEND_SCHEMA = {
|
||||
"name": "memory_backend",
|
||||
"description": (
|
||||
"Manage cross-session memory backends for user preference persistence. "
|
||||
"Pluggable architecture supports local SQLite (default, zero cloud dependency) "
|
||||
"and optional Honcho cloud backend (requires HONCHO_API_KEY).\n\n"
|
||||
"Actions:\n"
|
||||
" store — store a user preference/pattern\n"
|
||||
" retrieve — retrieve a specific memory by key\n"
|
||||
" query — search memories by text\n"
|
||||
" list — list all keys for a user\n"
|
||||
" delete — delete a memory entry\n"
|
||||
" info — show current backend info\n"
|
||||
" evaluate — run evaluation framework comparing backends"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["store", "retrieve", "query", "list", "delete", "info", "evaluate"],
|
||||
"description": "The action to perform.",
|
||||
},
|
||||
"user_id": {
|
||||
"type": "string",
|
||||
"description": "User identifier for memory operations (default: 'default').",
|
||||
},
|
||||
"key": {
|
||||
"type": "string",
|
||||
"description": "Memory key for store/retrieve/delete.",
|
||||
},
|
||||
"value": {
|
||||
"type": "string",
|
||||
"description": "Value to store.",
|
||||
},
|
||||
"query_text": {
|
||||
"type": "string",
|
||||
"description": "Search text for query action.",
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object",
|
||||
"description": "Optional metadata dict for store.",
|
||||
},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
}
|
||||
|
||||
registry.register(
|
||||
name="memory_backend",
|
||||
toolset="skills",
|
||||
schema=MEMORY_BACKEND_SCHEMA,
|
||||
handler=lambda args, **kw: memory_backend(
|
||||
action=args.get("action", ""),
|
||||
user_id=args.get("user_id", "default"),
|
||||
key=args.get("key"),
|
||||
value=args.get("value"),
|
||||
query_text=args.get("query_text"),
|
||||
metadata=args.get("metadata"),
|
||||
),
|
||||
emoji="🧠",
|
||||
)
|
||||
Reference in New Issue
Block a user