← 开源
TypeScript
增长势头
+024 小时新增 Star0.0%
8
Star
0
Fork
2
贡献者
创建于 2026-05-09 · 更新于 2026-06-19 · 今日第 28477 名
主要开发者
soorajshankar
README

MemexAI

Memory made available to your agent's next response, backed by Postgres.

Agents forget because most memory never makes it back into the next model call, or it lives in chat history, prompt glue, or app-specific tables no one can inspect. MemexAI gives agents a closed loop: store durable memory, make it available to the next turn, verify the answer, and inspect the record behind it.

No vector database required. No hidden memory blob. Just your Postgres.

Storage stays in your Postgres. If you enable model-backed memorize/search or dreaming, selected memory text is sent to your configured model provider.

What It Solves

AI agents need stable context:

  • A user says they prefer quiet neighborhoods, and the next session should know.
  • A support agent learns a durable account fact, and the team should audit when it changed.
  • A product assistant needs shared company context and private per-user memory.
  • A developer should be able to inspect memory without reverse-engineering model state.

MemexAI stores memory as scoped Markdown-like files in Postgres and exposes a prompt block that makes stored memory available to the model when it answers. Agents can use a simple two-tool interface, while advanced workflows can use raw file tools directly.

How It Is Different

Many memory systems start from captured conversations and optimize extraction plus retrieval over that history:

store every message -> embed chunks -> retrieve similar past chunks -> answer

That is useful, but MemexAI's bias is different:

conversation happens -> agent writes durable memory -> prompt block makes context available -> humans inspect why

MemexAI does not store every session as memory. Raw conversation logs can live in your app, warehouse, or audit store. MemexAI is for the smaller working set an agent should actually use later: user profile facts, preferences, timelines, commitments, project notes, decisions, and source-backed updates.

Tradeoff: smaller context, human-readable memory, editable records, revision history, access logs, simple Postgres operations, no separate vector infrastructure — at the cost of ingestion quality. If the agent fails to write a durable fact, later recall cannot recover it unless you replay raw logs.

mem0 and Zep are strong when you want managed or graph/vector-backed memory extraction and retrieval. MemexAI is strongest when the memory record itself must be directly editable, auditable, and Postgres-native.

Two Integration Paths

Memory Subagent: The Default

Give the model memory_remember and memory_context; MemexAI decides what is durable, retrieves relevant context, and handles file bookkeeping. Your system prompt gets the MemexAI prompt block.

const system = await memory.getSystemPrompt("You are a helpful assistant with durable user memory.")
const tools = memory.createMemorySubagentToolset()
// memory_remember, memory_context
  • memory_remember extracts durable facts and writes or patches memory.
  • memory_context retrieves relevant context. It internally calls memory_find (BM25 full-text search, or hybrid BM25 + pgvector with RRF fusion when GEMINI_API_KEY is set), memory_read, and memory_list, then returns a grounded response with cited source paths.

Raw File Tools: Explicit File Control

Use this when your agent or app should manage memory files directly.

const tools = memory.createRawToolset()
// memory_list, memory_read, memory_write, memory_patch, memory_find

Both paths use the same scoped paths, revision history, and access logs.

Quick Start: Docker Service

The service path is the best default for teams and production apps. Your app talks to an HTTP API; it never needs database credentials.

The fastest proof should take about 90 seconds on a clean machine: start the Docker stack, run the demo agent with one preference, open the admin UI, and ask a second question that can use the stored memory. No app integration required.

Create a compose.yml:

services:
  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: memexai
      POSTGRES_PASSWORD: memexai
      POSTGRES_DB: memexai
    volumes:
      - memexai_postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U memexai"]
      interval: 5s
      timeout: 5s
      retries: 5

  memexai:
    image: soorajshankar/memexai:latest
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      DATABASE_URL: postgresql://memexai:memexai@postgres:5432/memexai
      MEMEX_API_KEY: dev-agent-key
      MEMEX_ADMIN_SECRET: dev-admin-secret
      GEMINI_API_KEY: ...     # RECOMMENDED — enables LLM-backed memory_remember / memory_context and hybrid search
      MEMEX_DREAM_ENABLED: "false"
      # MEMEX_TELEMETRY_DISABLED: "true" # optional opt-out
      # OPENAI_API_KEY: ...
    ports:
      - "8080:8080"

volumes:
  memexai_postgres_data:

Then:

docker compose up -d
# API and admin UI: http://localhost:8080
# API key:          dev-agent-key
# Admin secret:     dev-admin-secret

npm install @memexai/sdk ai @ai-sdk/google
import { MemexAI } from "@memexai/sdk"
import { generateText, stepCountIs } from "ai"
import { createGoogleGenerativeAI } from "@ai-sdk/google"

const memex = new MemexAI({
  url: "http://localhost:8080",
  apiKey: process.env.MEMEX_API_KEY ?? "dev-agent-key",
})

const memory = memex.forUser({ userId: "user_123", actor: "assistant" })
const system = await memory.getSystemPrompt("You are a helpful assistant with durable user memory.")

const result = await generateText({
  model: createGoogleGenerativeAI()("gemini-2.5-flash"),
  system,
  prompt: "Remember that I prefer quiet neighborhoods near good schools.",
  tools: memory.createMemorySubagentToolset(),
  stopWhen: stepCountIs(5),
})

console.log(result.text)

Python apps use the same containerized service:

from memexai import MemexAI

memex = MemexAI(url="http://localhost:8080", api_key="dev-agent-key")
memory = memex.for_user("user_123", actor="assistant")
result = await memory.find("What does this user prefer?")
await memex.close()

LLM-backed memory_remember and memory subagent memory_context are configured on the service, not in the SDK. Set one of these in the service environment:

GEMINI_API_KEY=...
GEMINI_MODEL=gemini-2.5-flash

# or
OPENAI_API_KEY=...
OPENAI_MODEL=gpt-4.1-mini

To run the Docker service against Vertex AI with a service-account key, generate a local Vertex env file:

./scripts/setup-vertex-env.sh

set -a
source .env.vertex.local
set +a
docker compose up -d --build

The helper uses your active gcloud project, creates or reuses a memexai-vertex-smoke service account, grants roles/aiplatform.user, writes the key to .secrets/google-vertex-sa.json, and writes .env.vertex.local with:

MEMEX_LLM_PROVIDER=vertex
GOOGLE_VERTEX_PROJECT=your-gcp-project
GOOGLE_VERTEX_LOCATION=us-central1
GOOGLE_VERTEX_MODEL=gemini-2.5-flash
GOOGLE_APPLICATION_CREDENTIALS_HOST=/absolute/path/to/.secrets/google-vertex-sa.json
GOOGLE_APPLICATION_CREDENTIALS=/run/secrets/google-vertex-sa.json

Smoke the Vertex path:

curl -s http://localhost:8080/health

curl -s -X POST http://localhost:8080/v1/tools/memory_remember/execute \
  -H "Authorization: Bearer ${MEMEX_API_KEY:-dev-agent-key}" \
  -H "Content-Type: application/json" \
  -d '{"context":{"userId":"vertex_smoke","actor":"curl"},"arguments":{"text":"Remember that I prefer 2BHK apartments near metro stations.","maxWrites":2}}'

bun run --cwd apps/benchmark docker-smoke -- --limit 1 --max-sessions 3

Without a service model, memory_context still works through memory_find (Postgres full-text search), or hybrid pgvector search with RRF when GEMINI_API_KEY is set and MEMEX_SEARCH_MODE=auto. memory_remember returns MODEL_NOT_CONFIGURED.

Open the admin UI at http://localhost:8080/admin.

Anonymous telemetry

MemexAI service telemetry is enabled by default for the OSS Docker image. It sends anonymous product usage events to PostHog so the project can understand whether installs reach first memory, use MCP, enable dreaming, and hit service errors. It never sends memory content, prompts, file paths, tool arguments, user IDs, API keys, or database URLs.

Disable with:

MEMEX_TELEMETRY_DISABLED=true

Background dreaming

Dreaming is optional background memory consolidation. When enabled, Memex periodically finds users with changed user/ memory files, waits for a quiet grace period, then runs a consolidation pass to merge duplicates, compact fragmented notes, resolve direct contradictions, and keep long-running memory readable for the next agent session.

Enable with MEMEX_DREAM_ENABLED=true. Runtime settings live in mx_config as dream_* keys, manageable through the Dreams panel or /v1/admin/dream/* endpoints.

MCP Clients

The same service exposes Memex as a Model Context Protocol server. REST and MCP both route through the same core tool engine.

SSE transport:

http://localhost:8080/v1/mcp/sse?userId=user_123&actor=claude&apiKey=dev-agent-key

Stdio transport:

DATABASE_URL=postgresql://memexai:memexai@localhost:5433/memexai \
MEMEX_API_KEY=dev-agent-key \
node apps/service/dist/index.js --stdio --user-id user_123 --actor claude-desktop

Quick Start: Direct Postgres

Use direct mode when your app already owns Postgres or you want no HTTP service.

npm install @memexai/core ai @ai-sdk/google
import { createMemex } from "@memexai/core"
import { generateText, stepCountIs } from "ai"
import { createGoogleGenerativeAI } from "@ai-sdk/google"

const google = createGoogleGenerativeAI()

const memex = createMemex({
  databaseUrl: process.env.DATABASE_URL!,
  model: google("gemini-2.5-flash"),
})

await memex.migrate()

const memory = memex.forUser({ userId: "user_123", actor: "assistant" })
const system = await memory.getSystemPrompt("You are a helpful assistant with durable user memory.")

const result = await generateText({
  model: google("gemini-2.5-flash"),
  system,
  prompt: "Remember that I prefer quiet neighborhoods near good schools.",
  tools: memory.createMemorySubagentToolset(),
  stopWhen: stepCountIs(5),
})

await memex.end()

Inspect and manage memory with the admin CLI — works headlessly for agents and humans:

# Start the web UI (human-friendly)
npx @memexai/admin serve --database-url postgresql://...
# Opens http://localhost:4040/admin

# CLI for agents (no browser needed)
npx @memexai/admin -d $DATABASE_URL --json users list
npx @memexai/admin -d $DATABASE_URL files get shared/index.md
npx @memexai/admin -d $DATABASE_URL memory snapshot --user alice --at "2025-06-01T10:00:00Z"
npx @memexai/admin -d $DATABASE_URL trace <toolCallId>

The CLI for agents supports time-travel (reconstruct memory at a past timestamp), memory subagent trace (what did a specific tool call do?), setup bootstrapping, and all CRUD operations. See docs/admin-cli.md for the full reference.

Docker exec: the memex-admin binary is built into the runtime image:

docker exec <container> memex-admin --json users list

Python SDK

pip install memexai
from memexai import MemexAI

memex = MemexAI(url="http://localhost:8080", api_key="dev-agent-key")
memory = memex.for_user("user_123", actor="assistant")

await memory.write_file("user/profile.md", "# Profile\n\n- Prefers quiet neighborhoods.", reason="captured preference")
result = await memory.find("quiet neighborhoods")

await memex.close()

Framework Adapters

Adapter Package Language
Vercel AI SDK @memexai/sdk, @memexai/core TypeScript
Anthropic SDK @memexai/core TypeScript
LangChain @memexai/sdk, @memexai/core, memexai TypeScript + Python
OpenAI SDK @memexai/sdk TypeScript
LlamaIndex memexai Python
CrewAI memexai Python
MCP (SSE + stdio) service Any

The instance methods are the shortest path. For model calls, use both the prompt helper and the toolset:

const system = await memory.getSystemPrompt("You are a helpful assistant with durable user memory.")
const memorySubagentTools = memory.createMemorySubagentToolset()
const rawTools = memory.createRawToolset()

Named adapter imports are also available:

import { createVercelAITools } from "@memexai/sdk/adapters/vercel-ai"
import { createAnthropicTools, handleAnthropicToolCall } from "@memexai/core/adapters/anthropic"
import { createLangChainTools } from "@memexai/core/adapters/langchain"
import { createOpenAITools } from "@memexai/sdk/adapters/openai"

Raw MCP-style execution is available directly:

await memex.executeTool("memory_write", {
  path: "user/profile.md",
  content: "# Profile\n\n- Prefers quiet neighborhoods.",
  reason: "captured user preference",
}, { userId: "user_123", actor: "assistant" })

Memory Model

Memory is stored as files in Postgres tables:

  • mx_file stores the current file content.
  • mx_revision stores every write snapshot with actor, reason, and tool call ID.
  • mx_access_log stores every read, write, patch, search, and smart-read touch.

Agents see virtual paths:

user/profile.md  -> users/{userId}/profile.md
shared/index.md  -> shared/index.md

The model never receives raw physical paths. Core path validation maps virtual paths to the current userId scope; your backend must treat userId as trusted server-side identity. See docs/scopes.md.

Admin UI

Docker includes the admin UI at http://localhost:8080/admin.

Direct Postgres mode:

npx @memexai/admin --database-url postgresql://...

The admin UI shows files as a tree with full content, revision history for each write, access logs, and users derived from scoped memory paths.

Why Postgres Instead Of A Vector Store?

Most durable agent memory is not a nearest-neighbor problem. It is structured recall:

  • What does this user prefer?
  • What has the agent already learned?
  • Which shared file explains this workflow?
  • What changed, and who changed it?

Postgres gives MemexAI durable storage, full-text search, migrations, access control boundaries, and audit tables in one place. Postgres full-text ranking is enough for deterministic candidate discovery. When a model is configured, MemexAI can resolve over memory files through the memory subagent path, with bounded reads and cited source paths.

Comparison

This table describes the default product bias. Managed offerings and optional graph/vector backends vary.

mem0 OSS Zep MemexAI
Default storage Vector/KV stack Managed graph memory Postgres
Agent surface Automatic extraction APIs Platform memory APIs Two tools by default
Raw file control Limited Limited First-class
Revision history Not the default Not self-hosted by default Built in
Access logs Not the default Platform dependent Built in
Self-hosting Requires more infra Cloud-first One Postgres-backed service
Admin UI Not core OSS Managed Self-hosted

The goal is not to be a bigger memory platform. The goal is a smaller memory loop: stored memory influences the next response, and humans can inspect the record that made it happen.

Examples

Direct Postgres examples:

cd examples/vercel-ai
DATABASE_URL=postgresql://... GEMINI_API_KEY=... bun run start "Remember I prefer 2BHK apartments"

cd ../anthropic
DATABASE_URL=postgresql://... ANTHROPIC_API_KEY=... bun run start "Remember I prefer 2BHK apartments"

HTTP service demo agent:

docker compose up -d

MEMEX_URL=http://localhost:8080 \
MEMEX_API_KEY=dev-agent-key \
GEMINI_API_KEY=... \
bun run demo:agent -- "Remember that I prefer quiet neighborhoods"

Smoke test without an LLM:

MEMEX_URL=http://localhost:8080 \
MEMEX_API_KEY=dev-agent-key \
bun run demo:agent -- --smoke

Deeper Topics

Status

Early stage. The core loop works: Postgres-backed files, scoped agent tools, prompt-block injection, BM25 full-text search via memory_find, optional pgvector hybrid search with RRF fusion, model-backed memory_remember/memory_context, revisions, access logs, SDKs, and admin UI.

Community

Join Slack →  ·  Open an issue →  ·  Talk to the founders →

排名相邻

AI Rank iPhone 版

随时追踪 AI 模型榜单

在 App Store 下载