Lossmemory

Lossmemory is a Django REST Framework service for storing and retrieving LLM memory. It stores raw conversation events, extracts durable memories, embeds memories and file chunks with Gemini embeddings, and retrieves relevant context from PostgreSQL with pgvector.

The service is designed as a reusable memory API for agents, chat applications, and internal LLM tools.

Current Capabilities

  • Memory CRUD under /api/v1/memories/
  • Memory retrieval via /api/v1/memory/retrieve
  • Raw event ingestion via /api/v1/memory/events
  • Memory extraction from events
  • File upload, text chunking, chunk embedding, and optional file memory extraction
  • PostgreSQL + pgvector storage
  • HNSW vector indexes for memory and file chunk embeddings
  • Local TraceRecord persistence
  • Optional Langfuse tracing
  • OpenAPI schema at /api/schema/
  • Swagger UI at /api/docs/

Detailed API documentation is available in docs/api/README.md. Internal flow documentation is available in docs/architecture/flows.md.

Stack

  • Python 3.14
  • Django 6
  • Django REST Framework
  • PostgreSQL with pgvector
  • Google Gen AI SDK
  • Gemini embeddings, default gemini-embedding-002
  • Celery with Redis
  • Langfuse
  • Ruff and mypy

Prerequisites

Install the following before running the service:

  • Python 3.14
  • uv
  • PostgreSQL
  • pgvector extension available to PostgreSQL
  • Redis, required only for Celery background workers

Verify PostgreSQL can see pgvector:

psql -d lossmemory -c "select name, default_version, installed_version from pg_available_extensions where name = 'vector';"

The Django migration creates the extension with:

CREATE EXTENSION IF NOT EXISTS "vector";

The database user must have permission to create extensions, or the extension must already be installed by a superuser.

Installation

Clone the repository and install dependencies:

uv sync

Create a local environment file:

cp .env.example .env

Edit .env and set at least:

DJANGO_SECRET_KEY=replace-this
DATABASE_URL=postgresql://lossmemory:lossmemory@localhost:5432/lossmemory
GOOGLE_API_KEY=your-google-api-key
LANGFUSE_PUBLIC_KEY=your-langfuse-public-key
LANGFUSE_SECRET_KEY=your-langfuse-secret-key
LANGFUSE_HOST=https://cloud.langfuse.com

If GOOGLE_API_KEY is empty, the service uses deterministic local embeddings. This is useful for local smoke tests, but production retrieval should use Gemini embeddings.

Database Setup

Create the database and user according to your local PostgreSQL setup. Example:

createdb lossmemory

Run migrations:

uv run manage.py migrate

Verify migration state:

uv run manage.py showmigrations memory

Verify pgvector and HNSW indexes:

uv run manage.py shell -c "from django.db import connection; cur = connection.cursor(); cur.execute(\"select extname, extversion from pg_extension where extname='vector'\"); print(cur.fetchall()); cur.execute(\"select indexname from pg_indexes where indexname in ('memory_embedding_hnsw_idx', 'file_chunk_embedding_hnsw_idx')\"); print(cur.fetchall())"

Running the API

Start the development server:

uv run manage.py runserver 127.0.0.1:8000

Useful URLs:

API base:    http://127.0.0.1:8000/api/v1/
OpenAPI:     http://127.0.0.1:8000/api/schema/
Swagger UI:  http://127.0.0.1:8000/api/docs/

This project intentionally does not enable Django admin or application authentication yet.

Running Celery

Start Redis, then run the worker:

uv run celery -A config worker -l info

Celery currently handles:

  • event memory extraction through extract_memories
  • file chunk reprocessing through embed_file_chunks

The API can also run extraction synchronously with memory_write.mode = "sync".

API Examples

Create Memory Directly

curl -X POST http://127.0.0.1:8000/api/v1/memories/ \
  -H "Content-Type: application/json" \
  -d '{
    "project": "demo",
    "scope": "project",
    "type": "procedural",
    "content": "Use services and repositories for memory workflows.",
    "embed": true,
    "include_meta": true
  }'

Retrieve Memory

curl -X POST http://127.0.0.1:8000/api/v1/memory/retrieve \
  -H "Content-Type: application/json" \
  -d '{
    "project": "demo",
    "query": "service repository memory workflow",
    "include_meta": true
  }'

Store Events and Extract Memory

curl -X POST http://127.0.0.1:8000/api/v1/memory/events \
  -H "Content-Type: application/json" \
  -d '{
    "project": "demo",
    "session": "session-1",
    "source": "chat",
    "messages": [
      {
        "role": "user",
        "content": "The project should use service classes for memory workflows."
      }
    ],
    "memory_write": {
      "mode": "sync",
      "extract": true,
      "target_scope": "session",
      "allowed_types": ["semantic", "episodic", "procedural"]
    },
    "include_meta": true
  }'

Upload and Chunk a File

curl -X POST http://127.0.0.1:8000/api/v1/memory/files \
  -F 'payload={
    "project": "demo",
    "session": "session-1",
    "scope": "session",
    "store_file": true,
    "extract_memories": true,
    "chunking": {
      "chunk_size": 1000,
      "chunk_overlap": 150
    },
    "include_meta": true
  }' \
  -F 'files=@README.md;type=text/markdown'

Verification

Run the standard checks before committing changes:

uv run manage.py check
uv run manage.py makemigrations --check --dry-run
uv run ruff check .
uv run ty check
uv run mypy memory config
uv run manage.py spectacular --file /tmp/lossmemory-schema.yaml --validate

Run a quick API smoke test from Django shell:

uv run manage.py shell -c "from rest_framework.test import APIClient; c = APIClient(); r = c.post('/api/v1/memory/retrieve', {'project': 'demo', 'query': 'memory workflow', 'include_meta': True}, format='json'); print(r.status_code); print(r.json())"

Project Structure

config/
  settings.py          Django settings and environment loading
  urls.py              API schema and versioned API routes
  celery.py            Celery application

memory/
  api/v1/              DRF serializers, views, and routes
  domain/              enums, scoring, and domain dataclasses
  factories/           response and trace factories
  models/              database models
  repositories/        database query and persistence boundaries
  services/            business workflows
  tasks/               Celery tasks
  migrations/          database migrations

The intended dependency direction is:

views -> serializers -> services -> repositories -> models

Views should stay thin. Business logic belongs in services. Query logic belongs in repositories.

Environment Variables

VariablePurpose
DJANGO_SECRET_KEYDjango secret key
DJANGO_DEBUGEnables development debug mode
DJANGO_ALLOWED_HOSTSComma-separated allowed hosts
DATABASE_URLPostgreSQL connection URL
GOOGLE_API_KEYEnables Gemini embedding and extraction calls
MEMORY_EMBEDDING_MODELEmbedding model, default gemini-embedding-002
MEMORY_EMBEDDING_DIMENSIONSEmbedding dimensions, default 768
MEMORY_EXTRACTION_MODELGemini model for memory extraction
MEMORY_RETRIEVAL_DEFAULT_LIMITDefault retrieval limit
MEMORY_RETRIEVAL_MIN_SCOREDefault vector similarity threshold
LANGFUSE_PUBLIC_KEYLangfuse public key
LANGFUSE_SECRET_KEYLangfuse secret key
LANGFUSE_HOSTLangfuse host URL
LANGFUSE_ENVIRONMENTLangfuse environment label
CELERY_BROKER_URLCelery broker URL
CELERY_RESULT_BACKENDCelery result backend

Current Limitations

  • File text extraction currently supports UTF-8 text-like files. PDF, DOCX, and binary formats need dedicated extractors.
  • Conflict and supersession logic is not implemented yet.
  • Zep-style entity graph extraction is not implemented yet.
  • Formal pytest coverage is still pending.
  • API authentication is intentionally not enabled yet.

Development Notes

  • Real .env files are ignored by git.
  • .env.example is safe to commit.
  • Local deterministic embeddings are only a development fallback.
  • Production deployments should use PostgreSQL with pgvector and a real Gemini API key.