data-analytics-agent-memory 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ """Reusable local memory management kit for agent products."""
2
+
3
+ from .compressor import MemoryCompressor
4
+ from .conflict import MemoryConflictChecker
5
+ from .conversation import (
6
+ AsyncConversationStore,
7
+ ConversationTurn,
8
+ InMemoryConversationStore,
9
+ RedisConversationStore,
10
+ open_conversation_store,
11
+ )
12
+ from .context_packer import ContextPacker
13
+ from .diagnostics import MemoryDiagnostics
14
+ from .extractors import (
15
+ AnalyticsRunMemoryExtractor,
16
+ ClarificationMemoryExtractor,
17
+ MemoryExtractor,
18
+ RAGRetrievalMemoryExtractor,
19
+ UserPreferenceMemoryExtractor,
20
+ )
21
+ from .models import MemoryRecord, RankedMemory, RetrievalQuery
22
+ from .policy import MemoryPolicyEngine
23
+ from .privacy import PrivacyGuard, PrivacyPolicy, PrivacyReport, redact_sensitive
24
+ from .rag import RAGEvidenceValidator, RAGFreshnessChecker, RAGSourceReference, build_source_manifest
25
+ from .retriever import MemoryRetriever
26
+ from .ranker import MemoryRanker
27
+ from .postgres_store import PostgresMemoryStore
28
+ from .sqlite_store import SQLiteMemoryStore
29
+ from .store import MemoryStore, default_memory_root, open_memory_store
30
+ from .vector_index import EmbeddingFunction, SQLiteVectorIndex, VectorSearchResult
31
+
32
+ __all__ = [
33
+ "AnalyticsRunMemoryExtractor",
34
+ "AsyncConversationStore",
35
+ "ClarificationMemoryExtractor",
36
+ "ConversationTurn",
37
+ "ContextPacker",
38
+ "EmbeddingFunction",
39
+ "MemoryCompressor",
40
+ "MemoryConflictChecker",
41
+ "MemoryDiagnostics",
42
+ "MemoryExtractor",
43
+ "MemoryPolicyEngine",
44
+ "MemoryRanker",
45
+ "MemoryRecord",
46
+ "MemoryStore",
47
+ "MemoryRetriever",
48
+ "InMemoryConversationStore",
49
+ "PostgresMemoryStore",
50
+ "PrivacyGuard",
51
+ "PrivacyPolicy",
52
+ "PrivacyReport",
53
+ "RAGEvidenceValidator",
54
+ "RAGFreshnessChecker",
55
+ "RAGRetrievalMemoryExtractor",
56
+ "RAGSourceReference",
57
+ "RedisConversationStore",
58
+ "RankedMemory",
59
+ "RetrievalQuery",
60
+ "SQLiteMemoryStore",
61
+ "SQLiteVectorIndex",
62
+ "UserPreferenceMemoryExtractor",
63
+ "VectorSearchResult",
64
+ "build_source_manifest",
65
+ "default_memory_root",
66
+ "open_memory_store",
67
+ "open_conversation_store",
68
+ "redact_sensitive",
69
+ ]
agent_memory/cli.py ADDED
@@ -0,0 +1,116 @@
1
+ """Project scaffolding commands for agent-memory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+
9
+ def _prompt(label: str, default: str) -> str:
10
+ value = input(f"{label} [{default}]: ").strip()
11
+ return value or default
12
+
13
+
14
+ def initialize_project(
15
+ directory: str | Path = ".",
16
+ *,
17
+ backend: str | None = None,
18
+ env_file: str | None = None,
19
+ force: bool = False,
20
+ interactive: bool = True,
21
+ ) -> list[Path]:
22
+ root = Path(directory).expanduser().resolve()
23
+ root.mkdir(parents=True, exist_ok=True)
24
+ backend = (backend or (_prompt("Storage backend (sqlite/postgres)", "sqlite") if interactive else "sqlite")).casefold()
25
+ if backend not in {"sqlite", "postgres"}:
26
+ raise ValueError("Choose 'sqlite' or 'postgres'.")
27
+ env_file = env_file or (_prompt("Environment file name", ".env") if interactive else ".env")
28
+ env_path = Path(env_file)
29
+ if env_path.is_absolute() or ".." in env_path.parts:
30
+ raise ValueError("Environment file must be a project-relative path without '..'.")
31
+
32
+ config_path = root / "agent-memory.yaml"
33
+ if config_path.exists() and not force:
34
+ raise FileExistsError(f"{config_path} already exists; pass --force to replace it.")
35
+ config_text = f"""# agent-memory settings. PostgreSQL credentials belong in {env_file}, not here.
36
+ backend: {backend}
37
+ env_file: {env_file}
38
+
39
+ postgres:
40
+ # Maximum concurrent database connections for this process.
41
+ pool_size: 20
42
+ pool_timeout_seconds: 10
43
+
44
+ hosting:
45
+ # Increase for hosted traffic after configuring PostgreSQL and Redis.
46
+ max_workers: 1
47
+
48
+ conversation:
49
+ # Use redis for temporary conversation history shared by multiple workers.
50
+ # Install with: pip install "data-analytics-agent-memory[redis]".
51
+ backend: memory
52
+ ttl_seconds: 3600
53
+ max_turns: 6
54
+
55
+ redis:
56
+ # Maximum Redis connections per process when conversation.backend: redis.
57
+ pool_size: 50
58
+ """
59
+ config_path.write_text(config_text, encoding="utf-8")
60
+ created = [config_path]
61
+
62
+ env_path = root / env_path
63
+ env_path.parent.mkdir(parents=True, exist_ok=True)
64
+ if not env_path.exists():
65
+ env_path.write_text(
66
+ "# Keep real credentials private and out of source control.\n"
67
+ "# Required when backend: postgres\n"
68
+ "AGENT_MEMORY_POSTGRES_DSN=\n"
69
+ "# Required when conversation.backend: redis\n"
70
+ "AGENT_MEMORY_REDIS_URL=\n",
71
+ encoding="utf-8",
72
+ )
73
+ created.append(env_path)
74
+
75
+ example_path = root / ".env.example"
76
+ if not example_path.exists():
77
+ example_path.write_text(
78
+ "# Copy this template to the env_file named in agent-memory.yaml.\n"
79
+ "# PostgreSQL only; SQLite needs no database secret.\n"
80
+ "AGENT_MEMORY_POSTGRES_DSN=postgresql://USER:PASSWORD@HOST:5432/DATABASE\n"
81
+ "# Required only when conversation.backend: redis.\n"
82
+ "AGENT_MEMORY_REDIS_URL=redis://:PASSWORD@HOST:6379/0\n",
83
+ encoding="utf-8",
84
+ )
85
+ created.append(example_path)
86
+ return created
87
+
88
+
89
+ def main(argv: list[str] | None = None) -> int:
90
+ parser = argparse.ArgumentParser(prog="agent-memory", description="Initialize agent-memory in a project.")
91
+ subcommands = parser.add_subparsers(dest="command", required=True)
92
+ init = subcommands.add_parser("init", help="Create a commented config and environment-file template.")
93
+ init.add_argument("--directory", default=".", help="Project directory to initialize.")
94
+ init.add_argument("--backend", choices=("sqlite", "postgres"), help="Skip the backend prompt.")
95
+ init.add_argument("--env-file", help="Project-relative env filename; defaults to .env.")
96
+ init.add_argument("--force", action="store_true", help="Replace agent-memory.yaml if it exists.")
97
+ init.add_argument("--non-interactive", action="store_true", help="Use SQLite and .env defaults without prompts.")
98
+ args = parser.parse_args(argv)
99
+ try:
100
+ created = initialize_project(
101
+ args.directory,
102
+ backend=args.backend,
103
+ env_file=args.env_file,
104
+ force=args.force,
105
+ interactive=not args.non_interactive,
106
+ )
107
+ except (FileExistsError, ValueError) as exc:
108
+ parser.error(str(exc))
109
+ for path in created:
110
+ print(f"Created {path}")
111
+ print("PostgreSQL uses AGENT_MEMORY_POSTGRES_DSN from the selected env file; never commit real credentials.")
112
+ return 0
113
+
114
+
115
+ if __name__ == "__main__":
116
+ raise SystemExit(main())
@@ -0,0 +1,43 @@
1
+ """Deterministic memory compression."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+
7
+ from .models import MemoryRecord
8
+ from .serializers import stable_memory_id
9
+
10
+
11
+ class MemoryCompressor:
12
+ """Summarize old run memories while preserving critical evidence."""
13
+
14
+ PROTECTED_TYPES = {"decision_memory", "clarification_memory", "user_preference"}
15
+
16
+ def compress(self, memories: list[MemoryRecord], *, namespace: str = "default") -> list[MemoryRecord]:
17
+ protected = [memory for memory in memories if memory.memory_type in self.PROTECTED_TYPES or memory.value.get("unresolved")]
18
+ grouped: dict[str, list[MemoryRecord]] = defaultdict(list)
19
+ for memory in memories:
20
+ if memory in protected:
21
+ continue
22
+ run_id = str(memory.value.get("run_id") or "")
23
+ if run_id:
24
+ grouped[run_id].append(memory)
25
+ summaries: list[MemoryRecord] = []
26
+ for run_id, records in grouped.items():
27
+ artifact_refs = [ref for record in records for ref in record.evidence_refs]
28
+ keys = [record.key for record in records]
29
+ summaries.append(MemoryRecord(
30
+ memory_id=stable_memory_id(namespace, "run", f"run_summary:{run_id}"),
31
+ memory_type="run_summary",
32
+ scope="run",
33
+ namespace=namespace,
34
+ key=f"run_summary:{run_id}",
35
+ value={"run_id": run_id, "keys": keys, "memory_count": len(records)},
36
+ summary=f"Run {run_id} remembered {len(records)} compact artifact/task records: {', '.join(keys[:8])}.",
37
+ source="memory_compressor",
38
+ evidence_refs=artifact_refs[:20],
39
+ confidence=max((record.confidence for record in records), default=0.7),
40
+ trust_level="system_observed",
41
+ tags=["run_summary", run_id],
42
+ ))
43
+ return [*protected, *summaries]
agent_memory/config.py ADDED
@@ -0,0 +1,114 @@
1
+ """Validated settings for memory storage and hosted request concurrency."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+ from dotenv import dotenv_values
12
+
13
+
14
+ _DEFAULT_CONFIG = Path(__file__).resolve().parent / "defaults" / "memory.yaml"
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class MemorySettings:
19
+ backend: str = "sqlite"
20
+ postgres_pool_size: int = 20
21
+ postgres_pool_timeout: float = 10.0
22
+ max_workers: int = 128
23
+ env_file: str = ".env"
24
+ postgres_dsn: str | None = field(default=None, repr=False)
25
+ conversation_backend: str = "memory"
26
+ conversation_ttl_seconds: int = 3600
27
+ conversation_max_turns: int = 6
28
+ redis_url: str | None = field(default=None, repr=False)
29
+ redis_pool_size: int = 50
30
+
31
+
32
+ def load_memory_settings(path: str | Path | None = None) -> MemorySettings:
33
+ """Load YAML defaults, then apply environment overrides.
34
+
35
+ Explicit function or CLI arguments should override the returned values.
36
+ Connection credentials are hidden from reprs and loaded from the process
37
+ environment or the configured env file.
38
+ """
39
+ project_config = Path.cwd() / "agent-memory.yaml"
40
+ config_path = Path(path) if path is not None else (
41
+ project_config if project_config.is_file() else _DEFAULT_CONFIG
42
+ )
43
+ config_path = config_path.expanduser().resolve()
44
+ defaults: dict[str, Any] = {
45
+ "backend": "sqlite",
46
+ "postgres": {"pool_size": 20, "pool_timeout_seconds": 10.0},
47
+ "hosting": {"max_workers": 128},
48
+ "env_file": ".env",
49
+ }
50
+ try:
51
+ with config_path.open("r", encoding="utf-8") as stream:
52
+ raw: Any = yaml.safe_load(stream) or defaults
53
+ except (OSError, yaml.YAMLError) as exc:
54
+ if path is None and not config_path.exists():
55
+ raw = defaults
56
+ else:
57
+ raise ValueError(f"Unable to read memory configuration: {config_path}") from exc
58
+ if not isinstance(raw, dict):
59
+ raise ValueError("Memory configuration must contain a mapping.")
60
+
61
+ # A configured env file is read relative to the settings file. Real process
62
+ # environment variables take precedence, and secret values are never logged.
63
+ env_file = str(raw.get("env_file", ".env"))
64
+ env_path = Path(env_file).expanduser()
65
+ if not env_path.is_absolute():
66
+ # Project config and explicitly selected config files own their env
67
+ # paths. The packaged fallback config keeps the conventional cwd .env.
68
+ env_root = config_path.parent if path is not None or config_path == project_config.resolve() else Path.cwd()
69
+ env_path = env_root / env_path
70
+ file_env = dotenv_values(env_path) if env_path.is_file() else {}
71
+ def env_value(key: str, fallback: Any) -> Any:
72
+ return os.environ.get(key, file_env.get(key, fallback))
73
+
74
+ postgres = raw.get("postgres", {})
75
+ hosting = raw.get("hosting", {})
76
+ conversation = raw.get("conversation", {})
77
+ redis_settings = raw.get("redis", {})
78
+ if (not isinstance(postgres, dict) or not isinstance(hosting, dict)
79
+ or not isinstance(conversation, dict) or not isinstance(redis_settings, dict)):
80
+ raise ValueError("Memory postgres, hosting, conversation, and redis settings must be mappings.")
81
+ try:
82
+ settings = MemorySettings(
83
+ backend=str(env_value("AGENT_MEMORY_BACKEND", raw.get("backend", "sqlite"))).strip().casefold(),
84
+ postgres_pool_size=int(env_value("AGENT_MEMORY_DB_POOL_SIZE", postgres.get("pool_size", 20))),
85
+ postgres_pool_timeout=float(env_value("AGENT_MEMORY_DB_POOL_TIMEOUT", postgres.get("pool_timeout_seconds", 10))),
86
+ max_workers=int(env_value("AGENT_MEMORY_MAX_WORKERS", hosting.get("max_workers", 128))),
87
+ env_file=env_file,
88
+ postgres_dsn=(os.environ.get("AGENT_MEMORY_POSTGRES_DSN")
89
+ or os.environ.get("DATABASE_URL")
90
+ or file_env.get("AGENT_MEMORY_POSTGRES_DSN")
91
+ or file_env.get("DATABASE_URL")),
92
+ conversation_backend=str(env_value(
93
+ "AGENT_MEMORY_CONVERSATION_BACKEND", conversation.get("backend", "memory")
94
+ )).strip().casefold(),
95
+ conversation_ttl_seconds=int(env_value(
96
+ "AGENT_MEMORY_CONVERSATION_TTL_SECONDS", conversation.get("ttl_seconds", 3600)
97
+ )),
98
+ conversation_max_turns=int(env_value(
99
+ "AGENT_MEMORY_CONVERSATION_MAX_TURNS", conversation.get("max_turns", 6)
100
+ )),
101
+ redis_url=(os.environ.get("AGENT_MEMORY_REDIS_URL") or file_env.get("AGENT_MEMORY_REDIS_URL")),
102
+ redis_pool_size=int(env_value("AGENT_MEMORY_REDIS_POOL_SIZE", redis_settings.get("pool_size", 50))),
103
+ )
104
+ except (TypeError, ValueError) as exc:
105
+ raise ValueError("Memory configuration values have invalid types.") from exc
106
+ if settings.backend not in {"sqlite", "local", "postgres", "postgresql", "pg"}:
107
+ raise ValueError("Memory backend must be sqlite or postgres.")
108
+ if settings.conversation_backend not in {"memory", "local", "redis"}:
109
+ raise ValueError("Conversation backend must be memory or redis.")
110
+ if (settings.postgres_pool_size < 1 or settings.postgres_pool_timeout <= 0 or settings.max_workers < 1
111
+ or settings.conversation_ttl_seconds < 1 or settings.conversation_max_turns < 1
112
+ or settings.redis_pool_size < 1):
113
+ raise ValueError("Memory pool limits, timeout, and worker count must be positive.")
114
+ return settings
@@ -0,0 +1,61 @@
1
+ """Conflict and staleness checks for memory use."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from .models import MemoryConflict, MemoryRecord
8
+
9
+
10
+ class MemoryConflictChecker:
11
+ """Memory must never silently override current user/source evidence."""
12
+
13
+ def check(
14
+ self,
15
+ memories: list[MemoryRecord],
16
+ *,
17
+ current_user_instruction: dict[str, Any] | None = None,
18
+ current_dataset_evidence: dict[str, Any] | None = None,
19
+ current_source_evidence: dict[str, Any] | None = None,
20
+ accepted_decisions: dict[str, Any] | None = None,
21
+ ) -> dict[str, Any]:
22
+ conflicts: list[MemoryConflict] = []
23
+ instruction = current_user_instruction or {}
24
+ dataset = current_dataset_evidence or {}
25
+ decisions = accepted_decisions or {}
26
+ for record in memories:
27
+ if record.status != "active":
28
+ conflicts.append(MemoryConflict(record.memory_id, "status", "high", "Inactive memory cannot be applied.", memory_value=record.status))
29
+ continue
30
+ if record.trust_level in {"stale", "conflicting"}:
31
+ conflicts.append(MemoryConflict(record.memory_id, "trust_level", "medium", "Stale or conflicting memory may only be suggested.", memory_value=record.trust_level))
32
+ metric = record.value.get("metric") or record.value.get("preferred_metric")
33
+ requested_metric = instruction.get("metric") or decisions.get("metric")
34
+ if metric and requested_metric and str(metric).casefold() != str(requested_metric).casefold():
35
+ conflicts.append(MemoryConflict(record.memory_id, "metric", "high", "Current user instruction beats remembered metric.", requested_metric, metric))
36
+ dataset_columns = {str(column).casefold() for column in dataset.get("columns", [])}
37
+ if metric and dataset_columns and str(metric).casefold() not in dataset_columns and record.memory_type in {"user_preference", "task_state"}:
38
+ conflicts.append(MemoryConflict(record.memory_id, "metric", "medium", "Current dataset evidence does not contain the remembered metric.", sorted(dataset_columns), metric))
39
+ dataset_path = dataset.get("source_path")
40
+ remembered_path = record.value.get("source_path") or record.value.get("dataset_path")
41
+ if dataset_path and remembered_path and str(dataset_path) != str(remembered_path) and record.key in {"active_dataset", "active_cleaned_dataset"}:
42
+ conflicts.append(MemoryConflict(record.memory_id, "dataset", "medium", "Current dataset evidence beats previous active dataset memory.", dataset_path, remembered_path))
43
+ if current_source_evidence:
44
+ from .rag import RAGFreshnessChecker
45
+
46
+ source_report = RAGFreshnessChecker().check(memories, current_source_evidence)
47
+ conflicts.extend(MemoryConflict(**item) for item in source_report["conflicts"])
48
+ report = {
49
+ "status": "conflicts_found" if conflicts else "no_conflicts",
50
+ "truth_hierarchy": [
51
+ "current_user_instruction",
52
+ "current_dataset_source_evidence",
53
+ "accepted_current_decisions",
54
+ "project_memory",
55
+ "user_preference_memory",
56
+ "older_durable_memory",
57
+ "inference",
58
+ ],
59
+ "conflicts": [item.to_dict() for item in conflicts],
60
+ }
61
+ return report
@@ -0,0 +1,100 @@
1
+ """Build small memory context packets for the current task."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from .conflict import MemoryConflictChecker
8
+ from .models import MemoryContextPacket, RankedMemory
9
+ from .rag import build_source_manifest
10
+ from .token_budget import estimate_tokens
11
+
12
+
13
+ class ContextPacker:
14
+ def __init__(self, conflict_checker: MemoryConflictChecker | None = None) -> None:
15
+ self.conflict_checker = conflict_checker or MemoryConflictChecker()
16
+
17
+ def pack(
18
+ self,
19
+ *,
20
+ current_request: str,
21
+ active_task_state: dict[str, Any] | None,
22
+ candidate_memories: list[RankedMemory],
23
+ artifact_summaries: list[dict[str, Any]] | None = None,
24
+ retrieved_records: list[dict[str, Any]] | None = None,
25
+ token_budget: int = 8_000,
26
+ reserved_output_tokens: int = 1_500,
27
+ current_dataset_evidence: dict[str, Any] | None = None,
28
+ current_source_evidence: dict[str, Any] | None = None,
29
+ ) -> MemoryContextPacket:
30
+ available = max(256, int(token_budget) - int(reserved_output_tokens))
31
+ active_state = dict(active_task_state or {})
32
+ artifacts = list(artifact_summaries or [])
33
+ records = list(retrieved_records or [])
34
+ conflicts = self.conflict_checker.check(
35
+ [item.record for item in candidate_memories],
36
+ current_user_instruction=active_state.get("user_instruction", {}),
37
+ current_dataset_evidence=current_dataset_evidence or active_state.get("dataset_evidence", {}),
38
+ current_source_evidence=current_source_evidence or active_state.get("source_evidence", {}),
39
+ accepted_decisions=active_state.get("accepted_decisions", {}),
40
+ )
41
+ included: list[dict[str, Any]] = []
42
+ omitted: list[dict[str, Any]] = []
43
+ used = estimate_tokens({"request": current_request, "active_state": active_state, "artifacts": artifacts, "retrieved_records": records, "conflicts": conflicts})
44
+ for ranked in candidate_memories:
45
+ if ranked.score < 6.0 or not _has_strong_relevance(ranked.reasons):
46
+ omitted.append({"memory_id": ranked.record.memory_id, "key": ranked.record.key, "score": ranked.score, "reason": "low_relevance"})
47
+ continue
48
+ payload = {
49
+ "memory_id": ranked.record.memory_id,
50
+ "memory_type": ranked.record.memory_type,
51
+ "scope": ranked.record.scope,
52
+ "key": ranked.record.key,
53
+ "summary": ranked.record.summary,
54
+ "value": ranked.record.value,
55
+ "source": ranked.record.source,
56
+ "evidence_refs": ranked.record.evidence_refs,
57
+ "trust_level": ranked.record.trust_level,
58
+ "confidence": ranked.record.confidence,
59
+ "score": ranked.score,
60
+ }
61
+ cost = estimate_tokens(payload)
62
+ if used + cost <= available:
63
+ included.append(payload)
64
+ used += cost
65
+ else:
66
+ omitted.append({"memory_id": ranked.record.memory_id, "key": ranked.record.key, "score": ranked.score, "reason": "token_budget"})
67
+ packet = {
68
+ "active_state": active_state,
69
+ "relevant_memories": included,
70
+ "source_manifest": build_source_manifest(included),
71
+ "citation_policy": {
72
+ "rag_claims_require_source_refs": True,
73
+ "current_user_and_source_evidence_override_memory": True,
74
+ },
75
+ "relevant_artifacts": artifacts,
76
+ "open_questions": active_state.get("open_questions", []),
77
+ "conflicts": conflicts["conflicts"],
78
+ "retrieved_records": records,
79
+ "omitted_memory_summary": {
80
+ "count": len(omitted),
81
+ "items": omitted[:20],
82
+ },
83
+ }
84
+ budget = {
85
+ "max_tokens": token_budget,
86
+ "estimated_used": used,
87
+ "reserved_output": reserved_output_tokens,
88
+ "available_for_context": available,
89
+ }
90
+ return MemoryContextPacket(packet, budget)
91
+
92
+
93
+ def _has_strong_relevance(reasons: list[str]) -> bool:
94
+ return any(
95
+ reason == "exact_key"
96
+ or reason.startswith("tag:")
97
+ or reason.startswith("entity:")
98
+ or reason.startswith("lexical=")
99
+ for reason in reasons
100
+ )