data-analytics-agent-memory 0.1.0__tar.gz

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.
Files changed (29) hide show
  1. data_analytics_agent_memory-0.1.0/.gitignore +19 -0
  2. data_analytics_agent_memory-0.1.0/PKG-INFO +141 -0
  3. data_analytics_agent_memory-0.1.0/README_AGENT_MEMORY.md +113 -0
  4. data_analytics_agent_memory-0.1.0/docs/AGENT_MEMORY_HOSTING.md +97 -0
  5. data_analytics_agent_memory-0.1.0/pyproject.toml +70 -0
  6. data_analytics_agent_memory-0.1.0/src/agent_memory/__init__.py +69 -0
  7. data_analytics_agent_memory-0.1.0/src/agent_memory/cli.py +116 -0
  8. data_analytics_agent_memory-0.1.0/src/agent_memory/compressor.py +43 -0
  9. data_analytics_agent_memory-0.1.0/src/agent_memory/config.py +114 -0
  10. data_analytics_agent_memory-0.1.0/src/agent_memory/conflict.py +61 -0
  11. data_analytics_agent_memory-0.1.0/src/agent_memory/context_packer.py +100 -0
  12. data_analytics_agent_memory-0.1.0/src/agent_memory/conversation.py +252 -0
  13. data_analytics_agent_memory-0.1.0/src/agent_memory/defaults/memory.yaml +17 -0
  14. data_analytics_agent_memory-0.1.0/src/agent_memory/diagnostics.py +21 -0
  15. data_analytics_agent_memory-0.1.0/src/agent_memory/extractors.py +438 -0
  16. data_analytics_agent_memory-0.1.0/src/agent_memory/jsonl_audit.py +40 -0
  17. data_analytics_agent_memory-0.1.0/src/agent_memory/migration.py +144 -0
  18. data_analytics_agent_memory-0.1.0/src/agent_memory/models.py +183 -0
  19. data_analytics_agent_memory-0.1.0/src/agent_memory/policy.py +81 -0
  20. data_analytics_agent_memory-0.1.0/src/agent_memory/postgres_store.py +424 -0
  21. data_analytics_agent_memory-0.1.0/src/agent_memory/privacy.py +114 -0
  22. data_analytics_agent_memory-0.1.0/src/agent_memory/rag.py +196 -0
  23. data_analytics_agent_memory-0.1.0/src/agent_memory/ranker.py +120 -0
  24. data_analytics_agent_memory-0.1.0/src/agent_memory/retriever.py +213 -0
  25. data_analytics_agent_memory-0.1.0/src/agent_memory/serializers.py +87 -0
  26. data_analytics_agent_memory-0.1.0/src/agent_memory/sqlite_store.py +392 -0
  27. data_analytics_agent_memory-0.1.0/src/agent_memory/store.py +109 -0
  28. data_analytics_agent_memory-0.1.0/src/agent_memory/token_budget.py +18 -0
  29. data_analytics_agent_memory-0.1.0/src/agent_memory/vector_index.py +149 -0
@@ -0,0 +1,19 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .ruff_cache/
5
+ .mypy_cache/
6
+ .coverage
7
+ htmlcov/
8
+ .venv/
9
+ venv/
10
+ dist/
11
+ build/
12
+ *.egg-info/
13
+ .env
14
+ .coding-agent/
15
+
16
+ # Local analytics runs and generated evaluation workspaces
17
+ /.analytics-agent/
18
+ /.analytics-agent-promptfoo/
19
+ /readiness-*/
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.5
2
+ Name: data-analytics-agent-memory
3
+ Version: 0.1.0
4
+ Summary: Async, pluggable memory storage and retrieval components for AI agents.
5
+ Project-URL: Repository, https://gitlab.com/soberonlineemail/data-analytics-assistant
6
+ Keywords: agent,async,memory,postgresql,rag,redis
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: aiofiles>=24.1
17
+ Requires-Dist: aiosqlite>=0.21
18
+ Requires-Dist: python-dotenv>=1.0
19
+ Requires-Dist: pyyaml>=6.0
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
22
+ Requires-Dist: pytest>=8.0; extra == 'dev'
23
+ Provides-Extra: postgres
24
+ Requires-Dist: psycopg[binary,pool]>=3.2; extra == 'postgres'
25
+ Provides-Extra: redis
26
+ Requires-Dist: redis>=5.0; extra == 'redis'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # data-analytics-agent-memory
30
+
31
+ Async memory storage and retrieval building blocks for Python agent
32
+ applications. `agent-memory` provides durable SQLite or PostgreSQL records,
33
+ retrieval and memory policies, plus optional Redis backed temporary
34
+ conversation history. It does not require a particular agent framework,
35
+ embedding model, or vector database.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install data-analytics-agent-memory
41
+ ```
42
+
43
+ Install optional backends only when needed:
44
+
45
+ ```bash
46
+ pip install "data-analytics-agent-memory[postgres]"
47
+ pip install "data-analytics-agent-memory[redis]"
48
+ pip install "data-analytics-agent-memory[postgres,redis]"
49
+ ```
50
+
51
+ SQLite is the default durable store. PostgreSQL is intended for shared hosted
52
+ deployments. Redis stores only temporary conversation turns and is optional.
53
+
54
+ ## Quick start
55
+
56
+ Initialize a project to create a documented `agent-memory.yaml` and an env
57
+ file template:
58
+
59
+ ```bash
60
+ agent-memory init
61
+ ```
62
+
63
+ Use the async store API from your application:
64
+
65
+ ```python
66
+ from agent_memory import MemoryRecord, open_memory_store
67
+
68
+
69
+ async def remember_preference(user_id: str) -> None:
70
+ store = await open_memory_store()
71
+ try:
72
+ await store.upsert(MemoryRecord(
73
+ memory_id=f"preference:{user_id}:theme",
74
+ memory_type="user_preference",
75
+ scope="user",
76
+ namespace="my-agent",
77
+ key="theme",
78
+ value={"theme": "dark"},
79
+ summary="User prefers a dark theme",
80
+ source="user_statement",
81
+ user_id=user_id,
82
+ ))
83
+ matches = await store.search(
84
+ namespace="my-agent",
85
+ user_id=user_id,
86
+ memory_type="user_preference",
87
+ )
88
+ finally:
89
+ await store.close()
90
+ ```
91
+
92
+ ## Temporary conversations
93
+
94
+ Use the separate conversation store for short lived chat context:
95
+
96
+ ```python
97
+ from agent_memory import open_conversation_store
98
+
99
+
100
+ async def save_turn(identity: dict[str, str], conversation_id: str) -> None:
101
+ conversations = await open_conversation_store()
102
+ try:
103
+ prior_turns = await conversations.get_history(identity, conversation_id)
104
+ await conversations.append_turn(
105
+ identity, "What did I ask?", "You asked about deployment.", conversation_id
106
+ )
107
+ finally:
108
+ await conversations.close()
109
+ ```
110
+
111
+ Set `conversation.backend: redis` and `AGENT_MEMORY_REDIS_URL` to share
112
+ conversation history across workers. Conversation keys are isolated by the
113
+ identity mapping and conversation ID, and history is bounded and expires by
114
+ TTL. Use authenticated tenant, project, and user IDs for hosted applications.
115
+
116
+ ## Configuration and commands
117
+
118
+ `agent-memory init` creates a commented config file and documents the secrets
119
+ needed by the selected backends. Secret values belong in the selected env file
120
+ or process environment, never in YAML. Useful commands:
121
+
122
+ ```bash
123
+ agent-memory init --help
124
+ agent-memory-migrate --help
125
+ ```
126
+
127
+ For hosted deployments, configure PostgreSQL for durable shared records and
128
+ Redis for temporary conversation history. Multi-worker mode requires both.
129
+ Set `conversation.backend: redis`, provide `AGENT_MEMORY_REDIS_URL`, and size
130
+ both database pools across all replicas.
131
+
132
+ ## Build and validate distributions
133
+
134
+ ```bash
135
+ python -m pip install build twine
136
+ python -m build
137
+ python -m twine check dist/*
138
+ ```
139
+
140
+ The project is currently in alpha. No license is declared in this repository;
141
+ add the chosen license and metadata before publishing a public release.
@@ -0,0 +1,113 @@
1
+ # data-analytics-agent-memory
2
+
3
+ Async memory storage and retrieval building blocks for Python agent
4
+ applications. `agent-memory` provides durable SQLite or PostgreSQL records,
5
+ retrieval and memory policies, plus optional Redis backed temporary
6
+ conversation history. It does not require a particular agent framework,
7
+ embedding model, or vector database.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install data-analytics-agent-memory
13
+ ```
14
+
15
+ Install optional backends only when needed:
16
+
17
+ ```bash
18
+ pip install "data-analytics-agent-memory[postgres]"
19
+ pip install "data-analytics-agent-memory[redis]"
20
+ pip install "data-analytics-agent-memory[postgres,redis]"
21
+ ```
22
+
23
+ SQLite is the default durable store. PostgreSQL is intended for shared hosted
24
+ deployments. Redis stores only temporary conversation turns and is optional.
25
+
26
+ ## Quick start
27
+
28
+ Initialize a project to create a documented `agent-memory.yaml` and an env
29
+ file template:
30
+
31
+ ```bash
32
+ agent-memory init
33
+ ```
34
+
35
+ Use the async store API from your application:
36
+
37
+ ```python
38
+ from agent_memory import MemoryRecord, open_memory_store
39
+
40
+
41
+ async def remember_preference(user_id: str) -> None:
42
+ store = await open_memory_store()
43
+ try:
44
+ await store.upsert(MemoryRecord(
45
+ memory_id=f"preference:{user_id}:theme",
46
+ memory_type="user_preference",
47
+ scope="user",
48
+ namespace="my-agent",
49
+ key="theme",
50
+ value={"theme": "dark"},
51
+ summary="User prefers a dark theme",
52
+ source="user_statement",
53
+ user_id=user_id,
54
+ ))
55
+ matches = await store.search(
56
+ namespace="my-agent",
57
+ user_id=user_id,
58
+ memory_type="user_preference",
59
+ )
60
+ finally:
61
+ await store.close()
62
+ ```
63
+
64
+ ## Temporary conversations
65
+
66
+ Use the separate conversation store for short lived chat context:
67
+
68
+ ```python
69
+ from agent_memory import open_conversation_store
70
+
71
+
72
+ async def save_turn(identity: dict[str, str], conversation_id: str) -> None:
73
+ conversations = await open_conversation_store()
74
+ try:
75
+ prior_turns = await conversations.get_history(identity, conversation_id)
76
+ await conversations.append_turn(
77
+ identity, "What did I ask?", "You asked about deployment.", conversation_id
78
+ )
79
+ finally:
80
+ await conversations.close()
81
+ ```
82
+
83
+ Set `conversation.backend: redis` and `AGENT_MEMORY_REDIS_URL` to share
84
+ conversation history across workers. Conversation keys are isolated by the
85
+ identity mapping and conversation ID, and history is bounded and expires by
86
+ TTL. Use authenticated tenant, project, and user IDs for hosted applications.
87
+
88
+ ## Configuration and commands
89
+
90
+ `agent-memory init` creates a commented config file and documents the secrets
91
+ needed by the selected backends. Secret values belong in the selected env file
92
+ or process environment, never in YAML. Useful commands:
93
+
94
+ ```bash
95
+ agent-memory init --help
96
+ agent-memory-migrate --help
97
+ ```
98
+
99
+ For hosted deployments, configure PostgreSQL for durable shared records and
100
+ Redis for temporary conversation history. Multi-worker mode requires both.
101
+ Set `conversation.backend: redis`, provide `AGENT_MEMORY_REDIS_URL`, and size
102
+ both database pools across all replicas.
103
+
104
+ ## Build and validate distributions
105
+
106
+ ```bash
107
+ python -m pip install build twine
108
+ python -m build
109
+ python -m twine check dist/*
110
+ ```
111
+
112
+ The project is currently in alpha. No license is declared in this repository;
113
+ add the chosen license and metadata before publishing a public release.
@@ -0,0 +1,97 @@
1
+ # Hosting the memory RAG service
2
+
3
+ ## Initialize a project
4
+
5
+ After installing the distribution that provides the `agent-memory` command,
6
+ run `agent-memory init`. It prompts for SQLite or PostgreSQL and the env
7
+ filename to read. It creates a commented `agent-memory.yaml`, an empty selected
8
+ env file when one does not exist, and `.env.example`. Existing env files are
9
+ left untouched. PostgreSQL reads `AGENT_MEMORY_POSTGRES_DSN` (or
10
+ `DATABASE_URL`) from that file or the process environment; Redis conversation
11
+ history reads `AGENT_MEMORY_REDIS_URL`. Credentials are never copied into YAML
12
+ or printed. Run `agent-memory init --help` for non-interactive and
13
+ custom-directory options.
14
+
15
+ The memory chat server can run concurrent requests when configured with
16
+ PostgreSQL. SQLite remains a single-worker option for local use.
17
+
18
+ Example configuration for one process:
19
+
20
+ ```powershell
21
+ $env:AGENT_MEMORY_BACKEND = "postgres"
22
+ $env:AGENT_MEMORY_POSTGRES_DSN = "postgresql://..."
23
+ $env:AGENT_MEMORY_DB_POOL_SIZE = "20"
24
+ $env:AGENT_MEMORY_CONVERSATION_BACKEND = "redis"
25
+ $env:AGENT_MEMORY_REDIS_URL = "rediss://:PASSWORD@HOST:6379/0"
26
+ python memory_chat_ui.py --host 0.0.0.0 --max-workers 128 --memory-pool-size 20 --trust-identity-headers
27
+ ```
28
+
29
+ The store and retriever APIs are async-only. SQLite uses `aiosqlite` for local
30
+ single-worker use; PostgreSQL uses psycopg's native async connection pool for
31
+ shared hosted use. The PostgreSQL pool is capped at 20 connections per process
32
+ and waiters time out after 10 seconds. Multi-worker hosting also requires Redis
33
+ for shared temporary conversation history. The chat model request is asynchronous;
34
+ the separate document index still performs its indexing and embedding work in
35
+ the bounded request workers.
36
+
37
+ ## Temporary conversation history
38
+
39
+ Conversation turns are kept separately from durable memory records. For local
40
+ single-process development the default `conversation.backend: memory` uses
41
+ process memory. For multiple workers or replicas, install the Redis extra and
42
+ configure a shared Redis service:
43
+
44
+ ```powershell
45
+ pip install "data-analytics-agent-memory[redis]"
46
+ $env:AGENT_MEMORY_CONVERSATION_BACKEND = "redis"
47
+ $env:AGENT_MEMORY_REDIS_URL = "redis://:PASSWORD@HOST:6379/0"
48
+ ```
49
+
50
+ Or set `conversation.backend: redis` in `agent-memory.yaml` and put
51
+ `AGENT_MEMORY_REDIS_URL` in the env file named there. Conversation keys are
52
+ derived from the authenticated tenant, project, user, and optional
53
+ `conversation_id`; raw identity values are not used as Redis keys. History is
54
+ limited to six turns by default and expires one hour after its latest turn.
55
+ Adjust `conversation.max_turns` and `conversation.ttl_seconds` in YAML, or use
56
+ `AGENT_MEMORY_CONVERSATION_MAX_TURNS` and
57
+ `AGENT_MEMORY_CONVERSATION_TTL_SECONDS` overrides. SQLite/PostgreSQL continue
58
+ to hold durable memories, including facts the user explicitly asks to remember.
59
+ The Redis client uses a bounded async connection pool (`redis.pool_size`,
60
+ default 50 per process); budget connections across replicas just as you do for
61
+ PostgreSQL. Configure TLS with a `rediss://` URL when required by the Redis
62
+ provider.
63
+
64
+ Operational defaults live in [`config/memory.yaml`](../config/memory.yaml).
65
+ Pass `--memory-config` to select a different YAML file. CLI flags override the
66
+ selected file, and environment variables override YAML for backend and pool
67
+ settings. Keep the PostgreSQL DSN in `AGENT_MEMORY_POSTGRES_DSN` or
68
+ `DATABASE_URL`; credentials do not belong in YAML. `AGENT_MEMORY_MAX_WORKERS`
69
+ sets the hosted worker default.
70
+
71
+ Size the database connection budget across replicas:
72
+
73
+ ```text
74
+ replica_count * AGENT_MEMORY_DB_POOL_SIZE + migration/admin headroom
75
+ <= PostgreSQL max_connections
76
+ ```
77
+
78
+ For example, four replicas with a pool size of 20 can open up to 80 memory
79
+ connections. Keep the worker count and pool size aligned with the database and
80
+ model service capacity; a larger worker count does not make those dependencies
81
+ faster.
82
+
83
+ Non-loopback binding requires `--trust-identity-headers`. Put the server behind
84
+ an authenticating proxy that strips visitor-supplied `X-Authenticated-*`
85
+ headers and writes trusted `X-Authenticated-Tenant-ID`,
86
+ `X-Authenticated-Project-ID`, and `X-Authenticated-User-ID` values. The server
87
+ rejects API requests missing any of those identities in this mode. Do not
88
+ expose it directly to the public internet or trust those headers from an
89
+ uncontrolled client. Server-path indexing is disabled in this mode; visitors
90
+ must upload documents into their own identity scope.
91
+
92
+ This is bounded-concurrency support, not a demonstrated capacity guarantee.
93
+ Before production rollout, load-test the deployed database, model and embedding
94
+ services with the expected request mix and representative document sizes. The
95
+ optional `SQLiteVectorIndex` is intended for small local indexes; use a
96
+ production vector service or database vector extension for large hosted
97
+ indexes.
@@ -0,0 +1,70 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "data-analytics-agent-memory"
7
+ version = "0.1.0"
8
+ description = "Async, pluggable memory storage and retrieval components for AI agents."
9
+ readme = "README_AGENT_MEMORY.md"
10
+ requires-python = ">=3.11"
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ ]
21
+ keywords = ["agent", "memory", "rag", "async", "redis", "postgresql"]
22
+ dependencies = [
23
+ "aiosqlite>=0.21",
24
+ "aiofiles>=24.1",
25
+ "python-dotenv>=1.0",
26
+ "PyYAML>=6.0",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ dev = [
31
+ "pytest>=8.0",
32
+ "pytest-asyncio>=0.23",
33
+ ]
34
+ postgres = [
35
+ "psycopg[binary,pool]>=3.2",
36
+ ]
37
+ redis = [
38
+ "redis>=5.0",
39
+ ]
40
+
41
+ [project.scripts]
42
+ agent-memory = "agent_memory.cli:main"
43
+ agent-memory-migrate = "agent_memory.migration:main"
44
+
45
+ [project.urls]
46
+ Repository = "https://gitlab.com/soberonlineemail/data-analytics-assistant"
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["src/agent_memory"]
50
+
51
+ [tool.hatch.build.targets.wheel.force-include]
52
+ "src/agent_memory/defaults/memory.yaml" = "agent_memory/defaults/memory.yaml"
53
+
54
+ [tool.hatch.build.targets.sdist]
55
+ include = [
56
+ "src/agent_memory/**",
57
+ "README_AGENT_MEMORY.md",
58
+ "docs/AGENT_MEMORY_HOSTING.md",
59
+ "pyproject.toml",
60
+ ]
61
+
62
+ [tool.pytest.ini_options]
63
+ pythonpath = ["src"]
64
+ testpaths = ["tests"]
65
+ addopts = "-q"
66
+ asyncio_mode = "auto"
67
+
68
+ [tool.ruff]
69
+ line-length = 100
70
+ target-version = "py313"
@@ -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
+ ]
@@ -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]