---
title: "Quick Start"
description: "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-awar..."
last_updated: "2026-10-11T17:37:10.193334+00:00"
canonical_url: "https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/orientation/quick-start"
---

<details>
<summary>Relevant source files</summary>

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

- [mem0-ts/src/community/src/integrations/langchain/mem0.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts)
- [integrations/opencode-plugin/opencode-mem0.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/opencode-plugin/opencode-mem0.ts)
- [integrations/hermes-plugin-mem0/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/hermes-plugin-mem0/__init__.py)
- [mem0-ts/src/oss/src/memory/index.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/oss/src/memory/index.ts)
- [integrations/mem0-strands/python/src/mem0_strands/store.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/mem0-strands/python/src/mem0_strands/store.py)
- [integrations/deepseek-plugin/src/index.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts)
- [integrations/agent-plugin-core/python/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/python/memory_core.py)
- [integrations/antigravity-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/antigravity-plugin/core/memory_core.py)
- [integrations/mem0-agent-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/mem0-agent-plugin/core/memory_core.py)
- [integrations/codex-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/codex-plugin/core/memory_core.py)
- [integrations/kimi-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/kimi-plugin/core/memory_core.py)
- [integrations/claude-code-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/claude-code-plugin/core/memory_core.py)
- [integrations/cursor-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/cursor-plugin/core/memory_core.py)
- [cli/node/src/index.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/cli/node/src/index.ts)
- [mem0/memory/main.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/memory/main.py)
- [mem0/configs/prompts.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/configs/prompts.py)
- [mem0-ts/src/oss/src/prompts/index.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/oss/src/prompts/index.ts)
- [integrations/vercel-ai-sdk/src/mem0-utils.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/vercel-ai-sdk/src/mem0-utils.ts)
- [integrations/mem0-strands/python/src/mem0_strands/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/mem0-strands/python/src/mem0_strands/__init__.py)
- [integrations/n8n-nodes-mem0/nodes/Mem0/Mem0.node.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/n8n-nodes-mem0/nodes/Mem0/Mem0.node.ts)
- [integrations/mem0-strands/python/src/mem0_strands/client.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/mem0-strands/python/src/mem0_strands/client.py)
- [mem0/proxy/main.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/proxy/main.py)
- [mem0/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/__init__.py)
- [integrations/pi-agent-plugin/src/prompt.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/pi-agent-plugin/src/prompt.ts)
</details>

## 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](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/agent-plugins/python-agent-core), [Typescript Core](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/typescript-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](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/python-core/memory-lifecycle), [Mem0 Strands](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/ecosystem-integrations/mem0-strands).

```typescript
constructor(config: Partial<MemoryConfig> = {}) {
  // Merge and validate config
  this.config = ConfigManager.mergeConfig(config);
```
Sources: [mem0-ts/src/oss/src/memory/index.ts:220-222](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/oss/src/memory/index.ts#L220-L222)

The architecture supports both local self-hosted configurations and the managed Mem0 platform [Hermes Plugin](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/agent-plugins/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](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/agent-plugins/claude-code-plugin).

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/opencode-plugin/opencode-mem0.ts#L380-L390)

## 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.

```bash
pip install mem0ai
npm install mem0ai @langchain/core @langchain/community
```
Sources: [mem0-ts/src/community/src/integrations/langchain/mem0.ts:1-2](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L1-L2), [mem0/__init__.py:3-6](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/__init__.py#L3-L6)

### 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L151-L206)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L172-L178)

| Property | Type | Default | Purpose |
| :--- | :--- | :--- | :--- |
| `apiKey` | `string` | *Required* | Authentication credential for the Mem0 service |
| `sessionId` | `string` | *Required* | Unique identifier for the chat session or user scope |
| `memoryKey` | `string` | `"history"` | Key used to store and retrieve memory variables in LangChain |
| `humanPrefix` | `string` | `"Human"` | Prefix label for human utterances in formatted buffer strings |
| `aiPrefix` | `string` | `"AI"` | Prefix label for assistant responses in formatted buffer strings |
| `separateMessages` | `boolean` | `false` | Return separate messages for chat history versus a single condensed `HumanMessage` |

Sources: [mem0-ts/src/community/src/integrations/langchain/mem0.ts:152-170](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L152-L170)

## Storing Conversational Context

### Conversation Context Capture and Extraction

### LangChain Integration and Message Condensation

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L131-L149)

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L50-L58)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L50-L58)

### Memory Formatting Utilities

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L65-L102)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L123-L124), [mem0-ts/src/community/src/integrations/langchain/mem0.ts:240-246](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L240-L246)

## 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L217-L257)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L233-L238)

### 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L80-L94)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L200-L202)

## 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`.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L151-L170)

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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L50-L58)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L116-L124), [mem0-ts/src/community/src/integrations/langchain/mem0.ts:240-246](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts#L240-L246)

### 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/vercel-ai-sdk/src/mem0-utils.ts#L325-L365)

Memory retrieval routines in the [Vercel AI SDK integration](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/ecosystem-integrations/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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/vercel-ai-sdk/src/mem0-utils.ts#L391-L401)

## 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.

```python
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/proxy/main.py#L23-L36)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/proxy/main.py#L92-L93)

### 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.

```python
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/proxy/main.py#L100-L106)

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.

```python
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/proxy/main.py#L176-L186)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0/proxy/main.py#L95-L98)

## 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.

```typescript
export const name = "mem0";
export const inject = ["tools", "systemPrompt"];
```
Sources: [integrations/deepseek-plugin/src/index.ts:30-31](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L30-L31)

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L96-L104)

| Configuration Option | Type | Default | Purpose |
| :--- | :--- | :--- | :--- |
| `apiKey` | `string` | `process.env.MEM0_API_KEY` | Mem0 API authentication token. |
| `userId` | `string` | *required* | Default entity owning stored memories. |
| `allowUserOverride` | `boolean` | `false` | Explicitly permits model-selected cross-user access. |
| `host` | `string` | `api.mem0.ai` | Optional Mem0 Platform base-URL override. |
| `autoRecall` | `boolean` | `true` | Recalls relevant memory before each model request. |
| `autoCapture` | `boolean` | `true` | Stores completed interaction turns automatically. |

Sources: [integrations/deepseek-plugin/src/index.ts:53-66](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L53-L66)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L101-L104)

### 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L111-L121)

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L129-L149)

```mermaid
flowchart TD
    A["Session Event"] --> B{Event Type?}
    B -->|turn/start| C["Reset message buffer"]
    B -->|user/message| D["Push user message"]
    B -->|assistant/message| E["Push assistant message"]
    B -->|turn/end| F{Reason completed?}
    F -->|Yes| G["Add conversation to Mem0 client"]
    F -->|No| H["Skip storage"]
```
Sources: [integrations/deepseek-plugin/src/index.ts:174-196](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L174-L196)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/antigravity-plugin/core/memory_core.py#L40-L60)

## Related

- [Overview](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/orientation/overview)
- [Project Structure](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/orientation/project-structure)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/llms.txt) for all pages in this wiki.
