mintmory-api 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.
- mintmory/api/__init__.py +1 -0
- mintmory/api/app.py +559 -0
- mintmory/api/py.typed +0 -0
- mintmory/api/schemas.py +144 -0
- mintmory_api-0.1.0.dist-info/METADATA +33 -0
- mintmory_api-0.1.0.dist-info/RECORD +9 -0
- mintmory_api-0.1.0.dist-info/WHEEL +4 -0
- mintmory_api-0.1.0.dist-info/entry_points.txt +2 -0
- mintmory_api-0.1.0.dist-info/licenses/LICENSE +21 -0
mintmory/api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""mintmory-api: FastAPI HTTP REST API."""
|
mintmory/api/app.py
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MintMory FastAPI application — M6 implementation target.
|
|
3
|
+
|
|
4
|
+
All routes conform to docs/openapi/mintmory.yaml. This REST surface is a thin
|
|
5
|
+
transport over the frozen ``mintmory.core`` service layer: every route validates
|
|
6
|
+
its request, calls one or more core functions, and serialises the canonical
|
|
7
|
+
``types.py`` models back to the client. No domain logic lives here.
|
|
8
|
+
|
|
9
|
+
Run: uvicorn mintmory.api.app:app --port 8080
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import AsyncGenerator, Callable
|
|
15
|
+
from contextlib import asynccontextmanager
|
|
16
|
+
from typing import Annotated
|
|
17
|
+
|
|
18
|
+
import anyio
|
|
19
|
+
import anyio.to_thread
|
|
20
|
+
from fastapi import FastAPI, HTTPException, Query
|
|
21
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
22
|
+
from mintmory.api.schemas import (
|
|
23
|
+
CaptionRunRequest,
|
|
24
|
+
ConceptLinkCreate,
|
|
25
|
+
DreamRequest,
|
|
26
|
+
ImageCaptionPut,
|
|
27
|
+
MemoryCreate,
|
|
28
|
+
MemoryUpdate,
|
|
29
|
+
NoteCreate,
|
|
30
|
+
SessionFeedback,
|
|
31
|
+
SummaryPut,
|
|
32
|
+
)
|
|
33
|
+
from mintmory.core import session as session_module
|
|
34
|
+
from mintmory.core.config import load_settings
|
|
35
|
+
from mintmory.core.dreaming import DreamingEngine
|
|
36
|
+
from mintmory.core.llm import build_dreaming_engine
|
|
37
|
+
from mintmory.core.ports import StorageBackend
|
|
38
|
+
from mintmory.core.storage_factory import build_storage
|
|
39
|
+
from mintmory.core.telemetry import init_telemetry
|
|
40
|
+
from mintmory.core.types import (
|
|
41
|
+
SYMMETRIC_LINK_TYPES,
|
|
42
|
+
CaptionRunReport,
|
|
43
|
+
ConceptLink,
|
|
44
|
+
ConceptLinkType,
|
|
45
|
+
DreamIntensity,
|
|
46
|
+
DreamReport,
|
|
47
|
+
ImageDescription,
|
|
48
|
+
ImageJob,
|
|
49
|
+
LinkSource,
|
|
50
|
+
MemoryRecord,
|
|
51
|
+
MemoryStats,
|
|
52
|
+
MemorySummary,
|
|
53
|
+
NoteResult,
|
|
54
|
+
QuerySession,
|
|
55
|
+
SearchRequest,
|
|
56
|
+
SearchResponse,
|
|
57
|
+
SummaryJob,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# ---------------------------------------------------------------------------
|
|
61
|
+
# App lifecycle
|
|
62
|
+
# ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
_store: StorageBackend | None = None
|
|
65
|
+
|
|
66
|
+
# ---------------------------------------------------------------------------
|
|
67
|
+
# Thread-offload helper (design §6.3 Phase 2 requirement)
|
|
68
|
+
# ---------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
async def _db[T](call: Callable[[], T]) -> T:
|
|
72
|
+
"""Run a blocking storage call in anyio's default worker-thread pool.
|
|
73
|
+
|
|
74
|
+
Required for Postgres mode: psycopg3's synchronous pool blocks the event loop,
|
|
75
|
+
serialising concurrent requests and risking liveness-probe stalls on slow queries.
|
|
76
|
+
Running the call in a thread allows other requests (including /healthz) to be
|
|
77
|
+
served concurrently. SQLite is also acceptable inline, but wrapping it here is
|
|
78
|
+
harmless and keeps the code path uniform.
|
|
79
|
+
"""
|
|
80
|
+
return await anyio.to_thread.run_sync(call)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@asynccontextmanager
|
|
84
|
+
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
85
|
+
global _store
|
|
86
|
+
settings = load_settings()
|
|
87
|
+
# build_storage() resolves path from StorageSettings / MINTMORY_DB / default,
|
|
88
|
+
# creates the parent directory, and returns an uninitialised backend.
|
|
89
|
+
# NO embedder — API-added memories get NULL embeddings (asymmetry vs CLI).
|
|
90
|
+
_store = build_storage(settings.storage)
|
|
91
|
+
_store.initialise()
|
|
92
|
+
init_telemetry(settings.otel)
|
|
93
|
+
|
|
94
|
+
# Startup guard (design §6.3): cap anyio's default thread-limiter to at most
|
|
95
|
+
# pool_max so we never queue more DB threads than the pool can serve.
|
|
96
|
+
# This prevents thread starvation when pool_max < anyio's default (40).
|
|
97
|
+
pool_max = settings.storage.pool_max
|
|
98
|
+
limiter = anyio.to_thread.current_default_thread_limiter()
|
|
99
|
+
if limiter.total_tokens > pool_max:
|
|
100
|
+
limiter.total_tokens = pool_max
|
|
101
|
+
|
|
102
|
+
yield
|
|
103
|
+
if _store:
|
|
104
|
+
_store.close()
|
|
105
|
+
_store = None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
app = FastAPI(
|
|
109
|
+
title="MintMory Memory API",
|
|
110
|
+
version="0.1.0",
|
|
111
|
+
description=(
|
|
112
|
+
"Palantir-Ontology-inspired typed memory for LLM agents. "
|
|
113
|
+
"See docs/openapi/mintmory.yaml for the full contract."
|
|
114
|
+
),
|
|
115
|
+
lifespan=lifespan,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
app.add_middleware(
|
|
119
|
+
CORSMiddleware,
|
|
120
|
+
allow_origins=["*"],
|
|
121
|
+
allow_methods=["*"],
|
|
122
|
+
allow_headers=["*"],
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def get_store() -> StorageBackend:
|
|
127
|
+
if _store is None:
|
|
128
|
+
raise RuntimeError("Storage not initialised — lifespan not run")
|
|
129
|
+
return _store
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ---------------------------------------------------------------------------
|
|
133
|
+
# Health
|
|
134
|
+
# ---------------------------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@app.get("/healthz", tags=["Health"])
|
|
138
|
+
async def healthz() -> dict[str, str]:
|
|
139
|
+
"""Liveness probe — no DB touch."""
|
|
140
|
+
return {"status": "ok"}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@app.get("/readyz", tags=["Health"])
|
|
144
|
+
async def readyz() -> dict[str, str]:
|
|
145
|
+
"""Readiness probe — verifies the DB is reachable via a cheap SELECT 1."""
|
|
146
|
+
ok = await _db(lambda: get_store().ping())
|
|
147
|
+
if not ok:
|
|
148
|
+
raise HTTPException(status_code=503, detail="store not ready")
|
|
149
|
+
return {"status": "ready"}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ---------------------------------------------------------------------------
|
|
153
|
+
# Memories
|
|
154
|
+
# ---------------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@app.post("/memories", response_model=MemoryRecord, status_code=201, tags=["Memories"])
|
|
158
|
+
async def add_memory(body: MemoryCreate) -> MemoryRecord:
|
|
159
|
+
"""Add a new memory. See POST /memories in openapi/mintmory.yaml."""
|
|
160
|
+
data = body.model_dump()
|
|
161
|
+
return await _db(lambda: get_store().add_memory(**data))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@app.get("/memories/{memory_id}", response_model=MemoryRecord, tags=["Memories"])
|
|
165
|
+
async def get_memory(memory_id: str) -> MemoryRecord:
|
|
166
|
+
result = await _db(lambda: get_store().get_memory(memory_id))
|
|
167
|
+
if result is None:
|
|
168
|
+
raise HTTPException(status_code=404, detail=f"Memory '{memory_id}' not found")
|
|
169
|
+
return result
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@app.patch("/memories/{memory_id}", response_model=MemoryRecord, tags=["Memories"])
|
|
173
|
+
async def update_memory(memory_id: str, body: MemoryUpdate) -> MemoryRecord:
|
|
174
|
+
"""Partial update. Only fields present in the body are changed."""
|
|
175
|
+
store = get_store()
|
|
176
|
+
existing = await _db(lambda: store.get_memory(memory_id))
|
|
177
|
+
if existing is None:
|
|
178
|
+
raise HTTPException(status_code=404, detail=f"Memory '{memory_id}' not found")
|
|
179
|
+
updates = body.model_dump(exclude_unset=True)
|
|
180
|
+
return await _db(lambda: store.update_memory(memory_id, **updates))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@app.delete("/memories/{memory_id}", status_code=204, tags=["Memories"])
|
|
184
|
+
async def archive_memory(memory_id: str) -> None:
|
|
185
|
+
store = get_store()
|
|
186
|
+
existing = await _db(lambda: store.get_memory(memory_id))
|
|
187
|
+
if existing is None:
|
|
188
|
+
raise HTTPException(status_code=404, detail=f"Memory '{memory_id}' not found")
|
|
189
|
+
await _db(lambda: store.archive_memory(memory_id))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# ---------------------------------------------------------------------------
|
|
193
|
+
# Search
|
|
194
|
+
# ---------------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@app.post("/memories/search", response_model=SearchResponse, tags=["Search"])
|
|
198
|
+
async def search_memories(request: SearchRequest) -> SearchResponse:
|
|
199
|
+
return await _db(lambda: get_store().search(request))
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# ---------------------------------------------------------------------------
|
|
203
|
+
# Links
|
|
204
|
+
# ---------------------------------------------------------------------------
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@app.get("/memories/{memory_id}/links", response_model=list[ConceptLink], tags=["Links"])
|
|
208
|
+
async def get_links(
|
|
209
|
+
memory_id: str,
|
|
210
|
+
link_type: Annotated[ConceptLinkType | None, Query()] = None,
|
|
211
|
+
min_strength: Annotated[float, Query(ge=0.0, le=1.0)] = 0.0,
|
|
212
|
+
) -> list[ConceptLink]:
|
|
213
|
+
store = get_store()
|
|
214
|
+
existing = await _db(lambda: store.get_memory(memory_id))
|
|
215
|
+
if existing is None:
|
|
216
|
+
raise HTTPException(status_code=404, detail=f"Memory '{memory_id}' not found")
|
|
217
|
+
links = await _db(lambda: store.get_links(memory_id, link_type=link_type))
|
|
218
|
+
return [link for link in links if link.strength >= min_strength]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@app.post(
|
|
222
|
+
"/memories/{memory_id}/links",
|
|
223
|
+
response_model=ConceptLink,
|
|
224
|
+
status_code=201,
|
|
225
|
+
tags=["Links"],
|
|
226
|
+
)
|
|
227
|
+
async def create_link(memory_id: str, body: ConceptLinkCreate) -> ConceptLink:
|
|
228
|
+
"""Create a manual ``ConceptLink`` from the path memory to a target memory.
|
|
229
|
+
|
|
230
|
+
``source`` is forced to ``user``. For symmetric link types
|
|
231
|
+
(``relates_to``, ``contradicts``, ``similar_to``) the reverse link is also
|
|
232
|
+
persisted; the forward link is returned.
|
|
233
|
+
"""
|
|
234
|
+
store = get_store()
|
|
235
|
+
if await _db(lambda: store.get_memory(memory_id)) is None:
|
|
236
|
+
raise HTTPException(status_code=404, detail=f"Memory '{memory_id}' not found")
|
|
237
|
+
if await _db(lambda: store.get_memory(body.target_memory_id)) is None:
|
|
238
|
+
raise HTTPException(status_code=404, detail=f"Memory '{body.target_memory_id}' not found")
|
|
239
|
+
if body.target_memory_id == memory_id:
|
|
240
|
+
raise HTTPException(
|
|
241
|
+
status_code=422, detail="target_memory_id must differ from the source memory"
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
link = ConceptLink(
|
|
245
|
+
source_memory_id=memory_id,
|
|
246
|
+
target_memory_id=body.target_memory_id,
|
|
247
|
+
link_type=body.link_type,
|
|
248
|
+
entity=body.entity,
|
|
249
|
+
strength=body.strength,
|
|
250
|
+
confidence=body.confidence,
|
|
251
|
+
source=LinkSource.USER,
|
|
252
|
+
)
|
|
253
|
+
created = await _db(lambda: store.add_link(link))
|
|
254
|
+
|
|
255
|
+
if body.link_type in SYMMETRIC_LINK_TYPES:
|
|
256
|
+
reverse_link = ConceptLink(
|
|
257
|
+
source_memory_id=body.target_memory_id,
|
|
258
|
+
target_memory_id=memory_id,
|
|
259
|
+
link_type=body.link_type,
|
|
260
|
+
entity=body.entity,
|
|
261
|
+
strength=body.strength,
|
|
262
|
+
confidence=body.confidence,
|
|
263
|
+
source=LinkSource.USER,
|
|
264
|
+
)
|
|
265
|
+
await _db(lambda: store.add_link(reverse_link))
|
|
266
|
+
|
|
267
|
+
return created
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
# ---------------------------------------------------------------------------
|
|
271
|
+
# Notes
|
|
272
|
+
# ---------------------------------------------------------------------------
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@app.post("/notes", response_model=NoteResult, status_code=201, tags=["Notes"])
|
|
276
|
+
async def create_note(body: NoteCreate) -> NoteResult:
|
|
277
|
+
"""Create a user-authored note (``is_note=true``). See core.notes.create_note."""
|
|
278
|
+
from mintmory.core import notes as notes_mod # noqa: PLC0415
|
|
279
|
+
|
|
280
|
+
store = get_store()
|
|
281
|
+
content, about, when, until, category = (
|
|
282
|
+
body.content,
|
|
283
|
+
body.about,
|
|
284
|
+
body.when,
|
|
285
|
+
body.until,
|
|
286
|
+
body.category,
|
|
287
|
+
)
|
|
288
|
+
return await _db(
|
|
289
|
+
lambda: notes_mod.create_note(
|
|
290
|
+
store, content=content, about=about, when=when, until=until, category=category
|
|
291
|
+
)
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
@app.get("/notes", response_model=list[MemoryRecord], tags=["Notes"])
|
|
296
|
+
async def list_notes(
|
|
297
|
+
about: Annotated[str | None, Query()] = None,
|
|
298
|
+
upcoming: Annotated[bool, Query()] = False,
|
|
299
|
+
overdue: Annotated[bool, Query()] = False,
|
|
300
|
+
limit: Annotated[int, Query(ge=1, le=500)] = 50,
|
|
301
|
+
) -> list[MemoryRecord]:
|
|
302
|
+
"""List user-authored notes. ``upcoming``/``overdue`` are mutually exclusive (422 if both)."""
|
|
303
|
+
from mintmory.core import notes as notes_mod # noqa: PLC0415
|
|
304
|
+
|
|
305
|
+
store = get_store()
|
|
306
|
+
try:
|
|
307
|
+
return await _db(
|
|
308
|
+
lambda: notes_mod.notes_list(
|
|
309
|
+
store, about=about, upcoming=upcoming, overdue=overdue, limit=limit
|
|
310
|
+
)
|
|
311
|
+
)
|
|
312
|
+
except ValueError as exc:
|
|
313
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# ---------------------------------------------------------------------------
|
|
317
|
+
# Stats
|
|
318
|
+
# ---------------------------------------------------------------------------
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@app.get("/stats", response_model=MemoryStats, tags=["Stats"])
|
|
322
|
+
async def get_stats() -> MemoryStats:
|
|
323
|
+
return await _db(lambda: get_store().get_stats())
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ---------------------------------------------------------------------------
|
|
327
|
+
# Dream
|
|
328
|
+
# ---------------------------------------------------------------------------
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
@app.post("/dream", response_model=DreamReport, tags=["Dream"])
|
|
332
|
+
async def run_dream(body: DreamRequest) -> DreamReport:
|
|
333
|
+
store = get_store()
|
|
334
|
+
intensity = body.intensity
|
|
335
|
+
|
|
336
|
+
def _do_dream() -> DreamReport:
|
|
337
|
+
engine = DreamingEngine(store)
|
|
338
|
+
if intensity is DreamIntensity.FULL:
|
|
339
|
+
return engine.run_full()
|
|
340
|
+
return engine.run_light()
|
|
341
|
+
|
|
342
|
+
return await _db(_do_dream)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
# ---------------------------------------------------------------------------
|
|
346
|
+
# Sessions
|
|
347
|
+
# ---------------------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
@app.get("/sessions/{session_id}", response_model=QuerySession, tags=["Sessions"])
|
|
351
|
+
async def get_session(session_id: str) -> QuerySession:
|
|
352
|
+
result = await _db(lambda: get_store().get_session(session_id))
|
|
353
|
+
if result is None:
|
|
354
|
+
raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
|
|
355
|
+
return result
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
@app.post("/sessions/{session_id}/feedback", response_model=QuerySession, tags=["Sessions"])
|
|
359
|
+
async def session_feedback(session_id: str, body: SessionFeedback) -> QuerySession:
|
|
360
|
+
"""Apply LLM self-assessment feedback and conclude the session.
|
|
361
|
+
|
|
362
|
+
Maps the core ``ValueError`` to 404 (missing session) or 409 (already
|
|
363
|
+
concluded).
|
|
364
|
+
"""
|
|
365
|
+
store = get_store()
|
|
366
|
+
existing = await _db(lambda: store.get_session(session_id))
|
|
367
|
+
if existing is None:
|
|
368
|
+
raise HTTPException(status_code=404, detail=f"Session '{session_id}' not found")
|
|
369
|
+
useful_ids, stale_ids = body.useful_ids, body.stale_ids
|
|
370
|
+
confidence_rating, reasoning = body.confidence_rating, body.reasoning
|
|
371
|
+
try:
|
|
372
|
+
return await _db(
|
|
373
|
+
lambda: session_module.apply_feedback(
|
|
374
|
+
store,
|
|
375
|
+
session_id,
|
|
376
|
+
useful_ids=useful_ids,
|
|
377
|
+
stale_ids=stale_ids,
|
|
378
|
+
confidence_rating=confidence_rating,
|
|
379
|
+
reasoning=reasoning,
|
|
380
|
+
)
|
|
381
|
+
)
|
|
382
|
+
except ValueError as exc:
|
|
383
|
+
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# ---------------------------------------------------------------------------
|
|
387
|
+
# Summaries
|
|
388
|
+
# ---------------------------------------------------------------------------
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
@app.get("/summaries", response_model=list[MemorySummary], tags=["Summaries"])
|
|
392
|
+
async def list_summaries(
|
|
393
|
+
include_stale: Annotated[bool, Query()] = False,
|
|
394
|
+
) -> list[MemorySummary]:
|
|
395
|
+
summaries: list[MemorySummary] = await _db(lambda: get_store().list_summaries())
|
|
396
|
+
if include_stale:
|
|
397
|
+
return summaries
|
|
398
|
+
return [summary for summary in summaries if summary.is_current]
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
@app.get("/summaries/jobs", response_model=list[SummaryJob], tags=["Summaries"])
|
|
402
|
+
async def list_summary_jobs(
|
|
403
|
+
include_all: Annotated[bool, Query()] = False,
|
|
404
|
+
limit: Annotated[int, Query(ge=0)] = 0,
|
|
405
|
+
) -> list[SummaryJob]:
|
|
406
|
+
"""Concept-summary jobs for an agent to write (agent-supplied L3).
|
|
407
|
+
|
|
408
|
+
``include_all=false`` (default) returns only concepts needing a (re)summary.
|
|
409
|
+
``limit=0`` means no cap.
|
|
410
|
+
"""
|
|
411
|
+
settings = load_settings()
|
|
412
|
+
store = get_store()
|
|
413
|
+
|
|
414
|
+
def _collect() -> list[SummaryJob]:
|
|
415
|
+
engine = build_dreaming_engine(
|
|
416
|
+
store,
|
|
417
|
+
settings.llm,
|
|
418
|
+
link_settings=settings.link,
|
|
419
|
+
summary_settings=settings.summary,
|
|
420
|
+
)
|
|
421
|
+
jobs = engine.collect_summary_jobs(include_all=include_all)
|
|
422
|
+
return jobs[:limit] if limit > 0 else jobs
|
|
423
|
+
|
|
424
|
+
return await _db(_collect)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
@app.get("/summaries/{concept}", response_model=MemorySummary, tags=["Summaries"])
|
|
428
|
+
async def get_summary(concept: str) -> MemorySummary:
|
|
429
|
+
result = await _db(lambda: get_store().get_summary(concept))
|
|
430
|
+
if result is None:
|
|
431
|
+
raise HTTPException(status_code=404, detail=f"No summary for concept '{concept}'")
|
|
432
|
+
return result
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
@app.put("/summaries/{concept}", response_model=MemorySummary, tags=["Summaries"])
|
|
436
|
+
async def put_summary(concept: str, body: SummaryPut) -> MemorySummary:
|
|
437
|
+
"""Store an agent-supplied summary for ``concept`` (idempotent upsert)."""
|
|
438
|
+
settings = load_settings()
|
|
439
|
+
store = get_store()
|
|
440
|
+
summary_text = body.summary_text
|
|
441
|
+
|
|
442
|
+
def _apply() -> MemorySummary:
|
|
443
|
+
engine = build_dreaming_engine(
|
|
444
|
+
store,
|
|
445
|
+
settings.llm,
|
|
446
|
+
link_settings=settings.link,
|
|
447
|
+
summary_settings=settings.summary,
|
|
448
|
+
)
|
|
449
|
+
return engine.apply_summary(concept, summary_text)
|
|
450
|
+
|
|
451
|
+
return await _db(_apply)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
# ---------------------------------------------------------------------------
|
|
455
|
+
# Images
|
|
456
|
+
# ---------------------------------------------------------------------------
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
@app.get("/images/jobs", response_model=list[ImageJob], tags=["Images"])
|
|
460
|
+
async def list_image_jobs(
|
|
461
|
+
include_all: Annotated[bool, Query()] = False,
|
|
462
|
+
include_bytes: Annotated[bool, Query()] = False,
|
|
463
|
+
limit: Annotated[int, Query(ge=0)] = 0,
|
|
464
|
+
) -> list[ImageJob]:
|
|
465
|
+
"""Image-description jobs for an agent (agent-supplied vision).
|
|
466
|
+
|
|
467
|
+
Returns the set of raster image file-records the calling agent should describe.
|
|
468
|
+
MintMory does NOT call a vision model — the agent IS the vision-capable model.
|
|
469
|
+
Each job carries path/rel/mime/size, the online_only flag, and either an inline
|
|
470
|
+
base64 ``image_b64`` or ``null`` meaning the agent should read the file at ``path``.
|
|
471
|
+
``include_all=false`` (default) returns only images that still need a description.
|
|
472
|
+
``limit=0`` means no cap.
|
|
473
|
+
"""
|
|
474
|
+
from mintmory.core import vision as vision_mod # noqa: PLC0415
|
|
475
|
+
|
|
476
|
+
settings = load_settings()
|
|
477
|
+
store = get_store()
|
|
478
|
+
return await _db(
|
|
479
|
+
lambda: vision_mod.image_jobs(
|
|
480
|
+
store,
|
|
481
|
+
include_all=include_all,
|
|
482
|
+
include_bytes=include_bytes,
|
|
483
|
+
limit=limit,
|
|
484
|
+
settings=settings.vision,
|
|
485
|
+
)
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
@app.put("/images/{file_id}", response_model=ImageDescription, tags=["Images"])
|
|
490
|
+
async def put_image_caption(file_id: str, body: ImageCaptionPut) -> ImageDescription:
|
|
491
|
+
"""Store an agent-supplied description for the image file-record ``file_id``.
|
|
492
|
+
|
|
493
|
+
Persists the description as a context memory ANNOTATES-linked to the image
|
|
494
|
+
file-record. Idempotent: re-putting replaces the prior description (the image
|
|
495
|
+
then drops out of the default ``GET /images/jobs`` work-list). No vision backend
|
|
496
|
+
is required. Returns the stored ``ImageDescription`` with linkage facts.
|
|
497
|
+
"""
|
|
498
|
+
from mintmory.core import vision as vision_mod # noqa: PLC0415
|
|
499
|
+
|
|
500
|
+
settings = load_settings()
|
|
501
|
+
store = get_store()
|
|
502
|
+
description = body.description
|
|
503
|
+
try:
|
|
504
|
+
return await _db(
|
|
505
|
+
lambda: vision_mod.image_caption_put(
|
|
506
|
+
store, file_id, description, settings=settings.vision
|
|
507
|
+
)
|
|
508
|
+
)
|
|
509
|
+
except KeyError as exc:
|
|
510
|
+
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
@app.post("/images/caption-run", response_model=CaptionRunReport, tags=["Images"])
|
|
514
|
+
async def caption_run(body: CaptionRunRequest) -> CaptionRunReport:
|
|
515
|
+
"""Caption already-indexed pending images server-side with the configured vision provider.
|
|
516
|
+
|
|
517
|
+
Requires ``MINTMORY_VISION_PROVIDER=llm`` (a reachable OpenAI-compatible vision model)
|
|
518
|
+
to do real work. With provider=agent (the default) this is a no-op: returns a
|
|
519
|
+
``CaptionRunReport`` with ``provider='agent'`` and all-zero counts — use the
|
|
520
|
+
``GET /images/jobs`` / ``PUT /images/{file_id}`` agent loop instead.
|
|
521
|
+
|
|
522
|
+
Per-image failures (network/timeout/unreadable) are skipped and counted under
|
|
523
|
+
``failed``; one bad image never aborts the run. Returns a ``CaptionRunReport``
|
|
524
|
+
with per-image audit items.
|
|
525
|
+
|
|
526
|
+
Raises 422 when the configured provider is not yet implemented (e.g. ``ocr``).
|
|
527
|
+
"""
|
|
528
|
+
from mintmory.core import vision as vision_mod # noqa: PLC0415
|
|
529
|
+
|
|
530
|
+
settings = load_settings()
|
|
531
|
+
try:
|
|
532
|
+
captioner = vision_mod.captioner_from_settings(settings.vision)
|
|
533
|
+
except NotImplementedError as exc:
|
|
534
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
535
|
+
if captioner is None:
|
|
536
|
+
return CaptionRunReport(provider="agent")
|
|
537
|
+
store = get_store()
|
|
538
|
+
budget = int(body.budget_mb * 1024 * 1024) if body.budget_mb > 0 else None
|
|
539
|
+
limit_val, include_all_val = body.limit, body.include_all
|
|
540
|
+
return await _db(
|
|
541
|
+
lambda: vision_mod.caption_pending_images(
|
|
542
|
+
store,
|
|
543
|
+
captioner=captioner,
|
|
544
|
+
limit=limit_val,
|
|
545
|
+
budget=budget,
|
|
546
|
+
include_all=include_all_val,
|
|
547
|
+
settings=settings.vision,
|
|
548
|
+
)
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def main() -> None:
|
|
553
|
+
import uvicorn
|
|
554
|
+
|
|
555
|
+
uvicorn.run("mintmory.api.app:app", host="0.0.0.0", port=8080, reload=True)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
if __name__ == "__main__":
|
|
559
|
+
main()
|
mintmory/api/py.typed
ADDED
|
File without changes
|
mintmory/api/schemas.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Thin request-body models for the MintMory HTTP API.
|
|
3
|
+
|
|
4
|
+
These mirror the ``*Create`` / ``*Update`` / request schemas in
|
|
5
|
+
``docs/openapi/mintmory.yaml``. They exist only at the transport boundary:
|
|
6
|
+
each route validates the incoming JSON against one of these models and then
|
|
7
|
+
forwards the data into the frozen ``mintmory.core`` service layer (which owns
|
|
8
|
+
all domain logic and returns the canonical ``types.py`` models that are sent
|
|
9
|
+
back to the client).
|
|
10
|
+
|
|
11
|
+
Response models are the core ``types.py`` models directly (``MemoryRecord``,
|
|
12
|
+
``SearchResponse``, ``ConceptLink``, ``DreamReport``, ``QuerySession`` ...), so
|
|
13
|
+
they are not redefined here.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from mintmory.core.types import (
|
|
22
|
+
ConceptLinkType,
|
|
23
|
+
DreamIntensity,
|
|
24
|
+
MemoryCategory,
|
|
25
|
+
MemorySource,
|
|
26
|
+
)
|
|
27
|
+
from pydantic import BaseModel, Field, model_validator
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class MemoryCreate(BaseModel):
|
|
31
|
+
"""Request body for ``POST /memories`` (OpenAPI ``MemoryCreate``).
|
|
32
|
+
|
|
33
|
+
Only ``content`` and ``category`` are required; every other field has a
|
|
34
|
+
server-side default supplied by ``MemoryRecord``.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
content: str = Field(..., min_length=1, max_length=10_000)
|
|
38
|
+
category: MemoryCategory
|
|
39
|
+
source: MemorySource = MemorySource.AGENT
|
|
40
|
+
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
|
|
41
|
+
verified: bool = False
|
|
42
|
+
valid_from: datetime | None = None
|
|
43
|
+
valid_until: datetime | None = None
|
|
44
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class MemoryUpdate(BaseModel):
|
|
48
|
+
"""Request body for ``PATCH /memories/{id}`` (OpenAPI ``MemoryUpdate``).
|
|
49
|
+
|
|
50
|
+
All fields are optional but at least one must be present
|
|
51
|
+
(``minProperties: 1`` in the spec).
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
content: str | None = Field(default=None, min_length=1, max_length=10_000)
|
|
55
|
+
category: MemoryCategory | None = None
|
|
56
|
+
verified: bool | None = None
|
|
57
|
+
confidence: float | None = Field(default=None, ge=0.0, le=1.0)
|
|
58
|
+
valid_from: datetime | None = None
|
|
59
|
+
valid_until: datetime | None = None
|
|
60
|
+
metadata: dict[str, Any] | None = None
|
|
61
|
+
|
|
62
|
+
@model_validator(mode="after")
|
|
63
|
+
def _at_least_one_field(self) -> MemoryUpdate:
|
|
64
|
+
if not self.model_fields_set:
|
|
65
|
+
raise ValueError("at least one field must be provided")
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ConceptLinkCreate(BaseModel):
|
|
70
|
+
"""Request body for ``POST /memories/{id}/links`` (OpenAPI ``ConceptLinkCreate``).
|
|
71
|
+
|
|
72
|
+
The path memory is the ``source_memory_id``; ``source`` is forced to
|
|
73
|
+
``user`` by the route.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
target_memory_id: str
|
|
77
|
+
link_type: ConceptLinkType
|
|
78
|
+
entity: str = ""
|
|
79
|
+
strength: float = Field(default=0.5, ge=0.0, le=1.0)
|
|
80
|
+
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class DreamRequest(BaseModel):
|
|
84
|
+
"""Request body for ``POST /dream`` (OpenAPI ``DreamRequest``)."""
|
|
85
|
+
|
|
86
|
+
intensity: DreamIntensity
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class SessionFeedback(BaseModel):
|
|
90
|
+
"""Request body for ``POST /sessions/{id}/feedback`` (OpenAPI ``SessionFeedback``)."""
|
|
91
|
+
|
|
92
|
+
confidence_rating: int = Field(..., ge=1, le=5)
|
|
93
|
+
useful_ids: list[str]
|
|
94
|
+
stale_ids: list[str]
|
|
95
|
+
reasoning: str | None = None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class NoteCreate(BaseModel):
|
|
99
|
+
"""Request body for ``POST /notes`` (OpenAPI ``NoteCreate``).
|
|
100
|
+
|
|
101
|
+
Only ``content`` is required. ``when``/``until`` are ISO-8601 datetimes the
|
|
102
|
+
client/agent has already parsed from natural language (MintMory does no date
|
|
103
|
+
parsing). ``category`` defaults server-side to ``temporal`` when ``when`` is
|
|
104
|
+
set, otherwise ``episodic``.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
content: str = Field(..., min_length=1, max_length=10_000)
|
|
108
|
+
about: str | None = None
|
|
109
|
+
when: datetime | None = None
|
|
110
|
+
until: datetime | None = None
|
|
111
|
+
category: MemoryCategory | None = None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class SummaryPut(BaseModel):
|
|
115
|
+
"""Request body for ``PUT /summaries/{concept}`` (agent-supplied L3 summary)."""
|
|
116
|
+
|
|
117
|
+
summary_text: str = Field(..., min_length=1)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class ImageCaptionPut(BaseModel):
|
|
121
|
+
"""Request body for ``PUT /images/{file_id}`` (agent-supplied image description)."""
|
|
122
|
+
|
|
123
|
+
description: str = Field(..., min_length=1)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class CaptionRunRequest(BaseModel):
|
|
127
|
+
"""Request body for ``POST /images/caption-run`` (server-side auto-caption).
|
|
128
|
+
|
|
129
|
+
Triggers the configured server-side vision provider (``MINTMORY_VISION_PROVIDER=llm``)
|
|
130
|
+
to caption already-indexed pending raster images in place, without re-walking the
|
|
131
|
+
tree. With provider=agent (the default) the route is a no-op and returns
|
|
132
|
+
``provider='agent'`` with all-zero counts.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
limit: int = Field(default=0, ge=0, description="Max images to caption (0 = no cap).")
|
|
136
|
+
budget_mb: float = Field(
|
|
137
|
+
default=0.0,
|
|
138
|
+
ge=0.0,
|
|
139
|
+
description=("Download budget MB for online-only images (0 = use settings default)."),
|
|
140
|
+
)
|
|
141
|
+
include_all: bool = Field(
|
|
142
|
+
default=False,
|
|
143
|
+
description="Re-caption all raster images vs only pending (default).",
|
|
144
|
+
)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mintmory-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MintMory HTTP REST API via FastAPI
|
|
5
|
+
Project-URL: Homepage, https://github.com/WeLikeCode/mint-mory
|
|
6
|
+
Project-URL: Repository, https://github.com/WeLikeCode/mint-mory
|
|
7
|
+
Project-URL: Issues, https://github.com/WeLikeCode/mint-mory/issues
|
|
8
|
+
Author: WeLikeCode
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: agents,llm,mcp,memory,sqlite,vector-search
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Requires-Dist: fastapi>=0.115
|
|
21
|
+
Requires-Dist: mintmory-core~=0.1.0
|
|
22
|
+
Requires-Dist: python-multipart>=0.0.12
|
|
23
|
+
Requires-Dist: structlog>=24.4
|
|
24
|
+
Requires-Dist: uvicorn[standard]>=0.32
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# mintmory-api
|
|
28
|
+
|
|
29
|
+
FastAPI REST API for [MintMory](https://github.com/WeLikeCode/mint-mory) — the
|
|
30
|
+
typed agent-memory system. Entry point: `mintmory-api`.
|
|
31
|
+
|
|
32
|
+
Most users want the umbrella package instead: `pip install "mintmory[api]"`.
|
|
33
|
+
MIT licensed.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
mintmory/api/__init__.py,sha256=XoKUkd8Komd2JbWO5Srzg7zwySU0Hnalk2p0MmgAYGA,43
|
|
2
|
+
mintmory/api/app.py,sha256=wI87nEPYc-B0aNKn1QZUag3eJT2rcLjqURq4vtOwKuE,20119
|
|
3
|
+
mintmory/api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
mintmory/api/schemas.py,sha256=WEcTTlmWBnLE_IO3nqEY8kuLbwaLvkRl_YFn2_4UwBY,4864
|
|
5
|
+
mintmory_api-0.1.0.dist-info/METADATA,sha256=JEwIy-4SysJPoVlX52qsNPCy8Q407c191-ZmcLfO_5E,1238
|
|
6
|
+
mintmory_api-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
7
|
+
mintmory_api-0.1.0.dist-info/entry_points.txt,sha256=HMI4pNKvgF9wkEehYuol5gIcLjAADAagq4kOvE_Mwus,55
|
|
8
|
+
mintmory_api-0.1.0.dist-info/licenses/LICENSE,sha256=bHVoNuhpm8Mf7Mbyim_ODHLv-cnEPpnGKp-6lK0-qYo,1067
|
|
9
|
+
mintmory_api-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 WeLikeCode
|
|
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.
|