eviloomemvault 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.
- eviloomemvault-0.1.0.dist-info/METADATA +260 -0
- eviloomemvault-0.1.0.dist-info/RECORD +31 -0
- eviloomemvault-0.1.0.dist-info/WHEEL +4 -0
- eviloomemvault-0.1.0.dist-info/entry_points.txt +2 -0
- eviloomemvault-0.1.0.dist-info/licenses/LICENSE +21 -0
- memvault/__init__.py +26 -0
- memvault/api/__init__.py +0 -0
- memvault/api/app.py +59 -0
- memvault/api/dependencies.py +28 -0
- memvault/api/routes.py +207 -0
- memvault/api/schemas.py +98 -0
- memvault/cli/__init__.py +0 -0
- memvault/cli/main.py +193 -0
- memvault/core/__init__.py +0 -0
- memvault/core/consolidation.py +166 -0
- memvault/core/models.py +66 -0
- memvault/core/retrieval.py +126 -0
- memvault/core/scoring.py +135 -0
- memvault/embeddings/__init__.py +0 -0
- memvault/embeddings/base.py +34 -0
- memvault/embeddings/local.py +48 -0
- memvault/embeddings/provider.py +18 -0
- memvault/memvault.py +260 -0
- memvault/observability/__init__.py +0 -0
- memvault/observability/logging.py +46 -0
- memvault/observability/metrics.py +56 -0
- memvault/storage/__init__.py +0 -0
- memvault/storage/base.py +107 -0
- memvault/storage/memory.py +70 -0
- memvault/storage/postgres.py +216 -0
- memvault/storage/sqlite.py +187 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: eviloomemvault
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Open Source memory infrastructure for AI agents
|
|
5
|
+
Author: Aryan
|
|
6
|
+
License: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: fastapi>=0.110
|
|
10
|
+
Requires-Dist: pydantic>=2.0
|
|
11
|
+
Requires-Dist: structlog>=24.0
|
|
12
|
+
Requires-Dist: uvicorn>=0.29
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
15
|
+
Requires-Dist: pre-commit; extra == 'dev'
|
|
16
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
17
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
18
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
19
|
+
Provides-Extra: local
|
|
20
|
+
Requires-Dist: sentence-transformers>=3.0; extra == 'local'
|
|
21
|
+
Provides-Extra: postgres
|
|
22
|
+
Requires-Dist: psycopg2-binary>=2.9; extra == 'postgres'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# MemVault
|
|
26
|
+
|
|
27
|
+
> Open-source memory infrastructure for AI agents.
|
|
28
|
+
|
|
29
|
+
[](https://github.com/Aryaneviloo/memvault/actions)
|
|
30
|
+
[](https://www.python.org)
|
|
31
|
+
[](LICENSE)
|
|
32
|
+
|
|
33
|
+
Most AI applications are stateless — they forget users, forget context, and treat every conversation as if it's the first. MemVault solves this by providing a production-grade memory layer that AI agents can plug into.
|
|
34
|
+
|
|
35
|
+
## What it does
|
|
36
|
+
|
|
37
|
+
- **Stores memories** with rich metadata (type, importance, confidence, tags)
|
|
38
|
+
- **Retrieves semantically** — finds relevant memories by meaning, not keyword matching
|
|
39
|
+
- **Ranks intelligently** — combines embedding similarity with recency, importance, and frequency signals
|
|
40
|
+
- **Consolidates automatically** — detects near-duplicate memories and merges them
|
|
41
|
+
- **Decays over time** — unaccessed memories fade; accessed memories are reinforced
|
|
42
|
+
- **Isolates by namespace** — per-user, per-agent, per-project memory pools
|
|
43
|
+
|
|
44
|
+
## Architecture
|
|
45
|
+
┌─────────────────────────────────────┐
|
|
46
|
+
│ Service Layer │
|
|
47
|
+
│ REST API (FastAPI) · CLI (Typer) │
|
|
48
|
+
└─────────────────┬───────────────────┘
|
|
49
|
+
│
|
|
50
|
+
┌─────────────────▼───────────────────┐
|
|
51
|
+
│ Intelligence Layer │
|
|
52
|
+
│ Hybrid Retrieval · Scoring · Decay │
|
|
53
|
+
│ Consolidation · Reinforcement │
|
|
54
|
+
└──────────┬──────────────┬───────────┘
|
|
55
|
+
│ │
|
|
56
|
+
┌──────────▼──────┐ ┌─────▼──────────┐
|
|
57
|
+
│ Storage Layer │ │ Embedding Layer │
|
|
58
|
+
│ SQLite/Postgres│ │ BGE-small (local│
|
|
59
|
+
│ In-Memory │ │ or bring your │
|
|
60
|
+
│ (adapter-based)│ │ own embedder) │
|
|
61
|
+
└─────────────────┘ └────────────────┘
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
## Quick start
|
|
65
|
+
|
|
66
|
+
### As a library
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
pip install memvault
|
|
70
|
+
pip install memvault[local] # for local BGE embeddings
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from memvault.core.models import MemoryItem, MemoryQuery, MemoryType
|
|
75
|
+
from memvault.core.retrieval import retrieve
|
|
76
|
+
from memvault.embeddings.local import LocalEmbedder
|
|
77
|
+
from memvault.storage.sqlite import SQLiteStorage
|
|
78
|
+
from memvault.storage.base import EmbeddingStorageWrapper
|
|
79
|
+
|
|
80
|
+
# Set up the stack
|
|
81
|
+
backend = SQLiteStorage("memories.db")
|
|
82
|
+
embedder = LocalEmbedder()
|
|
83
|
+
store = EmbeddingStorageWrapper(backend=backend, embedder=embedder)
|
|
84
|
+
|
|
85
|
+
# Store a memory
|
|
86
|
+
item = MemoryItem(
|
|
87
|
+
agent_id="my-agent",
|
|
88
|
+
user_id="user-123",
|
|
89
|
+
type=MemoryType.SEMANTIC,
|
|
90
|
+
content="User prefers Python over JavaScript",
|
|
91
|
+
importance=0.8,
|
|
92
|
+
)
|
|
93
|
+
store.insert(item)
|
|
94
|
+
|
|
95
|
+
# Retrieve semantically
|
|
96
|
+
query = MemoryQuery(text="programming language preferences", user_id="user-123")
|
|
97
|
+
results = retrieve(query=query, backend=backend, embedder=embedder)
|
|
98
|
+
|
|
99
|
+
for r in results:
|
|
100
|
+
print(f"[{r.final_score:.3f}] {r.item.content}")
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### As a REST API
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
# With Docker (recommended)
|
|
107
|
+
docker compose -f docker/docker-compose.yml up
|
|
108
|
+
|
|
109
|
+
# Or directly
|
|
110
|
+
uvicorn memvault.api.app:app --reload --port 8000
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
# Store a memory
|
|
115
|
+
curl -X POST http://localhost:8000/memories \
|
|
116
|
+
-H "Content-Type: application/json" \
|
|
117
|
+
-d '{
|
|
118
|
+
"agent_id": "my-agent",
|
|
119
|
+
"user_id": "user-123",
|
|
120
|
+
"content": "User prefers Python over JavaScript",
|
|
121
|
+
"type": "semantic",
|
|
122
|
+
"importance": 0.8
|
|
123
|
+
}'
|
|
124
|
+
|
|
125
|
+
# Search semantically
|
|
126
|
+
curl -X POST http://localhost:8000/memories/search \
|
|
127
|
+
-H "Content-Type: application/json" \
|
|
128
|
+
-d '{
|
|
129
|
+
"text": "programming language preferences",
|
|
130
|
+
"user_id": "user-123"
|
|
131
|
+
}'
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
API docs available at `http://localhost:8000/docs`.
|
|
135
|
+
|
|
136
|
+
### As a CLI
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
memvault remember "User prefers dark mode" --user aryan
|
|
140
|
+
memvault recall "display preferences" --user aryan
|
|
141
|
+
memvault consolidate --user aryan
|
|
142
|
+
memvault doctor
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Installation
|
|
146
|
+
|
|
147
|
+
### Requirements
|
|
148
|
+
|
|
149
|
+
- Python 3.10+
|
|
150
|
+
- Docker (optional, for containerized deployment)
|
|
151
|
+
|
|
152
|
+
### Local development
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
git clone https://github.com/Aryaneviloo/memvault.git
|
|
156
|
+
cd memvault
|
|
157
|
+
|
|
158
|
+
python -m venv venv
|
|
159
|
+
source venv/bin/activate # Windows: venv\Scripts\activate
|
|
160
|
+
|
|
161
|
+
pip install -e ".[local,dev]"
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### Environment variables
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
cp .env.example .env
|
|
168
|
+
# Edit .env with your values
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Running tests
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
# Core test suite (no external dependencies)
|
|
175
|
+
pytest
|
|
176
|
+
|
|
177
|
+
# With PostgreSQL backend
|
|
178
|
+
docker compose -f docker/docker-compose.yml up postgres -d
|
|
179
|
+
TEST_POSTGRES_DSN="postgresql://memvault:memvault@localhost:5433/memvault" pytest
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Memory types
|
|
183
|
+
|
|
184
|
+
| Type | Description | Example |
|
|
185
|
+
|------|-------------|---------|
|
|
186
|
+
| `episodic` | Concrete events and interactions | "User asked about Python on Jan 1" |
|
|
187
|
+
| `semantic` | Stable facts and preferences | "User prefers Python over JavaScript" |
|
|
188
|
+
| `procedural` | Useful workflows and patterns | "Run tests before committing" |
|
|
189
|
+
| `working` | Short-term session context | "Current task: debugging auth module" |
|
|
190
|
+
| `consolidated` | Summaries merged from repeated episodes | Auto-generated by consolidation |
|
|
191
|
+
|
|
192
|
+
## Storage backends
|
|
193
|
+
|
|
194
|
+
| Backend | Use case | Setup |
|
|
195
|
+
|---------|----------|-------|
|
|
196
|
+
| `InMemoryStorage` | Tests, experimentation | Zero setup |
|
|
197
|
+
| `SQLiteStorage` | Local dev, single-process production | Zero setup |
|
|
198
|
+
| `PostgresStorage` | Production, multi-process | Postgres instance required |
|
|
199
|
+
|
|
200
|
+
All backends implement the same interface — swap them with one line of code.
|
|
201
|
+
|
|
202
|
+
## Retrieval scoring
|
|
203
|
+
|
|
204
|
+
Each retrieved memory is scored by:
|
|
205
|
+
final_score = (similarity_weight × cosine_similarity)
|
|
206
|
+
+ (relevance_weight × relevance_score)
|
|
207
|
+
relevance_score = (0.4 × recency) + (0.4 × importance) + (0.2 × frequency)
|
|
208
|
+
|
|
209
|
+
All weights are configurable via `RetrievalConfig` and `ScoringWeights`.
|
|
210
|
+
|
|
211
|
+
## Project structure
|
|
212
|
+
src/memvault/
|
|
213
|
+
├── core/
|
|
214
|
+
│ ├── models.py # MemoryItem, MemoryQuery, MemoryType
|
|
215
|
+
│ ├── scoring.py # Relevance scoring, decay, reinforcement
|
|
216
|
+
│ ├── retrieval.py # Hybrid retrieval pipeline
|
|
217
|
+
│ └── consolidation.py # Near-duplicate detection and merging
|
|
218
|
+
├── storage/
|
|
219
|
+
│ ├── base.py # StorageBackend ABC + EmbeddingStorageWrapper
|
|
220
|
+
│ ├── memory.py # In-memory backend (tests/dev)
|
|
221
|
+
│ ├── sqlite.py # SQLite backend
|
|
222
|
+
│ └── postgres.py # PostgreSQL backend
|
|
223
|
+
├── embeddings/
|
|
224
|
+
│ ├── base.py # BaseEmbedder ABC
|
|
225
|
+
│ ├── local.py # BGE-small via sentence-transformers
|
|
226
|
+
│ └── provider.py # Embedder factory
|
|
227
|
+
├── api/
|
|
228
|
+
│ ├── app.py # FastAPI application factory
|
|
229
|
+
│ ├── routes.py # API endpoints
|
|
230
|
+
│ ├── schemas.py # Request/response models
|
|
231
|
+
│ └── dependencies.py # Dependency injection
|
|
232
|
+
├── cli/
|
|
233
|
+
│ └── main.py # Typer CLI
|
|
234
|
+
└── observability/
|
|
235
|
+
├── logging.py # Structured logging (structlog)
|
|
236
|
+
└── metrics.py # In-process metrics
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
## Roadmap
|
|
240
|
+
|
|
241
|
+
- [x] Core memory engine (storage, scoring, retrieval, consolidation)
|
|
242
|
+
- [x] SQLite and PostgreSQL backends
|
|
243
|
+
- [x] Local BGE embeddings
|
|
244
|
+
- [x] REST API (FastAPI)
|
|
245
|
+
- [x] CLI (Typer)
|
|
246
|
+
- [x] Docker support
|
|
247
|
+
- [ ] `MemVault` facade class (simple single-import API)
|
|
248
|
+
- [ ] LLM-based re-ranking
|
|
249
|
+
- [ ] Auto-ingest from conversation turns
|
|
250
|
+
- [ ] OpenAI / Cohere embedding providers
|
|
251
|
+
- [ ] pgvector support for native vector search
|
|
252
|
+
- [ ] Web dashboard
|
|
253
|
+
|
|
254
|
+
## Contributing
|
|
255
|
+
|
|
256
|
+
See [CONTRIBUTING.md](docs/contributing.md).
|
|
257
|
+
|
|
258
|
+
## License
|
|
259
|
+
|
|
260
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
memvault/__init__.py,sha256=0zy0Jwk6bVRQfPFgzRYkJRQFneUK1HOPKLVX2hk8KB0,652
|
|
2
|
+
memvault/memvault.py,sha256=uVMY2ToRKjEvPliu7sJ-pWtStntc55W9Oc8SoEqwp0Y,8069
|
|
3
|
+
memvault/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
memvault/api/app.py,sha256=VQa0n2K3VRFquL7Mtn2Vr0Fmio49n4qLALH9Nh1BcSI,1501
|
|
5
|
+
memvault/api/dependencies.py,sha256=uJpxj00Y8d4paxbiOsIIV4riN-EApeVpNnEuZiRizzE,866
|
|
6
|
+
memvault/api/routes.py,sha256=9_LbQA29_L_s_qD88Ht0wH-OJhAqsyzoVXiBjh7_va8,5753
|
|
7
|
+
memvault/api/schemas.py,sha256=vF7BVbcENpFqSyMv8ScIB3dMg6ZZlYWq6vS01Wb90jc,2416
|
|
8
|
+
memvault/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
memvault/cli/main.py,sha256=WG46KogVZQafepUG4DF7rTNvjpCom2lsYJo451FZir4,6508
|
|
10
|
+
memvault/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
memvault/core/consolidation.py,sha256=Rd2kBwAiQrUl9pcOWmnxzCib3Ig92pKBjwI66sTIn5Q,4703
|
|
12
|
+
memvault/core/models.py,sha256=sIHxIDeXAo3DMqEhpqInebTM4YnRvH5TPErd-drbmA8,1919
|
|
13
|
+
memvault/core/retrieval.py,sha256=oQVbGfHb6qLyAnzUV_9RH-ncmK7pOF6v-Tmj6PRwPMc,3565
|
|
14
|
+
memvault/core/scoring.py,sha256=1IoGn2w4AtwCucRF1y4EBuFhPEbY_AXmzuKxbiYqX6M,3956
|
|
15
|
+
memvault/embeddings/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
|
+
memvault/embeddings/base.py,sha256=TN8sIavvgwN7CIadRIQGIvwSYH5y5Q7q9aAAF14YKoY,829
|
|
17
|
+
memvault/embeddings/local.py,sha256=Cbgza6Oiov_Hz1qE1Sdgzn6pcpa9TgIU6KLYyFy7G8U,1330
|
|
18
|
+
memvault/embeddings/provider.py,sha256=nmYobsXxlsSR21onD2_UBE-sjoQ7NJGIZAHv6g6_aGE,553
|
|
19
|
+
memvault/observability/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
20
|
+
memvault/observability/logging.py,sha256=_Eo3jcnkWhqPgBcY4wOUV82UMQhBRXzgtlb4CWsTE8w,1337
|
|
21
|
+
memvault/observability/metrics.py,sha256=YHD8DJx6nD2IGNvmsmpJgnCtWV8FrQcoM9jobTyhsf0,1665
|
|
22
|
+
memvault/storage/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
23
|
+
memvault/storage/base.py,sha256=4rG_flyEx2mrShhfgMKlw9bSMKsaDYU67gWYcWMzWlE,3320
|
|
24
|
+
memvault/storage/memory.py,sha256=JdV1jAIlnjzUREbqnRynInxjSL6aPRmfvJzkGP_I-Do,2239
|
|
25
|
+
memvault/storage/postgres.py,sha256=_VQiD2qZpD06fuyLxptIz2D0fcIF3fGjBI5OKwrXci4,6845
|
|
26
|
+
memvault/storage/sqlite.py,sha256=W4GDxdjP_25Jp2OXBeP6aGRpiHtRT7r704w7rcuFYlo,6008
|
|
27
|
+
eviloomemvault-0.1.0.dist-info/METADATA,sha256=8t0jE8XNySyZsI_d86xWMIYWkT3-4d9XMvZ7rXmj64k,8612
|
|
28
|
+
eviloomemvault-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
29
|
+
eviloomemvault-0.1.0.dist-info/entry_points.txt,sha256=RtcWa2ihtRd_vVJz2BFzaV5ZumqHycT64x3j2ntF6wU,52
|
|
30
|
+
eviloomemvault-0.1.0.dist-info/licenses/LICENSE,sha256=XD8dwoxLQDq_ZGtDyiyu1-W2hzN1SyYNirSRMdEyXzc,1061
|
|
31
|
+
eviloomemvault-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aryan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
memvault/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""MemVault - open source infrastructure for AI agents
|
|
2
|
+
|
|
3
|
+
Quick starts:
|
|
4
|
+
from memvault import MemVault
|
|
5
|
+
|
|
6
|
+
mc = MemVault()
|
|
7
|
+
mc.remember("User likes C++", user_id="aryan")
|
|
8
|
+
results = mc.recall("programming preferences", user_id="aryan")
|
|
9
|
+
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from memvault.core.models import MemoryItem, MemoryQuery, MemoryType
|
|
13
|
+
from memvault.core.retrieval import RetrievalConfig, RetrievalResult
|
|
14
|
+
from memvault.core.scoring import ScoringWeights
|
|
15
|
+
from memvault.memvault import MemVault
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
__all__ = [
|
|
19
|
+
"MemVault",
|
|
20
|
+
"MemoryItem",
|
|
21
|
+
"MemoryQuery",
|
|
22
|
+
"MemoryType",
|
|
23
|
+
"RetrievalConfig",
|
|
24
|
+
"RetrievalResult",
|
|
25
|
+
"ScoringWeights",
|
|
26
|
+
]
|
memvault/api/__init__.py
ADDED
|
File without changes
|
memvault/api/app.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
from fastapi import FastAPI, Request, Response
|
|
4
|
+
|
|
5
|
+
from memvault.api.routes import router
|
|
6
|
+
from memvault.observability.logging import get_logger, setup_logging
|
|
7
|
+
from memvault.observability.metrics import get_metrics
|
|
8
|
+
|
|
9
|
+
VERSION = "0.1.0"
|
|
10
|
+
logger = get_logger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def create_app() -> FastAPI:
|
|
14
|
+
"""
|
|
15
|
+
Application factory: creates and configures the FASTAPI app
|
|
16
|
+
Using a factory function (rather than module level app) makes it easier
|
|
17
|
+
to test — tests can call create_app() to get a fresh instance with
|
|
18
|
+
test dependencies injected.
|
|
19
|
+
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
setup_logging()
|
|
23
|
+
|
|
24
|
+
app = FastAPI(
|
|
25
|
+
title="MemVault API",
|
|
26
|
+
description="Open-source memory infrastructure for AI agents",
|
|
27
|
+
version=VERSION,
|
|
28
|
+
docs_url="/docs",
|
|
29
|
+
redoc_url="/redoc",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
@app.middleware("http")
|
|
33
|
+
async def log_requests(request: Request, call_next) -> Response:
|
|
34
|
+
"""
|
|
35
|
+
LOG every request with method, path, status, amd latency
|
|
36
|
+
|
|
37
|
+
"""
|
|
38
|
+
start = time.perf_counter()
|
|
39
|
+
response = await call_next(request)
|
|
40
|
+
latency_ms = (time.perf_counter() - start) * 1000
|
|
41
|
+
|
|
42
|
+
metrics = get_metrics()
|
|
43
|
+
metrics.record_request(latency_ms)
|
|
44
|
+
|
|
45
|
+
logger.info(
|
|
46
|
+
"request",
|
|
47
|
+
method=request.method,
|
|
48
|
+
path=request.url.path,
|
|
49
|
+
status=response.status_code,
|
|
50
|
+
latency_ms=round(latency_ms, 2),
|
|
51
|
+
)
|
|
52
|
+
return response
|
|
53
|
+
|
|
54
|
+
app.include_router(router)
|
|
55
|
+
|
|
56
|
+
return app
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
app = create_app
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from functools import lru_cache
|
|
3
|
+
|
|
4
|
+
from memvault.embeddings.local import LocalEmbedder
|
|
5
|
+
from memvault.storage.base import EmbeddingStorageWrapper
|
|
6
|
+
from memvault.storage.sqlite import SQLiteStorage
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@lru_cache(maxsize=1)
|
|
10
|
+
def get_embedder() -> LocalEmbedder:
|
|
11
|
+
"""
|
|
12
|
+
Load the embedding model once and cache it.
|
|
13
|
+
lru_cache ensures this is only called once per process —
|
|
14
|
+
loading the model is expensive, we don't want to do it per request.
|
|
15
|
+
"""
|
|
16
|
+
return LocalEmbedder()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@lru_cache(maxsize=1)
|
|
20
|
+
def get_storage() -> EmbeddingStorageWrapper:
|
|
21
|
+
"""
|
|
22
|
+
Create the storage backend once and cache it.
|
|
23
|
+
Uses SQLite by default
|
|
24
|
+
Path configurable later via env vars.
|
|
25
|
+
"""
|
|
26
|
+
backend = SQLiteStorage(os.environ.get("DB_PATH", "memories.db"))
|
|
27
|
+
embedder = get_embedder()
|
|
28
|
+
return EmbeddingStorageWrapper(backend=backend, embedder=embedder)
|
memvault/api/routes.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
from fastapi import APIRouter, Depends, HTTPException, status
|
|
2
|
+
|
|
3
|
+
from memvault.api.dependencies import get_embedder, get_storage
|
|
4
|
+
from memvault.api.schemas import (
|
|
5
|
+
ConsolidateRequest,
|
|
6
|
+
ConsolidationResponse,
|
|
7
|
+
CreateMemoryRequest,
|
|
8
|
+
HealthResponse,
|
|
9
|
+
MemoryResponse,
|
|
10
|
+
SearchRequest,
|
|
11
|
+
SearchResultResponse,
|
|
12
|
+
UpdateMemoryRequest,
|
|
13
|
+
)
|
|
14
|
+
from memvault.core.consolidation import ConsolidationConfig, consolidate
|
|
15
|
+
from memvault.core.models import MemoryItem, MemoryQuery
|
|
16
|
+
from memvault.core.retrieval import retrieve
|
|
17
|
+
from memvault.observability.logging import get_logger
|
|
18
|
+
from memvault.observability.metrics import get_metrics
|
|
19
|
+
from memvault.storage.base import EmbeddingStorageWrapper
|
|
20
|
+
|
|
21
|
+
logger = get_logger(__name__)
|
|
22
|
+
|
|
23
|
+
VERSION = "0.1.0"
|
|
24
|
+
|
|
25
|
+
router = APIRouter()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@router.get("/health", response_model=HealthResponse)
|
|
29
|
+
def health_check():
|
|
30
|
+
"""Check that the API is running."""
|
|
31
|
+
return HealthResponse(status="ok", version=VERSION)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@router.post(
|
|
35
|
+
"/memories",
|
|
36
|
+
response_model=MemoryResponse,
|
|
37
|
+
status_code=status.HTTP_201_CREATED,
|
|
38
|
+
)
|
|
39
|
+
def create_memory(
|
|
40
|
+
request: CreateMemoryRequest,
|
|
41
|
+
store: EmbeddingStorageWrapper = Depends(get_storage),
|
|
42
|
+
):
|
|
43
|
+
"""
|
|
44
|
+
Store a new memory.
|
|
45
|
+
Embedding is generated automatically before saving.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
item = MemoryItem(
|
|
49
|
+
agent_id=request.agent_id,
|
|
50
|
+
user_id=request.user_id,
|
|
51
|
+
namespace=request.namespace,
|
|
52
|
+
type=request.type,
|
|
53
|
+
content=request.content,
|
|
54
|
+
importance=request.importance,
|
|
55
|
+
tags=request.tags,
|
|
56
|
+
metadata=request.metadata,
|
|
57
|
+
source=request.source,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
stored = store.insert(item)
|
|
61
|
+
logger.info("memory_created", memory_id=stored.id, user_id=request.user_id)
|
|
62
|
+
return MemoryResponse.model_validate(stored)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@router.get("/memories/{memory_id}", response_model=MemoryResponse)
|
|
66
|
+
def get_memory(
|
|
67
|
+
memory_id: str,
|
|
68
|
+
store: EmbeddingStorageWrapper = Depends(get_storage),
|
|
69
|
+
):
|
|
70
|
+
"""Fetch a single memory by ID."""
|
|
71
|
+
|
|
72
|
+
item = store.get(memory_id)
|
|
73
|
+
if item is None:
|
|
74
|
+
raise HTTPException(
|
|
75
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
76
|
+
detail=f"Memory {memory_id!r} not found",
|
|
77
|
+
)
|
|
78
|
+
return MemoryResponse.model_validate(item)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@router.patch("/memories/{memory_id}", response_model=MemoryResponse)
|
|
82
|
+
def update_memory(
|
|
83
|
+
memory_id: str,
|
|
84
|
+
request: UpdateMemoryRequest,
|
|
85
|
+
store: EmbeddingStorageWrapper = Depends(get_storage),
|
|
86
|
+
):
|
|
87
|
+
"""
|
|
88
|
+
Partially update a memory.
|
|
89
|
+
Only provided fields are updated — others stay as-is.
|
|
90
|
+
Re-embeds automatically if content changed.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
item = store.get(memory_id)
|
|
94
|
+
if item is None:
|
|
95
|
+
raise HTTPException(
|
|
96
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
97
|
+
detail=f"Memory {memory_id!r} not found",
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
if request.content is not None:
|
|
101
|
+
item.content = request.content
|
|
102
|
+
if request.importance is not None:
|
|
103
|
+
item.importance = request.importance
|
|
104
|
+
if request.tags is not None:
|
|
105
|
+
item.tags = request.tags
|
|
106
|
+
if request.metadata is not None:
|
|
107
|
+
item.metadata = request.metadata
|
|
108
|
+
|
|
109
|
+
updated = store.update(item)
|
|
110
|
+
return MemoryResponse.model_validate(updated)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@router.delete("/memories/{memory_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
114
|
+
def delete_memory(
|
|
115
|
+
memory_id: str,
|
|
116
|
+
hard: bool = False,
|
|
117
|
+
store: EmbeddingStorageWrapper = Depends(get_storage),
|
|
118
|
+
):
|
|
119
|
+
"""
|
|
120
|
+
Delete a memory.
|
|
121
|
+
Default is soft delete (recoverable). Pass ?hard=true for permanent deletion.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
deleted = store.delete(memory_id, hard=hard)
|
|
125
|
+
if not deleted:
|
|
126
|
+
raise HTTPException(
|
|
127
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
128
|
+
detail=f"Memory {memory_id!r} not found",
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@router.post("/memories/search", response_model=list[SearchResultResponse])
|
|
133
|
+
def search_memories(
|
|
134
|
+
request: SearchRequest,
|
|
135
|
+
store: EmbeddingStorageWrapper = Depends(get_storage),
|
|
136
|
+
embedder=Depends(get_embedder),
|
|
137
|
+
):
|
|
138
|
+
"""
|
|
139
|
+
Semantic search over memories.
|
|
140
|
+
Returns results ranked by hybrid similarity + relevance score.
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
query = MemoryQuery(
|
|
144
|
+
text=request.text,
|
|
145
|
+
user_id=request.user_id,
|
|
146
|
+
agent_id=request.agent_id,
|
|
147
|
+
namespace=request.namespace,
|
|
148
|
+
types=request.types,
|
|
149
|
+
top_k=request.top_k,
|
|
150
|
+
recency_bias=request.recency_bias,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
results = retrieve(
|
|
154
|
+
query=query,
|
|
155
|
+
backend=store._backend,
|
|
156
|
+
embedder=embedder,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
logger.info(
|
|
160
|
+
"search_performed", query=request.text, user_id=request.user_id, results=len(results)
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
return [
|
|
164
|
+
SearchResultResponse(
|
|
165
|
+
memory=MemoryResponse.model_validate(r.item),
|
|
166
|
+
similarity=r.similarity,
|
|
167
|
+
relevance=r.relevance,
|
|
168
|
+
final_score=r.final_score,
|
|
169
|
+
)
|
|
170
|
+
for r in results
|
|
171
|
+
]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@router.post("/memories/consolidate", response_model=ConsolidationResponse)
|
|
175
|
+
def consolidate_memories(
|
|
176
|
+
request: ConsolidateRequest,
|
|
177
|
+
store: EmbeddingStorageWrapper = Depends(get_storage),
|
|
178
|
+
):
|
|
179
|
+
"""
|
|
180
|
+
Run consolidation for a user's memories.
|
|
181
|
+
Detects near-duplicate memories, merges them, soft-deletes originals.
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
config = ConsolidationConfig(
|
|
185
|
+
similarity_threshold=request.similarity_threshold,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
result = consolidate(
|
|
189
|
+
user_id=request.user_id,
|
|
190
|
+
backend=store._backend,
|
|
191
|
+
agent_id=request.agent_id,
|
|
192
|
+
namespace=request.namespace,
|
|
193
|
+
config=config,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
return ConsolidationResponse(
|
|
197
|
+
clusters_found=result.clusters_found,
|
|
198
|
+
memories_consolidated=result.memories_consolidated,
|
|
199
|
+
consolidated_ids=[item.id for item in result.consolidated_items],
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@router.get("/metrics")
|
|
204
|
+
def metrics_endpoint():
|
|
205
|
+
"""Return current system metrics"""
|
|
206
|
+
|
|
207
|
+
return get_metrics().to_dict()
|