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.
- agent_memory/__init__.py +69 -0
- agent_memory/cli.py +116 -0
- agent_memory/compressor.py +43 -0
- agent_memory/config.py +114 -0
- agent_memory/conflict.py +61 -0
- agent_memory/context_packer.py +100 -0
- agent_memory/conversation.py +252 -0
- agent_memory/defaults/memory.yaml +17 -0
- agent_memory/diagnostics.py +21 -0
- agent_memory/extractors.py +438 -0
- agent_memory/jsonl_audit.py +40 -0
- agent_memory/migration.py +144 -0
- agent_memory/models.py +183 -0
- agent_memory/policy.py +81 -0
- agent_memory/postgres_store.py +424 -0
- agent_memory/privacy.py +114 -0
- agent_memory/rag.py +196 -0
- agent_memory/ranker.py +120 -0
- agent_memory/retriever.py +213 -0
- agent_memory/serializers.py +87 -0
- agent_memory/sqlite_store.py +392 -0
- agent_memory/store.py +109 -0
- agent_memory/token_budget.py +18 -0
- agent_memory/vector_index.py +149 -0
- data_analytics_agent_memory-0.1.0.dist-info/METADATA +141 -0
- data_analytics_agent_memory-0.1.0.dist-info/RECORD +28 -0
- data_analytics_agent_memory-0.1.0.dist-info/WHEEL +4 -0
- data_analytics_agent_memory-0.1.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""Async short-lived conversation state backends.
|
|
2
|
+
|
|
3
|
+
Conversation context is deliberately separate from durable ``MemoryStore``
|
|
4
|
+
records: it is bounded, expires automatically, and is safe to share across
|
|
5
|
+
application workers when backed by Redis.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from hashlib import sha256
|
|
12
|
+
import json
|
|
13
|
+
import time
|
|
14
|
+
from typing import Any, Protocol
|
|
15
|
+
|
|
16
|
+
from .config import MemorySettings, load_memory_settings
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
ConversationTurn = dict[str, str]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AsyncConversationStore(Protocol):
|
|
23
|
+
async def open(self) -> None: ...
|
|
24
|
+
|
|
25
|
+
async def close(self) -> None: ...
|
|
26
|
+
|
|
27
|
+
async def get_history(
|
|
28
|
+
self, identity: Mapping[str, str], conversation_id: str = "default"
|
|
29
|
+
) -> list[ConversationTurn]: ...
|
|
30
|
+
|
|
31
|
+
async def append_turn(
|
|
32
|
+
self,
|
|
33
|
+
identity: Mapping[str, str],
|
|
34
|
+
user_message: str,
|
|
35
|
+
assistant_message: str,
|
|
36
|
+
conversation_id: str = "default",
|
|
37
|
+
) -> None: ...
|
|
38
|
+
|
|
39
|
+
async def clear(
|
|
40
|
+
self, identity: Mapping[str, str], conversation_id: str = "default"
|
|
41
|
+
) -> None: ...
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class InMemoryConversationStore:
|
|
45
|
+
"""Single-process development backend with TTL and bounded history."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, *, ttl_seconds: int = 3600, max_turns: int = 6) -> None:
|
|
48
|
+
self.ttl_seconds = ttl_seconds
|
|
49
|
+
self.max_turns = max_turns
|
|
50
|
+
self._turns: dict[str, tuple[float, list[ConversationTurn]]] = {}
|
|
51
|
+
|
|
52
|
+
async def open(self) -> None:
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
async def close(self) -> None:
|
|
56
|
+
self._turns.clear()
|
|
57
|
+
|
|
58
|
+
def _key(self, identity: Mapping[str, str], conversation_id: str) -> str:
|
|
59
|
+
material = json.dumps(
|
|
60
|
+
{"identity": dict(identity), "conversation_id": conversation_id},
|
|
61
|
+
sort_keys=True,
|
|
62
|
+
separators=(",", ":"),
|
|
63
|
+
)
|
|
64
|
+
return sha256(material.encode("utf-8")).hexdigest()
|
|
65
|
+
|
|
66
|
+
async def get_history(
|
|
67
|
+
self, identity: Mapping[str, str], conversation_id: str = "default"
|
|
68
|
+
) -> list[ConversationTurn]:
|
|
69
|
+
key = self._key(identity, conversation_id)
|
|
70
|
+
entry = self._turns.get(key)
|
|
71
|
+
if entry is None:
|
|
72
|
+
return []
|
|
73
|
+
expires_at, turns = entry
|
|
74
|
+
if expires_at <= time.monotonic():
|
|
75
|
+
self._turns.pop(key, None)
|
|
76
|
+
return []
|
|
77
|
+
return [dict(turn) for turn in turns]
|
|
78
|
+
|
|
79
|
+
async def append_turn(
|
|
80
|
+
self,
|
|
81
|
+
identity: Mapping[str, str],
|
|
82
|
+
user_message: str,
|
|
83
|
+
assistant_message: str,
|
|
84
|
+
conversation_id: str = "default",
|
|
85
|
+
) -> None:
|
|
86
|
+
key = self._key(identity, conversation_id)
|
|
87
|
+
turns = await self.get_history(identity, conversation_id)
|
|
88
|
+
turns.append({"user": user_message[:800], "assistant": assistant_message[:800]})
|
|
89
|
+
self._turns[key] = (time.monotonic() + self.ttl_seconds, turns[-self.max_turns :])
|
|
90
|
+
|
|
91
|
+
async def clear(
|
|
92
|
+
self, identity: Mapping[str, str], conversation_id: str = "default"
|
|
93
|
+
) -> None:
|
|
94
|
+
self._turns.pop(self._key(identity, conversation_id), None)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class RedisConversationStore:
|
|
98
|
+
"""Redis list-based store for shared, expiring conversation history."""
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
redis_url: str,
|
|
103
|
+
*,
|
|
104
|
+
ttl_seconds: int = 3600,
|
|
105
|
+
max_turns: int = 6,
|
|
106
|
+
pool_size: int = 50,
|
|
107
|
+
key_prefix: str = "agent-memory:conversation:",
|
|
108
|
+
client: Any | None = None,
|
|
109
|
+
) -> None:
|
|
110
|
+
if not redis_url and client is None:
|
|
111
|
+
raise ValueError("Redis conversation backend requires AGENT_MEMORY_REDIS_URL.")
|
|
112
|
+
if ttl_seconds < 1 or max_turns < 1 or pool_size < 1:
|
|
113
|
+
raise ValueError("Conversation TTL, max_turns, and Redis pool size must be positive.")
|
|
114
|
+
self.redis_url = redis_url
|
|
115
|
+
self.ttl_seconds = ttl_seconds
|
|
116
|
+
self.max_turns = max_turns
|
|
117
|
+
self.pool_size = pool_size
|
|
118
|
+
self.key_prefix = key_prefix
|
|
119
|
+
self._client = client
|
|
120
|
+
|
|
121
|
+
async def open(self) -> None:
|
|
122
|
+
if self._client is None:
|
|
123
|
+
try:
|
|
124
|
+
from redis.asyncio import BlockingConnectionPool, Redis
|
|
125
|
+
except ImportError as exc:
|
|
126
|
+
raise RuntimeError(
|
|
127
|
+
"Redis conversation support requires `pip install 'data-analytics-agent-memory[redis]'`."
|
|
128
|
+
) from exc
|
|
129
|
+
pool = BlockingConnectionPool.from_url(
|
|
130
|
+
self.redis_url,
|
|
131
|
+
decode_responses=True,
|
|
132
|
+
max_connections=self.pool_size,
|
|
133
|
+
timeout=10,
|
|
134
|
+
socket_connect_timeout=2,
|
|
135
|
+
socket_timeout=2,
|
|
136
|
+
)
|
|
137
|
+
self._client = Redis(connection_pool=pool)
|
|
138
|
+
await self._client.ping()
|
|
139
|
+
|
|
140
|
+
async def close(self) -> None:
|
|
141
|
+
if self._client is not None:
|
|
142
|
+
close = getattr(self._client, "aclose", None)
|
|
143
|
+
if close is not None:
|
|
144
|
+
try:
|
|
145
|
+
await close(close_connection_pool=True)
|
|
146
|
+
except TypeError:
|
|
147
|
+
await close()
|
|
148
|
+
else:
|
|
149
|
+
result = self._client.close()
|
|
150
|
+
if hasattr(result, "__await__"):
|
|
151
|
+
await result
|
|
152
|
+
self._client = None
|
|
153
|
+
|
|
154
|
+
def _key(self, identity: Mapping[str, str], conversation_id: str) -> str:
|
|
155
|
+
material = json.dumps(
|
|
156
|
+
{"identity": dict(identity), "conversation_id": conversation_id},
|
|
157
|
+
sort_keys=True,
|
|
158
|
+
separators=(",", ":"),
|
|
159
|
+
)
|
|
160
|
+
return self.key_prefix + sha256(material.encode("utf-8")).hexdigest()
|
|
161
|
+
|
|
162
|
+
async def get_history(
|
|
163
|
+
self, identity: Mapping[str, str], conversation_id: str = "default"
|
|
164
|
+
) -> list[ConversationTurn]:
|
|
165
|
+
if self._client is None:
|
|
166
|
+
await self.open()
|
|
167
|
+
rows = await self._client.lrange(
|
|
168
|
+
self._key(identity, conversation_id), -self.max_turns, -1
|
|
169
|
+
)
|
|
170
|
+
turns = []
|
|
171
|
+
for row in rows:
|
|
172
|
+
try:
|
|
173
|
+
value = json.loads(row)
|
|
174
|
+
except (TypeError, ValueError):
|
|
175
|
+
continue
|
|
176
|
+
if isinstance(value, dict):
|
|
177
|
+
user = value.get("user")
|
|
178
|
+
assistant = value.get("assistant")
|
|
179
|
+
if isinstance(user, str) and isinstance(assistant, str):
|
|
180
|
+
turns.append({"user": user, "assistant": assistant})
|
|
181
|
+
return turns
|
|
182
|
+
|
|
183
|
+
async def append_turn(
|
|
184
|
+
self,
|
|
185
|
+
identity: Mapping[str, str],
|
|
186
|
+
user_message: str,
|
|
187
|
+
assistant_message: str,
|
|
188
|
+
conversation_id: str = "default",
|
|
189
|
+
) -> None:
|
|
190
|
+
if self._client is None:
|
|
191
|
+
await self.open()
|
|
192
|
+
key = self._key(identity, conversation_id)
|
|
193
|
+
payload = json.dumps(
|
|
194
|
+
{"user": user_message[:800], "assistant": assistant_message[:800]},
|
|
195
|
+
ensure_ascii=False,
|
|
196
|
+
separators=(",", ":"),
|
|
197
|
+
)
|
|
198
|
+
async with self._client.pipeline(transaction=True) as pipe:
|
|
199
|
+
pipe.rpush(key, payload)
|
|
200
|
+
pipe.ltrim(key, -self.max_turns, -1)
|
|
201
|
+
pipe.expire(key, self.ttl_seconds)
|
|
202
|
+
await pipe.execute()
|
|
203
|
+
|
|
204
|
+
async def clear(
|
|
205
|
+
self, identity: Mapping[str, str], conversation_id: str = "default"
|
|
206
|
+
) -> None:
|
|
207
|
+
if self._client is None:
|
|
208
|
+
await self.open()
|
|
209
|
+
await self._client.delete(self._key(identity, conversation_id))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
async def open_conversation_store(
|
|
213
|
+
settings: MemorySettings | None = None,
|
|
214
|
+
*,
|
|
215
|
+
memory_config_path: str | None = None,
|
|
216
|
+
) -> AsyncConversationStore:
|
|
217
|
+
"""Open the configured temporary conversation backend."""
|
|
218
|
+
settings = settings or load_memory_settings(memory_config_path)
|
|
219
|
+
if settings.conversation_backend in {"memory", "local"}:
|
|
220
|
+
store: AsyncConversationStore = InMemoryConversationStore(
|
|
221
|
+
ttl_seconds=settings.conversation_ttl_seconds,
|
|
222
|
+
max_turns=settings.conversation_max_turns,
|
|
223
|
+
)
|
|
224
|
+
elif settings.conversation_backend == "redis":
|
|
225
|
+
if not settings.redis_url:
|
|
226
|
+
raise ValueError(
|
|
227
|
+
"Redis conversation backend requires AGENT_MEMORY_REDIS_URL in the process "
|
|
228
|
+
"environment or configured env file."
|
|
229
|
+
)
|
|
230
|
+
store = RedisConversationStore(
|
|
231
|
+
settings.redis_url,
|
|
232
|
+
ttl_seconds=settings.conversation_ttl_seconds,
|
|
233
|
+
max_turns=settings.conversation_max_turns,
|
|
234
|
+
pool_size=settings.redis_pool_size,
|
|
235
|
+
)
|
|
236
|
+
else:
|
|
237
|
+
raise ValueError(f"Unsupported conversation backend: {settings.conversation_backend!r}.")
|
|
238
|
+
try:
|
|
239
|
+
await store.open()
|
|
240
|
+
except Exception:
|
|
241
|
+
await store.close()
|
|
242
|
+
raise
|
|
243
|
+
return store
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
__all__ = [
|
|
247
|
+
"AsyncConversationStore",
|
|
248
|
+
"ConversationTurn",
|
|
249
|
+
"InMemoryConversationStore",
|
|
250
|
+
"RedisConversationStore",
|
|
251
|
+
"open_conversation_store",
|
|
252
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Operational defaults for the memory subsystem. Keep credentials in the
|
|
2
|
+
# process environment or the project's selected env file, never in this file.
|
|
3
|
+
backend: sqlite
|
|
4
|
+
env_file: .env
|
|
5
|
+
postgres:
|
|
6
|
+
pool_size: 20
|
|
7
|
+
pool_timeout_seconds: 10
|
|
8
|
+
hosting:
|
|
9
|
+
max_workers: 128
|
|
10
|
+
conversation:
|
|
11
|
+
# Use redis for temporary conversation history shared by multiple workers.
|
|
12
|
+
# The in-memory backend is intended for local, single-process development.
|
|
13
|
+
backend: memory
|
|
14
|
+
ttl_seconds: 3600
|
|
15
|
+
max_turns: 6
|
|
16
|
+
redis:
|
|
17
|
+
pool_size: 50
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Diagnostics for memory stores."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .store import MemoryStore
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MemoryDiagnostics:
|
|
9
|
+
def __init__(self, store: MemoryStore) -> None:
|
|
10
|
+
self.store = store
|
|
11
|
+
|
|
12
|
+
async def doctor(self) -> dict[str, object]:
|
|
13
|
+
stats = await self.store.stats()
|
|
14
|
+
recent_audit = await self.store.audit.read_recent(5)
|
|
15
|
+
active = await self.store.list_active(limit=10)
|
|
16
|
+
return {
|
|
17
|
+
**stats,
|
|
18
|
+
"active_sample_count": len(active),
|
|
19
|
+
"recent_audit_events": recent_audit,
|
|
20
|
+
"problems": [],
|
|
21
|
+
}
|