SuperAPIAI Directory

memex

github.com · AI agents

Persistent agent memory with semantic search and recency decay, local ONNX embeddings, background summarization and Prometheus/Grafana observability.

Open website Alternatives
PricingOpen source开源项目(可免费自部署)
PlatformsLinux · API

About this tool

memex is a production-grade persistent memory service for AI agents, built on FastAPI, pgvector, and local ONNX embeddings. Agents forget everything between sessions by default, and memex is used to solve this problem: it stores, retrieves, and ranks conversation memories, using semantic search combined with recency decay, so that agents return content that is both relevant and relatively recent, not just the semantically closest content.

Key capabilities

Write path: content → fastembed ONNX inference (local, about 12 ms CPU, model BAAI/bge-small-en-v1.5) → INSERT as a 384-dimensional vector → return memory ID.

Read path: query → embed → pgvector cosine search (take top_k × 3 candidates) → rerank in Python with recency decay → return top_k results with scores.

Design decisions

  1. Layer recency decay on top of semantic search: pure vector similarity returns the semantically most similar memories, not the most useful memories. A fact with similarity 0.95 from 90 days ago is often less useful than content with similarity 0.80 from yesterday. In the formula, λ = ln(2) / half_life_days (default 30 days, meaning a memory from 30 days ago retains 50% of its recency weight). α can be configured per request (default 0.7). Task-oriented agents use a higher α (semantics dominate), while conversational agents use a lower α (recency matters more).

  2. Take 3 times as many candidates and rerank in Python: the pgvector query returns top_k × 3 candidates sorted by pure similarity, and Python reranks them with the decay formula and then truncates to top_k. This prevents recency decay from "starving" older memories with high similarity—they remain in the candidate pool. At 10 times the scale (more than 1 million memories per agent), scoring can be pushed down to a Postgres function (pg_proc) to eliminate the round-trip overhead of Python reranking.

  3. Use asyncpg + an explicit connection pool instead of SQLAlchemy async: SQLAlchemy adds ORM overhead to every query, while the hot retrieval path (embedding, query, rerank) needs to be compact. asyncpg allows direct control of the connection pool min/max. The pgvector query's <=> operator also inherently requires native SQL. The connection pool defaults to min=5, max=20, and can be overridden via the DB_MAX_POOL_SIZE environment variable.

  4. Put rate limiting in Postgres instead of Redis: implement a sliding-window counter via upsert, with one fewer dependency, and it is correct under concurrent requests (transactional upsert). In a distributed deployment at 10 times the scale, it can be replaced with Redis INCR + EXPIRE.

  5. Use an ivfflat index instead of HNSW: ivfflat has lower build cost and smaller memory usage, making it suitable for small to medium scale (fewer than 1 million vectors). lists=100 performs well up to about 1 million rows. At 10 times the scale, you can switch to HNSW (m=16, ef_construction=64) for better recall, at the cost of higher memory and build time.

Running locally

Prerequisites: Docker and Docker Compose. No API key is required—the entire stack runs locally. The API is located at http://localhost:8000,交互式文档位于 http://localhost:8000/docs。

Performance and Load Testing

Run on MacBook M series, Docker Desktop, single Postgres instance. Realistic load (50 users, 100–300 ms think time, simulating actual agent traffic); saturation test (500 users, minimal think time, to find the throughput ceiling). The runtime environment is MacBook M series, Docker Desktop (4 CPU), 4 uvicorn workers, 16 threads per worker. Embeddings use local ONNX (BAAI/bge-small-en-v1.5), zero external API calls, zero cost.

The reason the throughput ceiling is about 120 RPS: every write and every search requires one ONNX inference (about 10–15 ms on CPU). With 4 Docker CPUs, 4 cores / 12 ms ≈ 333 embeddings/sec is the theoretical ceiling; after deducting Python overhead, database queries, and asyncio scheduling, it is actually about 120 RPS.

Observability

docker compose up starts Prometheus and Grafana at the same time as the API. The Grafana dashboard is automatically configured, with panels including: HTTP request rate and latency p50/p99 (from prometheus-fastapi-instrumentator); embedding API latency p50/p99 (per-attempt histograms by operation embed / embed_batch); memory operations/sec (create, search, delete throughput); database connection pool utilization (active and idle connections, update interval 15 seconds); summarizer activity (memories compacted per hour, run results); embedding errors/minute (by operation and error type). Custom metrics are located in app/services/metrics.py and are exposed at /metrics together with the standard FastAPI instrumentator metrics.

MCP-Compatible Endpoint

memex exposes itself as an MCP server, so any MCP-capable agent (Claude Desktop, Claude Code, custom agents) can store and retrieve memories without a custom HTTP integration. Transport: Streamable HTTP (MCP 2024-11-05 specification).A single worker process runs on port 8001—session state is in-process, so an independent service avoids the complexity of sticky sessions while maintaining multi-worker throughput for the REST API.

Connecting from Claude Desktop: add the configuration in ~/.config/claude/claude_desktop_config.json. Connecting from Claude Code works the same way.

Why use an independent service by design: The MCP Streamable HTTP transport is stateful—initialize, tools/list, and tools/call must all reach the same server process. The REST API runs 4 uvicorn workers with round-robin routing, and routing different MCP requests to different workers would break session state. Running a dedicated single-worker MCP service on port 8001 avoids sticky session infrastructure (nginx ip_hash, Redis session storage) while keeping the REST API fully multi-worker.

Memory summarization

Runs as a background asyncio task at a configurable interval (default every 5 minutes). Finds any (agent_id, user_id) pair whose episodic memory count exceeds a threshold, compresses the oldest batch into a single semantic memory, then deletes the original records. Fully local—no LLM API calls.

Summarization method: a pure Python extractive algorithm. Sentences are deduplicated by Jaccard similarity (threshold ≥ 0.7), scored by term frequency (TF), and the top N highest-scoring sentences are returned in their original order. Each summarization takes about 1 millisecond, with zero dependencies beyond the standard library.

Why only episodic memory is processed: Episodic memory consists of conversational events with natural temporal expiration. Semantic memory and procedural memory encode facts and skills, and silently compressing them risks precision loss; they naturally age through time decay.

Concurrency safety: Uses pg_try_advisory_xact_lock keyed by hashtext(agent_id|user_id). The lock is held only during the database write transaction, not during embedding calls. Adjustable via environment variables.

Other features

Memory summarization—a background task compresses old episodic memories when the count exceeds a threshold (local extractive algorithm, zero API calls).

Prometheus + Grafana—p50/p99 latency dashboards, embedding API call duration, connection pool saturation.

MCP-compatible endpoint—a Streamable HTTP server on port 8001; 4 tools (store, search, delete, count); can connect to Claude Desktop and Claude Code.

HNSW index option—a switch to move from ivfflat to HNSW for deployments exceeding 1 million vectors.

Importance-weighted retrieval—combines similarity, recency, and importance scores in the ranking formula.

Use cases and limitations

memex is suitable for AI agents that need cross-session memory, especially conversational or task-oriented agents, as well as deployments that want to run locally without relying on external embedding APIs. Its throughput ceiling is about 120 RPS (in a 4 CPU environment), and higher throughput requires scaling CPU or adjusting the architecture. The project materials do not provide specific installation commands, a complete list of environment variables, license information, or pricing model; this content is not yet available.

Up/Down to navigate · Enter to open · ESC to closeBrowse all tools