Skip to main content
doc0blade47/mem0documentation home
Sign in

Quick Start

Last updated Oct 11, 2026100% grounded
Relevant source files

The following files were used as context for generating this wiki page:

Overview

This quick start guide demonstrates how to install, initialize, and integrate Mem0 across Python and TypeScript environments to equip language models and coding agents with persistent, context-aware memory Python Agent Core, Typescript Core. By combining client instantiation, conversational write paths, and scoped semantic search, developers can store user preferences, manage project trajectories, and bridge agent frameworks without boilerplate Memory Lifecycle, Mem0 Strands.

constructor(config: Partial<MemoryConfig> = {}) {
  // Merge and validate config
  this.config = ConfigManager.mergeConfig(config);

Sources: mem0-ts/src/oss/src/memory/index.ts:220-222

The architecture supports both local self-hosted configurations and the managed Mem0 platform Hermes Plugin, enabling seamless zero-code proxying via OpenAI-compatible endpoints Proxy as well as native plugins for ecosystem harnesses like LangChain mem0.ts, Vercel AI SDK mem0-utils.ts, and IDE assistants Claude Code Plugin.

add_memory: tool({
  description: "Add a new memory. This method is called everytime the user informs anything about themselves, their preferences, or anything that has any relevant information which can be useful in the future conversation. This can also be called when the user asks you to remember something. Set infer to false to store the memory verbatim without LLM fact extraction.",
  args: {
    text: tool.schema.string().describe("Memory text content"),
    user_id: tool.schema.string().optional().describe("User ID"),
    app_id: tool.schema.string().optional().describe("App/Project ID"),
    agent_id: tool.schema.string().optional().describe("Agent ID"),
    metadata: tool.schema.record(tool.schema.string(), tool.schema.any()).optional().describe("Metadata key-value pairs"),
    infer: tool.schema.boolean().optional().describe("Set to false to store memory verbatim without LLM fact extraction"),
    scope: tool.schema.string().optional().describe('Write scope: "project" (this repo, default), "session" (this run), or "global" (user-wide, all projects). Use "global" only when explicitly asked.')
  },

Sources: integrations/opencode-plugin/opencode-mem0.ts:380-390

Installing and Initializing Mem0

Python and TypeScript SDK Setup

To install Mem0 in Python and TypeScript environments, package managers install the core client libraries from PyPI and npm. Python environments import Memory or MemoryClient from the mem0 package mem0/init.py, while TypeScript projects utilize MemoryClient from mem0ai or community integrations such as Mem0Memory mem0-ts/src/community/src/integrations/langchain/mem0.ts.

pip install mem0ai
npm install mem0ai @langchain/core @langchain/community

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:1-2, mem0/init.py:3-6

Client Instantiation and Configuration

Client initialization requires passing configuration options containing credentials and optional host endpoints. In TypeScript, Mem0Memory validates that both apiKey and sessionId are present during construction before instantiating the underlying MemoryClient mem0-ts/src/community/src/integrations/langchain/mem0.ts.

import { Mem0Memory } from "./mem0";
 
const memory = new Mem0Memory({
  sessionId: "user123",
  apiKey: "your-api-key",
  memoryOptions: {
    user_id: "user123",
  },
});

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:151-206

Warning

Omitting apiKey or sessionId when constructing Mem0Memory throws an immediate runtime error before any client connection occurs. Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:172-178

PropertyTypeDefaultPurpose
apiKeystringRequiredAuthentication credential for the Mem0 service
sessionIdstringRequiredUnique identifier for the chat session or user scope
memoryKeystring"history"Key used to store and retrieve memory variables in LangChain
humanPrefixstring"Human"Prefix label for human utterances in formatted buffer strings
aiPrefixstring"AI"Prefix label for assistant responses in formatted buffer strings
separateMessagesbooleanfalseReturn separate messages for chat history versus a single condensed HumanMessage

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:152-170

Storing Conversational Context

Conversation Context Capture and Extraction

LangChain Integration and Message Condensation

import { Mem0Memory } from "./mem0";
import { ChatOpenAI } from "@langchain/openai";
import { ConversationChain } from "langchain/chains";
 
const memory = new Mem0Memory({
  sessionId: "user123",
  apiKey: process.env.MEM0_API_KEY!,
  memoryOptions: {
    user_id: "user123",
  },
});
 
const model = new ChatOpenAI({
  modelName: "gpt-4o-mini",
  temperature: 0,
});
 
const chain = new ConversationChain({ llm: model, memory });

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:131-149

export const condenseMem0MemoryIntoHumanMessage = (
  memory: Memory[],
): HumanMessage => {
  const basePrompt =
    "These are the memories I have stored. Give more weightage to the question by users and try to answer that first. You have to modify your answer based on the memories I have provided. If the memories are irrelevant you can ignore them. Also don't reply to this section of the prompt, or the memories, they are only for your reference. The MEMORIES of the USER are: \n\n";
  const systemPrompt = mem0MemoryContextToSystemPrompt(memory);
 
  return new HumanMessage(`${basePrompt}\n${systemPrompt}`);
};

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:50-58

Note

condenseMem0MemoryIntoHumanMessage formats retrieved memories into a single instruction-prefixed HumanMessage by default, instructing the model to prioritize direct user questions while referencing stored facts. Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:50-58

Memory Formatting Utilities

export const mem0MemoryToMessages = (memories: Memory[]): BaseMessage[] => {
  if (!memories || !Array.isArray(memories)) {
    return [];
  }
 
  const messages: BaseMessage[] = [];
 
  const memoryContent = memories
    .filter((m) => m?.memory)
    .map((m) => m.memory)
    .join("\n");
 
  if (memoryContent) {
    messages.push(new SystemMessage(memoryContent));
  }
 
  memories.forEach((memory) => {
    if (memory.messages) {
      memory.messages.forEach((msg) => {
        const content =
          typeof msg.content === "string"
            ? msg.content
            : JSON.stringify(msg.content);
        if (msg.role === "user") {
          messages.push(new HumanMessage(content));
        } else if (msg.role === "assistant") {
          messages.push(new AIMessage(content));
        } else if (content) {
          messages.push(new ChatMessage(content, msg.role));
        }
      });
    }
  });
 
  return messages;
};

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:65-102

Tip

Setting separateMessages: true in Mem0MemoryInput causes loadMemoryVariables to return distinct SystemMessage and chat history objects via mem0MemoryToMessages rather than a unified prompt block. Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:123-124, mem0-ts/src/community/src/integrations/langchain/mem0.ts:240-246

Querying Memories Across Scopes

Semantic Retrieval and Scoped Parameters

Memories can be queried dynamically based on conversation input or retrieved entirely via scoped identifiers. When input values are present during memory loading, Mem0Memory executes a semantic search query against the client; otherwise, it retrieves all stored records for the target entity.

async loadMemoryVariables(values: InputValues): Promise<MemoryVariables> {
  const searchType = values.input ? "search" : "get_all";
  let memories: Memory[] = [];
 
  try {
    if (searchType === "get_all") {
      memories = await this.mem0Client.getAll({
        user_id: this.sessionId,
        ...this.memoryOptions,
      });
    } else {
      memories = await this.mem0Client.search(values.input, {
        user_id: this.sessionId,
        ...this.memoryOptions,
      });
    }
  } catch (error) {
    console.error("Error loading memories:", error);
    return this.returnMessages
      ? { [this.memoryKey]: [] }
      : { [this.memoryKey]: "" };
  }
 
  if (this.returnMessages) {
    return {
      [this.memoryKey]: this.separateMessages
        ? mem0MemoryToMessages(memories)
        : [condenseMem0MemoryIntoHumanMessage(memories)],
    };
  }
 
  return {
    [this.memoryKey]: this.separateMessages
      ? getBufferString(
          mem0MemoryToMessages(memories),
          this.humanPrefix,
          this.aiPrefix,
        )
      : (condenseMem0MemoryIntoHumanMessage(memories).content ?? ""),
  };
}

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:217-257

Warning

If a query execution throws an error during loadMemoryVariables, the method catches the failure and returns an empty array or empty string depending on returnMessages configuration rather than interrupting the chat chain. Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:233-238

Agent Harness Filtering and Tool Parameters

Agent harnesses partition memory access using granular identifiers such as user IDs, agent IDs, and run IDs. For instance, the DeepSeek integration registers a search_memory tool that validates user overrides and resolves filters prior to querying the vector client.

const scopeParams = {
  userId: {
    type: "string",
    description:
      "Entity that owns the memory. Defaults to the plugin's configured userId; cross-user overrides require allowUserOverride in plugin configuration.",
  },
  agentId: {
    type: "string",
    description: "Optional agent scope, to partition memories by agent.",
  },
  runId: {
    type: "string",
    description: "Optional run/session scope, to partition memories by session.",
  },
} as const;

Sources: integrations/deepseek-plugin/src/index.ts:80-94

Caution

The platform rejects top-level entity parameters during search operations; search scopes must be nested inside the filters property, unlike memory addition calls which accept top-level parameters. Sources: integrations/deepseek-plugin/src/index.ts:200-202

Configuring Framework and SDK Adapters

LangChain Integration Architecture

The LangChain integration package maps Mem0 persistent memory storage into LangChain memory management abstractions through the Mem0Memory class. This class extends BaseChatMemory to load, format, and save conversational turns and retrieved facts using MemoryClient from mem0ai.

export class Mem0Memory extends BaseChatMemory implements Mem0MemoryInput {
  memoryKey = "history";
  apiKey: string;
  sessionId: string;
  humanPrefix = "Human";
  aiPrefix = "AI";
  mem0Client: InstanceType<typeof MemoryClient>;
  memoryOptions: AddMemoryOptions | SearchMemoryOptions | GetAllMemoryOptions;
  mem0Options: ClientOptions;
  separateMessages?: boolean;

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:151-170

Formatting utilities transform retrieved memory items into structured message formats or consolidated prompt strings. The condenseMem0MemoryIntoHumanMessage function builds a HumanMessage incorporating stored facts with explicit instructions for the model to prioritize user questions and treat retrieved memory strictly as reference context.

export const condenseMem0MemoryIntoHumanMessage = (
  memory: Memory[],
): HumanMessage => {
  const basePrompt =
    "These are the memories I have stored. Give more weightage to the question by users and try to answer that first. You have to modify your answer based on the memories I have provided. If the memories are irrelevant you can ignore them. Also don't reply to this section of the prompt, or the memories, they are only for your reference. The MEMORIES of the USER are: \n\n";
  const systemPrompt = mem0MemoryContextToSystemPrompt(memory);
 
  return new HumanMessage(`${basePrompt}\n${systemPrompt}`);
};

Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:50-58

Tip

Setting separateMessages: true in Mem0MemoryInput causes loadMemoryVariables to return distinct SystemMessage instances and chat history objects via mem0MemoryToMessages rather than collapsing all context into a single unified prompt block. Sources: mem0-ts/src/community/src/integrations/langchain/mem0.ts:116-124, mem0-ts/src/community/src/integrations/langchain/mem0.ts:240-246

Vercel AI SDK Utilities

The Vercel AI SDK utilities module provides functions for adding, updating, retrieving, and searching memories within language model pipelines. The updateMemories function dispatches POST requests to the Mem0 API endpoint, transmitting conversation messages alongside optional configuration fields with specific attribution headers.

const updateMemories = async (messages: Array<Message>, config?: Mem0ConfigSettings) => {
    try {
        const apiKey = loadApiKey({
            apiKey: config?.mem0ApiKey,
            environmentVariableName: "MEM0_API_KEY",
            description: "Mem0",
        });
 
        const body: Record<string, any> = { messages };
        if (config?.user_id) body.user_id = config.user_id;
        if (config?.app_id) body.app_id = config.app_id;
        if (config?.agent_id) body.agent_id = config.agent_id;
        if (config?.run_id) body.run_id = config.run_id;
        if (config?.metadata) body.metadata = config.metadata;
        if (config?.infer != null) body.infer = config.infer;
 
        const options = {
            method: 'POST',
            headers: {
                Authorization: `Token ${apiKey}`,
                'Content-Type': 'application/json',
                // Surface attribution. Set-once by contract: this wrapper is the
                // outermost layer on these raw fetch calls.
                'X-Mem0-Source': 'VERCEL_AI_SDK',
                'X-Mem0-Client': `mem0-vercel-ai-provider/${PROVIDER_VERSION}`
            },
            body: JSON.stringify(body),
        };
 
        const baseUrl = config?.host || 'https://api.mem0.ai';
        const response = await fetch(`${baseUrl}/v3/memories/add/`, options);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Error in updateMemories:", error);
        throw error;
    }
}

Sources: integrations/vercel-ai-sdk/src/mem0-utils.ts:325-365

Memory retrieval routines in the Vercel AI SDK integration normalize varying API response structures into standard formats. The getMemories function guarantees a flat array output whether the underlying data payload returns as a raw array or an object containing a results key.

const getMemories = async (prompt: LanguageModelV3Prompt | string, config?: Mem0ConfigSettings) => {
    try {
        const message = typeof prompt === 'string' ? prompt : flattenPrompt(prompt);
        const data = await searchInternalMemories(message, config);
        // Normalize: always return a flat array regardless of API response shape
        return Array.isArray(data) ? data : (data?.results ?? []);
    } catch (error) {
        console.error("Error in getMemories:", error);
        throw error;
    }
}

Sources: integrations/vercel-ai-sdk/src/mem0-utils.ts:391-401

Executing Transparent Memory Proxying

Proxy Architecture and Interception

The transparent memory proxy intercepts chat completion requests through an OpenAI-compatible interface powered by litellm. The proxy client initializes via the Mem0 class, selecting either a hosted MemoryClient when an API key is supplied or a local Memory instance configured with user settings. Incoming chat requests hit the Completions.create method, which enforces that at least one identifier among user_id, agent_id, or run_id is present before processing.

class Mem0:
    def __init__(
        self,
        config: Optional[dict] = None,
        api_key: Optional[str] = None,
        host: Optional[str] = None,
    ):
        if api_key:
            self.mem0_client = MemoryClient(api_key, host)
        else:
            self.mem0_client = Memory.from_config(config) if config else Memory()
 
        self.chat = Chat(self.mem0_client)
 

Sources: mem0/proxy/main.py:23-36

Warning

Omitting all three scope identifiers (user_id, agent_id, and run_id) in a proxy completion call triggers a ValueError during validation. At least one scope parameter must be provided for memory persistence and retrieval. Sources: mem0/proxy/main.py:92-93

Automatic Memory Augmentation

When a completion request includes a user-role final message, the proxy performs background ingestion and semantic search concurrently. The user message is dispatched to storage asynchronously via a daemon thread running _async_add_to_memory, preventing blocking on write operations. Simultaneously, _fetch_relevant_memories queries the underlying client using the last six conversation turns, bounded by the configured top_k parameter.

prepared_messages = self._prepare_messages(messages)
if prepared_messages[-1]["role"] == "user":
    self._async_add_to_memory(messages, user_id, agent_id, run_id, metadata, filters)
    relevant_memories = self._fetch_relevant_memories(messages, user_id, agent_id, run_id, filters, top_k)
    logger.debug(f"Retrieved {len(relevant_memories)} relevant memories")
    prepared_messages[-1]["content"] = self._format_query_with_memories(messages, relevant_memories)
 

Sources: mem0/proxy/main.py:100-106

The retrieved facts and associated relational entities are formatted directly into the final user prompt using MEMORY_ANSWER_PROMPT as a system message prefix. Telemetry events (mem0.chat.create) are captured upon completion based on whether the client instance is local or remote.

def _format_query_with_memories(self, messages, relevant_memories):
    # Check if self.mem0_client is an instance of Memory or MemoryClient
 
    entities = []
    if isinstance(self.mem0_client, mem0.memory.main.Memory):
        memories_text = "\n".join(memory["memory"] for memory in relevant_memories["results"])
        if relevant_memories.get("relations"):
            entities = [entity for entity in relevant_memories["relations"]]
    elif isinstance(self.mem0_client, mem0.client.main.MemoryClient):
        memories_text = "\n".join(memory["memory"] for memory in relevant_memories)
    return f"- Relevant Memories/Facts: {memories_text}\n\n- Entities: {entities}\n\n- User Question: {messages[-1]['content']}"

Sources: mem0/proxy/main.py:176-186

Tip

The proxy automatically inspects the model for function calling compatibility using litellm.supports_function_calling(model) and rejects unsupported models immediately before executing storage or retrieval steps. Sources: mem0/proxy/main.py:95-98

Managing Agent Plugin Embeddings

Plugin Architecture and Cordis Bindings

The DeepSeek agent plugin integrates Mem0 long-term memory into the Cordis harness architecture by defining the plugin module name as mem0 and declaring dependencies on tools and systemPrompt services. During bootstrap, the apply function validates configuration inputs, enforcing that an API key is present via config.apiKey or the MEM0_API_KEY environment variable and that config.userId is a non-empty string.

export const name = "mem0";
export const inject = ["tools", "systemPrompt"];

Sources: integrations/deepseek-plugin/src/index.ts:30-31

export function apply(ctx: Context, config: Config): void {
  const apiKey = config.apiKey ?? process.env.MEM0_API_KEY;
  if (!apiKey) {
    throw new Error("deepseek-plugin: set config.apiKey or the MEM0_API_KEY env var");
  }
  const userId = config.userId?.trim();
  if (!userId || /^\*+$/.test(userId)) {
    throw new Error("deepseek-plugin: config.userId is required");
  }

Sources: integrations/deepseek-plugin/src/index.ts:96-104

Configuration OptionTypeDefaultPurpose
apiKeystringprocess.env.MEM0_API_KEYMem0 API authentication token.
userIdstringrequiredDefault entity owning stored memories.
allowUserOverridebooleanfalseExplicitly permits model-selected cross-user access.
hoststringapi.mem0.aiOptional Mem0 Platform base-URL override.
autoRecallbooleantrueRecalls relevant memory before each model request.
autoCapturebooleantrueStores completed interaction turns automatically.

Sources: integrations/deepseek-plugin/src/index.ts:53-66

Warning

Providing an asterisk wildcard (*) or leaving userId empty causes initialization to throw an immediate error during plugin application. Sources: integrations/deepseek-plugin/src/index.ts:101-104

Session Lifecycle and Event Hooks

The plugin utilizes a weak map to maintain per-session states, tracking both conversation messages and local lifecycle handlers. When autoRecall is active, the system prompt assembly hook intercepts context requests, extracts the latest user prompt, and queries the memory client with an auto-recall limit of 5 results.

const sessionStates = new WeakMap<object, SessionState>();
const stateFor = (session: object): SessionState => {
  let state = sessionStates.get(session);
  if (!state) {
    const lifecycle = createMemoryLifecycle({ recallHeading: USER_RECALL_HEADING });
    lifecycle.beginSession();
    state = { lifecycle, messages: [] };
    sessionStates.set(session, state);
  }
  return state;
};

Sources: integrations/deepseek-plugin/src/index.ts:111-121

if (config.autoRecall !== false) {
  ctx.on("system-prompt/assemble", async (_input, context, next): Promise<PromptAssembly> => {
    const assembly = await next();
    const { agent, signal } = context;
    if (!agent || signal?.aborted) return assembly;
 
    const state = stateFor(agent.session);
    const prompt = state.lifecycle.prepareConversation(
      agent.session
        .deriveMessages()
        .filter((message) => message.role === "user" && message.source?.kind === "user"),
    ).at(-1)?.content;
    if (!prompt) return assembly;
 
    const memoryContext = await state.lifecycle.recall(prompt, true, async (query) => {
      const started = Date.now();
      try {
        const result = await client.search(query, {
          filters: resolveSearchFilters({}, userId),
          topK: AUTO_RECALL_LIMIT,
        });

Sources: integrations/deepseek-plugin/src/index.ts:129-149

Sources: integrations/deepseek-plugin/src/index.ts:174-196

Tip

The python agent core modules across integration plugins share common harness configuration parameters, exposing environment prefix mapping, data directory naming, and source tagging helpers. Sources: integrations/antigravity-plugin/core/memory_core.py:40-60

Was this page helpful?