Skip to content
Docs ·Amem AI memory

Amem AI memory

Preferences and facts API, coding and voice integrations, storage and LLM configuration

Use an Amem key to store and retrieve preferences and work records, or include retrieved memories in an AI Gateway request. Coding and voice integration examples follow below.

Connect an organization and a user

An owner or admin of an organization with Amem access enables Amem in organization settings. Choose an Amem-only key if your app calls models directly, or AI Gateway + Amem if it calls models through AlpRouter. Keep the key on your app server and assign each signed-in user a stable UUID v4. The examples read it from AMEM_USER_ID.

Create an Amem-only key

Derive the user ID from the authenticated session on your server. Creating a new key starts a separate project. To replace the secret for an existing project, choose “Rotate secret” on its key details page. Preferences and usage history stay with the project.

Get consent and save preferences

ItemAccepted values
languageko, en, ja
pressureUnitbar, kPa, psi
answerFormatchecklist, paragraph, table

Send at least one field in a JSON body of up to 4 KiB. A successful PUT returns 204 with an empty body. Saving again replaces the entire profile and resets its expiry to 30 days from the write.

curl --fail-with-body -sS -X PUT 'https://alprouter.com/api/v1/memory/preferences' \
  -H "Authorization: Bearer $ALPROUTER_API_KEY" \
  -H "x-alprouter-memory-user: $AMEM_USER_ID" \
  -H "Content-Type: application/json" \
  -d '{"consent":true,"preferences":{"pressureUnit":"bar","answerFormat":"checklist"}}'

Connect an existing OpenAI or Claude app

An Amem-only key supports GET, PUT and DELETE on the preferences API. You can start without buying model credits. Activity shows monthly reads, writes and deletes. Keep your existing provider API key and billing arrangement.

Install Python requests and the appropriate provider SDK on your server. Set the model ID and provider API key in environment variables. These examples add the saved preferences to the instructions in your existing model request.

from openai import OpenAI
import os
import requests

def instructions(user_id):
    response = requests.get(
        "https://alprouter.com/api/v1/memory/preferences",
        headers={
            "Authorization": "Bearer " + os.environ["ALPROUTER_API_KEY"],
            "x-alprouter-memory-user": user_id,
        },
        timeout=3,
    )
    response.raise_for_status()
    prefs = response.json()["preferences"] or {}
    return "Apply unless the user asks otherwise. " + " ".join(
        f"{field}: {value}." for field, value in prefs.items()
    )

# Use the stable UUID from your authenticated session in production.
user_id = os.environ["AMEM_USER_ID"]
question = "How should I inspect this pump?"

reply = OpenAI().responses.create(
    model=os.environ["OPENAI_MODEL"],
    instructions=instructions(user_id),
    input=question,
)
print(reply.output_text)

Apply selected preferences automatically with AI Gateway

Use the same organization key and user header. This request sends only the saved pressure unit to the model. Separate multiple field names with commas. Omit x-alprouter-memory-fields to apply every saved field.

curl --fail-with-body -sS 'https://alprouter.com/api/v1/chat/completions' \
  -H "Authorization: Bearer $ALPROUTER_API_KEY" \
  -H "x-alprouter-memory-user: $AMEM_USER_ID" \
  -H "x-alprouter-memory-fields: pressureUnit" \
  -H "Content-Type: application/json" \
  -d '{"model":"anthropic/claude-opus-5.5","messages":[{"role":"user","content":"Gauge readings: 600 kPa / 6 bar. Give one reading in my preferred unit."}]}'

The instruction asks the model to follow an explicit preference in the current question first. If no selected preference is stored, Amem adds no instruction. History sent by the app and preferences added by the gateway both count as model input.

Read preferences and handle consent withdrawal

curl --fail-with-body -sS 'https://alprouter.com/api/v1/memory/preferences' \
  -H "Authorization: Bearer $ALPROUTER_API_KEY" \
  -H "x-alprouter-memory-user: $AMEM_USER_ID"

GET returns preferences and expiresAt. Both are null if no preferences exist or the profile has expired. If the user withdraws consent, delete the profile with the request below. Success returns 204. Turning off Amem for the organization deletes all its saved profiles.

After Amem access ends, the same active app key can still delete a user’s preferences.

curl --fail-with-body -sS -X DELETE 'https://alprouter.com/api/v1/memory/preferences' \
  -H "Authorization: Bearer $ALPROUTER_API_KEY" \
  -H "x-alprouter-memory-user: $AMEM_USER_ID"

Business facts and revision history

Apps can store consented business facts in a separate API. Reusing a topic closes the previous version at the new effective time. Supply effectiveAt for the time the fact took effect and source for a reference in your app. Each version is retained for up to 30 days after storage.

curl --fail-with-body -sS 'https://alprouter.com/api/v1/memory/facts' \
  -H "Authorization: Bearer $ALPROUTER_API_KEY" \
  -H "x-alprouter-memory-user: $AMEM_USER_ID" \
  -H "Content-Type: application/json" \
  -d '{"action":"add","consent":true,"effectiveAt":"2026-12-01T09:00:00Z","facts":[{"topic":"order-17.delivery","content":"Delivery is December 18.","source":"PO-17","entities":["PO-17"]}]}'

Read the current value with get, or include asOf to read a past value. Use search for natural-language retrieval and traverse to follow shared entities across records. Use the next cursor for history and list pagination.

{
  "action": "get",
  "topic": "order-17.delivery",
  "asOf": "2026-12-01T12:00:00Z"
}
APIOperation
add · import · exportDirect writes, bulk import and export
extract · documentExtract from conversations and documents
get · list · profile · search · traverse · answerCurrent profiles, filtered search, graph traversal and cited answers
history · forget · feedbackRevision history, deletion and retrieval feedback
configure · settings · consolidateInstructions, categories and consolidation settings

Extraction, reranking and summaries require a configured model. Documents support UTF-8 text, MDX, PDF, PNG and JPEG. Scanned PDFs without a text layer use OCR on the first 16 pages. Enable dream in configure to consolidate related memories periodically. Set x-alprouter-memory-facts to search on Chat Completions to send retrieved evidence to the model.

Use answer to return a verbatim answer with its source. Empty retrieval returns null without calling a model. The group and agent headers are x-alprouter-memory-group and x-alprouter-memory-agent.

To manage shared group memory or agent memory, send exactly one stable UUID in the user, group, or agent header. The app server must authorize access to that subject. All three spaces are isolated within the project.

Send DELETE to the same endpoint to withdraw consent for business memory. This clears every agent and run namespace, revision, generated summary, and setting for that subject. Send DELETE to /memory to erase both preferences and business memories atomically.

Project settings and model selection

Use a management credential to PATCH /memory/projects/{id}/settings and set extraction instructions, categories, decay and provider credentials. When the app sets x-alprouter-amem-model to project, the chosen provider receives the relevant text for extraction, summaries or answers and charges the project’s provider account.

Batch operations and exports

Save or forget up to 1,000 topics in one request. Use export to select fields, or structured_export to generate and validate output against your JSON Schema. Queue a document extraction or export with enqueue and poll its receipt with job. Withdrawing consent removes pending input and results.

Search memory from an agent

Configure your MCP client to use /api/v1/memory/mcp. Set the authorization header and exactly one user, group or agent header in your trusted server. Read and search tools are available by default. After obtaining write consent, set x-alprouter-amem-tools to write. The /memory/events endpoint lists the last seven days of project activity.

Coding tool capture

Download and extract the integrations, then install them in a virtual environment. Give the editor an Amem API key and the authenticated user’s stable UUID. Capture requires explicit consent and an allowed workspace.

Download the Amem integrations (ZIP)
cd amem-integrations-0.2.0
python3 -m venv .venv
. .venv/bin/activate
python -m pip install .
export AMEM_CAPTURE_ROOT="/absolute/path/to/approved-project"
export AMEM_WRITE_CONSENT=1
# Set ALPROUTER_API_KEY and AMEM_USER_ID in the editor environment.
claude --plugin-dir "$PWD/editors/claude-code"

Claude Code, Codex, Cursor, Kimi Code and Antigravity use editor hooks. Register the bundled plugin for OpenCode, Pi, OpenClaw, DeepSeek Harness or Hermes. The README lists each entry point. Hooks read user input or visible reply text and skip messages over 2,048 UTF-16 code units or matching known credential patterns.

On withdrawal, turn capture off and erase the user’s work memories. Replayed events are stored once. Without a host event ID, identical text from the same role within a session is treated as one event.

Captured messages are immediately available for text search. A local model builds embeddings in the background. Once indexed, a request like “Call me in the afternoon” can be found with “When can I reach them?” Erasing the record also removes its pending work.

Connect final voice transcripts

Create a VoiceMemory recorder per authenticated participant and call ID. Attach LiveKit to a single-participant session. Pipecat requires an STT service that marks final frames for the selected participant. ElevenLabs uses synchronous Conversation callbacks. Audio stays out of Amem.

from amem_client import AmemClient
from amem_voice import VoiceMemory

memory = AmemClient(api_key, user_uuid, timeout=3)
voice = VoiceMemory(memory, call_id, consent=consent_from_session)

# Choose the integration used by your app.
voice.livekit(agent_session)
# Pipecat: add voice.pipecat(participant=participant_id) after STT.
# ElevenLabs: Conversation(..., **voice.elevenlabs())

# After ending the call, outside the audio callback:
voice.close()

Memory storage and vector indexes

AlpRouter’s managed Amem service stores memories and their revision history in PostgreSQL. Each memory record also holds its embedding and entities. Amem follows shared entities to find related memories. Self-hosted deployments can connect a secondary vector index.

PostgreSQL holds authoritative records, permissions and expiry times. The secondary index receives embeddings, random IDs and a scope hash. Results are checked against the authoritative scope and expiry. Deletions take effect in Amem at commit. A worker retries external index erasure.

python -m pip install ".[providers]"
amem-providers list
export AMEM_VECTOR_PROVIDER=sqlite
export AMEM_VECTOR_CONFIG='{"path":"/var/lib/amem/vectors.db"}'
export AMEM_VECTOR_TARGET=local-index-v1
# Set AMEM_INDEX_DATABASE_URL and AMEM_PROVIDER_TOKEN on the operator host.
amem-providers register-index
amem-providers serve --sync

Set the gateway’s AMEM_VECTOR_URL to http://127.0.0.1:8068/v1 and use the worker’s service token. Match the embedding model and dimensions. Options include the 25 Mem0 Python 2.2.1 drivers, Neon via pgvector, Cloudflare Vectorize, SQLite and in-memory storage. Validate managed providers in your own account.

LLMs for extraction and summaries

Self-hosted operators can pin the extraction endpoint and provider. Adapters include local Ollama, vLLM, LM Studio, AWS Bedrock, Anthropic and OpenAI. Run amem-providers list for the complete registry. Listing providers and recording hook text do not call a generative model.

export AMEM_LLM_PROVIDER=openai_compatible
export AMEM_LLM_CONFIG='{"model":"local-model","openai_base_url":"http://127.0.0.1:8080/v1","api_key":"local-only"}'
export AMEM_EXTRACTION_MODEL=local-model
# Set the same AMEM_PROVIDER_TOKEN on the gateway and bridge.
# Gateway: AMEM_EXTRACTION_URL=http://127.0.0.1:8068/v1
amem-providers serve

Local checks covered writes, search and deletion in SQLite, in-memory storage, Qdrant and pgvector. A local Qwen2.5 model extracted memories, and voice checks exercised each SDK’s transcript events.

Troubleshoot the integration

CodeWhat to check
memory_disabledCheck that your organization has access to Amem and has enabled it.
wrong_key_typeUse an Amem-only key or the organization's inference key for the preferences API.
memory_user_requiredSend the user’s stable UUID v4 from the app server.
invalid_memoryCheck the consent flag and the supported preference names and values.
invalid_memory_fieldsInclude at least one supported field name in the selection header.