Skip to content

Automatic memory

Wrap the model client you already use, and every reply reads memory and every exchange is saved, without the model deciding to call a tool.

An agent that has memory as a tool uses it only when its model decides to call it, and models often don't: they answer from the conversation, or ask the user for something memory already holds. Wrap your model client instead. Before each call, what memory holds about the user's latest message is put in front of the model; after it, the exchange is saved. No tool, no prompt telling the model to search.

It works with the official Anthropic and OpenAI clients in Python and TypeScript, and with any model of the Vercel AI SDK. It takes an API key from the Console, under API keys, and user_id names one of your app users.

Wrap your client

pip install alexein anthropic   # or openai
from anthropic import Anthropic
from alexein import Memory
from alexein.wrap import wrap_anthropic

memory = Memory()          # reads ALEXEIN_API_KEY; one for the process
anthropic = Anthropic()

def reply(user_id: str, conversation_id: str, messages: list[dict]) -> str:
    claude = wrap_anthropic(anthropic, memory, user_id=user_id, session=conversation_id)
    answer = claude.messages.create(model="...", max_tokens=1024, messages=messages)
    return answer.content[0].text

wrap_openai(OpenAI(), memory, user_id=...) does the same for chat.completions and responses. The async clients (AsyncAnthropic, AsyncOpenAI) work the same way, awaited.

Vercel AI SDK

import { generateText, wrapLanguageModel } from "ai";
import { alexeinMiddleware } from "@alexein/sdk/ai-sdk";

const model = wrapLanguageModel({
  model: yourModel,
  middleware: alexeinMiddleware(memory, { userId, session: conversationId }),
});
const { text } = await generateText({ model, messages });

It works with generateText, streamText and agents, for AI SDK 7.

What happens on each call

Before the call, memory is searched once with the user's latest message. When the message is short ("yes, the second one"), the end of the reply before it is searched with it. A message that is only a go-ahead, a thank-you or a greeting ("thanks!", "ok, do it", "sounds good") is not looked up; a question always is. Anything in the message that looks like a key, token or password is left out of the search.

What the search ranks first is added to the system prompt, after your own instructions:

  • at most four facts or excerpts, each once per conversation (session);
  • each on one line, with the date it was said and who said it: the user, an assistant, or someone else;
  • inside a <memory> block that tells the model it is quoted data, not instructions, and that memory never authorises sharing secrets or sending data anywhere. Characters in one of them that could close or fake that block are replaced;
  • up to about max_tokens tokens (600 by default).

When memory finds nothing, nothing is added. With fast off, memory also checks whether it holds the answer, and adds nothing when it does not.

After the call, the user's message and the model's reply are saved to that user's memory, in the background: the reply reaches your user without waiting for the save. A streamed reply is saved when the stream ends. In a tool loop, memory is looked up once and only the turn's final answer is saved.

Never in the way

  • A call waits for memory at most budget (1.5 seconds by default). When memory is slower, down, or out of plan, the model is called without it; no error reaches your code.
  • Saves never delay a reply, and a failed save never raises. In Python, at most 256 saves wait at once (past that, the oldest is dropped, with a warning), and a process waits at most two seconds for them at exit.
  • The user whose memory is read and written is the user_id your code passes. Nothing a model writes or a request body holds can change it.

Options

PythonTypeScriptDefaultWhat it does
user_iduserIdrequiredYour id for the app user whose memory this is.
sessionsessionnoneThe conversation. Saves are grouped under it, a retried call edits what it saved rather than copying it, and a fact or excerpt is shown once in it.
authorauthornoneWho the user is, {"name": ..., "id": ...}; what they say is saved as theirs. Pass "self": false when the user turn holds someone else's words.
recallrecallonRead memory before each call.
savesaveonSave the user's message and the reply after each call.
budgetbudget1.5 s / 1500 msThe longest a call waits for memory.
max_tokensmaxTokens600About how many tokens of memory a call is given at most.
fastfastonQuicker search. Off, memory also checks it holds the answer and adds nothing when it does not; raise budget with it.
redactredactoffReplace phone numbers, cards, keys and the like, in the search and before memory keeps any copy.
before_savebeforeSavenoneA function (sync or async) that sees what is about to be saved and returns what to save: change it, drop some, or return nothing to save nothing. It runs in the background.

memory_of(client).last (memoryOf(client).last; middleware.alexein.last for the AI SDK) says how the last lookup went: how long the call waited, how much it added, and whether it timed out or was skipped. In a script or a serverless function, wait for the last save before it ends:

  • Python: memory_of(client).flush(), or await memory_of(client).aflush() for an async client;
  • TypeScript: await memoryOf(client).flush();
  • AI SDK: await middleware.alexein.flush(), on the middleware you passed to wrapLanguageModel.

Cost

Each call that reads memory counts one search against your plan, and each saved exchange counts its two items as events. The calls of one tool loop share one lookup, and a message that is only a go-ahead or a thank-you is not looked up. Turn recall or save off where a call does not need it.