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,149 @@
1
+ """Provider-neutral vector index support for memory retrieval."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any, Protocol, Sequence
9
+
10
+ import aiosqlite
11
+
12
+ from .models import MemoryRecord
13
+ from .serializers import json_dumps, json_loads_object
14
+
15
+
16
+ class EmbeddingFunction(Protocol):
17
+ async def __call__(self, text: str) -> Sequence[float]:
18
+ ...
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class VectorSearchResult:
23
+ memory_id: str
24
+ score: float
25
+ metadata: dict[str, Any]
26
+
27
+
28
+ class SQLiteVectorIndex:
29
+ """Small local vector index for RAG memory.
30
+
31
+ This is intentionally provider-neutral: callers own embedding generation,
32
+ while the kit stores vectors and computes cosine similarity locally.
33
+ """
34
+
35
+ def __init__(self, root: str | Path = ".analytics-agent/memory") -> None:
36
+ self.root = Path(root)
37
+ self.db_path = self.root / "memory_vectors.sqlite"
38
+ self.connection: aiosqlite.Connection | None = None
39
+
40
+ async def open(self) -> None:
41
+ if self.connection is not None:
42
+ return
43
+ self.root.mkdir(parents=True, exist_ok=True)
44
+ self.connection = await aiosqlite.connect(self.db_path)
45
+ self.connection.row_factory = aiosqlite.Row
46
+ await self.connection.execute(
47
+ """
48
+ CREATE TABLE IF NOT EXISTS memory_vectors (
49
+ memory_id TEXT PRIMARY KEY,
50
+ vector_json TEXT NOT NULL,
51
+ metadata_json TEXT NOT NULL,
52
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
53
+ )
54
+ """
55
+ )
56
+ await self.connection.commit()
57
+
58
+ async def close(self) -> None:
59
+ if self.connection is not None:
60
+ await self.connection.close()
61
+ self.connection = None
62
+
63
+ async def upsert_memory(self, record: MemoryRecord, embedding: Sequence[float]) -> None:
64
+ metadata = {
65
+ "namespace": record.namespace,
66
+ "memory_type": record.memory_type,
67
+ "scope": record.scope,
68
+ "tenant_id": record.tenant_id,
69
+ "project_id": record.project_id,
70
+ "user_id": record.user_id,
71
+ "privacy_level": record.privacy_level,
72
+ }
73
+ await self.upsert(record.memory_id, embedding, metadata)
74
+
75
+ async def upsert(self, memory_id: str, embedding: Sequence[float], metadata: dict[str, Any] | None = None) -> None:
76
+ if self.connection is None:
77
+ raise RuntimeError("Vector index is not open; await index.open() first.")
78
+ vector = [float(item) for item in embedding]
79
+ if not vector:
80
+ raise ValueError("Embedding vector must not be empty.")
81
+ await self.connection.execute(
82
+ """
83
+ INSERT INTO memory_vectors(memory_id, vector_json, metadata_json, updated_at)
84
+ VALUES (?, ?, ?, CURRENT_TIMESTAMP)
85
+ ON CONFLICT(memory_id) DO UPDATE SET
86
+ vector_json=excluded.vector_json,
87
+ metadata_json=excluded.metadata_json,
88
+ updated_at=excluded.updated_at
89
+ """,
90
+ (memory_id, json_dumps(vector), json_dumps(metadata or {})),
91
+ )
92
+ await self.connection.commit()
93
+
94
+ async def delete(self, memory_id: str) -> bool:
95
+ if self.connection is None:
96
+ raise RuntimeError("Vector index is not open; await index.open() first.")
97
+ cursor = await self.connection.execute("DELETE FROM memory_vectors WHERE memory_id = ?", (memory_id,))
98
+ await self.connection.commit()
99
+ return bool(cursor.rowcount)
100
+
101
+ async def search(
102
+ self,
103
+ embedding: Sequence[float],
104
+ *,
105
+ filters: dict[str, Any] | None = None,
106
+ limit: int = 20,
107
+ min_score: float | None = None,
108
+ ) -> list[VectorSearchResult]:
109
+ if self.connection is None:
110
+ raise RuntimeError("Vector index is not open; await index.open() first.")
111
+ query = [float(item) for item in embedding]
112
+ if not query:
113
+ return []
114
+ filters = {key: value for key, value in (filters or {}).items() if value not in (None, "", [])}
115
+ results: list[VectorSearchResult] = []
116
+ cursor = await self.connection.execute("SELECT memory_id, vector_json, metadata_json FROM memory_vectors")
117
+ rows = await cursor.fetchall()
118
+ for row in rows:
119
+ metadata = json_loads_object(row["metadata_json"], {})
120
+ if not _metadata_matches(metadata, filters):
121
+ continue
122
+ vector = json_loads_object(row["vector_json"], [])
123
+ score = _cosine(query, [float(item) for item in vector])
124
+ if min_score is not None and score < min_score:
125
+ continue
126
+ results.append(VectorSearchResult(str(row["memory_id"]), round(score, 6), metadata))
127
+ results.sort(key=lambda item: item.score, reverse=True)
128
+ return results[: int(limit)]
129
+
130
+
131
+ def _metadata_matches(metadata: dict[str, Any], filters: dict[str, Any]) -> bool:
132
+ for key, value in filters.items():
133
+ if isinstance(value, (list, tuple, set)):
134
+ if metadata.get(key) not in value:
135
+ return False
136
+ elif metadata.get(key) != value:
137
+ return False
138
+ return True
139
+
140
+
141
+ def _cosine(left: Sequence[float], right: Sequence[float]) -> float:
142
+ if len(left) != len(right) or not left:
143
+ return 0.0
144
+ dot = sum(a * b for a, b in zip(left, right))
145
+ left_norm = math.sqrt(sum(a * a for a in left))
146
+ right_norm = math.sqrt(sum(b * b for b in right))
147
+ if not left_norm or not right_norm:
148
+ return 0.0
149
+ return dot / (left_norm * right_norm)
@@ -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,28 @@
1
+ agent_memory/__init__.py,sha256=1n0CVUD7MZGr_KW2OCdyrz6UwunsWlsAjcMrisgYLBo,2213
2
+ agent_memory/cli.py,sha256=GEavZ5NftxSNDuXo1oa4JO9KEwxf4TLsftZxBfpRMAU,4503
3
+ agent_memory/compressor.py,sha256=L-Kuric_2s0VAbZo6pWt03-1aFgSaWfN8c_tKqUfi_A,2000
4
+ agent_memory/config.py,sha256=q5jWf6PZF8Ad-Gt48ObIv0dss957-tLVviSRb9Yi2v0,5583
5
+ agent_memory/conflict.py,sha256=a2rd26qNKJQ7dfZbXCCyfeKyFYG97J9NbM6NEPms76w,3535
6
+ agent_memory/context_packer.py,sha256=zW4ffuAptc_7ovd5fKiPuHN54aWY5YJmTy64UB0nScE,4510
7
+ agent_memory/conversation.py,sha256=B1CcLvrmkZ_VxRmpTSYbxyYxHPzRdGAmdQqMMbDHVQM,8664
8
+ agent_memory/diagnostics.py,sha256=dZsM1cb9py19m_5wygJFBMfpG1oHCLNrcKUwbL7COIE,613
9
+ agent_memory/extractors.py,sha256=80tgnT4GC4emPwh7vQlZRW7nf1fnr4uLi40jDrq_iW0,20261
10
+ agent_memory/jsonl_audit.py,sha256=5RFKM86CDOXptFHLlCFy1FyZo-p3ZmK_9DbOfYC_8CA,1376
11
+ agent_memory/migration.py,sha256=8lXdDKNnpBZK2K2ZiSvd6MjTQ1PnXKTXrXqHIX2y1pE,4705
12
+ agent_memory/models.py,sha256=8fCJ4n8qGrc9FnrMu09BRVoPW0Bcll4f4C-Jf17kWAI,6195
13
+ agent_memory/policy.py,sha256=upY7mxcV9xZ-QlKWpqaB35vj6SovgQMKw-NOwMKe_Jo,3820
14
+ agent_memory/postgres_store.py,sha256=_iaMHjRuPVvkj_E2kirDStWfaN01TqkSLsVUHs8Mucs,20314
15
+ agent_memory/privacy.py,sha256=8X3hJSMQhSVxTJ9dlwZluPbsVo2tEHQ-R7X5hgrQ0zo,4508
16
+ agent_memory/rag.py,sha256=wx2V_lRFRnrzCeOTwKjcrvINcioehmp1BlbcJdDbZ4U,8706
17
+ agent_memory/ranker.py,sha256=TiyRwAEnWwXJgl_vTae1xnkbaN1H9B9Y_0B-shXnbd8,4302
18
+ agent_memory/retriever.py,sha256=_tw1Rsfqb0HUiziihMGY57I1Ktc40ocYLgnLHRN3qSQ,10462
19
+ agent_memory/serializers.py,sha256=kW-C3PMYl60bGZbCcJdDvgWsoc0z-AoOkKueQCWTGi0,3357
20
+ agent_memory/sqlite_store.py,sha256=ePz9muEhdbf1kiGqrgnHzOaU5gMzubMCFrPsS0is8yA,20624
21
+ agent_memory/store.py,sha256=2f-Cc5aMmKY7E8-1mEeZd2-1pfyOUKOqx55noGmmPxM,3787
22
+ agent_memory/token_budget.py,sha256=j8ozk60xj9BjLvdm5dwz7bSgX_9EDrxSWQrcEtT4-l8,537
23
+ agent_memory/vector_index.py,sha256=oBN7h5LCR3-bOpDx5xGgc_svqWv8sHm3vVaYegYCKKc,5807
24
+ agent_memory/defaults/memory.yaml,sha256=P6jTSzLM6Slkve-LK7hmw_faxhPLy8U4q1i7Naj9vTs,507
25
+ data_analytics_agent_memory-0.1.0.dist-info/METADATA,sha256=Qg8LuUYKZaIaQAGCq01Bi_7ZJCInMQEKRaS6yfIXmM8,4612
26
+ data_analytics_agent_memory-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
27
+ data_analytics_agent_memory-0.1.0.dist-info/entry_points.txt,sha256=vDPMoxN0W-13M1_o7eoxzjnbXesFJgMyYQiqxnKAOug,106
28
+ data_analytics_agent_memory-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ agent-memory = agent_memory.cli:main
3
+ agent-memory-migrate = agent_memory.migration:main