Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d39ebad09f | ||
|
|
9d82e2329d | ||
|
|
789cc9d607 | ||
|
|
e59e3d5f0c | ||
|
|
d926f3697c | ||
|
|
c996b0e7fa | ||
|
|
78ca85a260 |
@@ -10,7 +10,7 @@ description: "REST APIs for memory management, search, and entity operations"
|
||||
Mem0 provides a comprehensive REST API for integrating advanced memory capabilities into your applications. Create, search, update, and manage memories across users, agents, and custom entities with simple HTTP requests.
|
||||
|
||||
<Info>
|
||||
**Quick start:** Get your API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys) and make your first memory operation in minutes.
|
||||
**Quick start:** Get your API key from the <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 Dashboard</a> and make your first memory operation in minutes.
|
||||
</Info>
|
||||
|
||||
---
|
||||
@@ -87,7 +87,7 @@ All API requests require authentication using Token-based authentication. Includ
|
||||
Authorization: Token <your-api-key>
|
||||
```
|
||||
|
||||
Get your API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys).
|
||||
Get your API key from the <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 Dashboard</a>.
|
||||
|
||||
<Warning>
|
||||
**Keep your API key secure.** Never expose it in client-side code or public repositories. Use environment variables and server-side requests only.
|
||||
|
||||
@@ -4,6 +4,20 @@ description: "Release notes for the OpenClaw plugin and agent harness."
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Update label="2026-04-11" description="v1.0.6">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Telemetry:** Replaced shared `"anonymous-openclaw"` fallback with a persistent per-machine random hash (`openclaw-anon-<uuid>`), so anonymous plugin users are counted individually in PostHog ([#4790](https://github.com/mem0ai/mem0/pull/4790))
|
||||
- **Telemetry:** Added PostHog `$identify` event on first authenticated run to stitch anonymous history onto the authenticated profile ([#4790](https://github.com/mem0ai/mem0/pull/4790))
|
||||
- **Telemetry:** Fixed event loss on short-lived CLI invocations — added `beforeExit` handler to flush queued events before the process exits ([#4790](https://github.com/mem0ai/mem0/pull/4790))
|
||||
- **Telemetry:** Added lazy `/v1/ping/` email resolution so users who configure API key outside `mem0 init` show as their email in PostHog, not an md5 hash ([#4790](https://github.com/mem0ai/mem0/pull/4790))
|
||||
- **Telemetry:** Unified CLI event prefix from `openclaw.<cmd>` to `openclaw.cli.<cmd>` on the needsSetup branch to match the authenticated branch ([#4790](https://github.com/mem0ai/mem0/pull/4790))
|
||||
|
||||
**Improvements:**
|
||||
- **API:** Added `source: "OPENCLAW"` to all provider calls (`add`, `search`, `getAll`) across tools, CLI commands, recall, and the OSS backend adapter ([#4790](https://github.com/mem0ai/mem0/pull/4790))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-04-07" description="v1.0.5">
|
||||
|
||||
**Bug Fixes:**
|
||||
|
||||
@@ -45,7 +45,7 @@ Before you begin, follow these steps to set up the demo application:
|
||||
OPENAI_API_KEY=your_openai_api_key
|
||||
MEM0_API_KEY=your_mem0_api_key
|
||||
```
|
||||
You can obtain your `MEM0_API_KEY` by signing up at [Mem0 API Dashboard](https://app.mem0.ai/dashboard/api-keys).
|
||||
You can obtain your `MEM0_API_KEY` by signing up at <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 API Dashboard</a>.
|
||||
|
||||
5. Start the development server:
|
||||
```bash
|
||||
|
||||
@@ -38,7 +38,7 @@ client = MemoryClient(api_key="your-api-key")
|
||||
```
|
||||
|
||||
<Note>
|
||||
Replace `your-api-key` with your actual Mem0 API key from the [dashboard](https://app.mem0.ai). Without proper API authentication, memory operations will fail.
|
||||
Replace `your-api-key` with your actual Mem0 API key from the <a href="https://app.mem0.ai" rel="nofollow">dashboard</a>. Without proper API authentication, memory operations will fail.
|
||||
</Note>
|
||||
|
||||
---
|
||||
|
||||
@@ -17,7 +17,7 @@ from mem0 import MemoryClient
|
||||
client = MemoryClient(api_key="m0-...")
|
||||
```
|
||||
|
||||
Grab an API key from the <Link href="https://app.mem0.ai/">Mem0 dashboard</Link> to get started.
|
||||
Grab an API key from the <a href="https://app.mem0.ai/" rel="nofollow">Mem0 dashboard</a> to get started.
|
||||
|
||||
## Store and Retrieve Scoped Memories
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ client = MemoryClient(api_key="your-api-key")
|
||||
```
|
||||
|
||||
<Note>
|
||||
Your API key needs export permissions to download memory data. Check your project settings on the [dashboard](https://app.mem0.ai) if export operations fail with authentication errors.
|
||||
Your API key needs export permissions to download memory data. Check your project settings on the <a href="https://app.mem0.ai" rel="nofollow">dashboard</a> if export operations fail with authentication errors.
|
||||
</Note>
|
||||
|
||||
Let's add some sample memories to work with:
|
||||
|
||||
@@ -55,7 +55,7 @@ GEMINI_API_KEY=your-gemini-api-key-here
|
||||
```
|
||||
|
||||
<Note>
|
||||
Ensure you have your Mem0 API key from the [Mem0 Dashboard](https://app.mem0.ai) and your Gemini API key from the [Google AI Studio](https://ai.studio/app/api-keys).
|
||||
Ensure you have your Mem0 API key from the <a href="https://app.mem0.ai" rel="nofollow">Mem0 Dashboard</a> and your Gemini API key from the [Google AI Studio](https://ai.studio/app/api-keys).
|
||||
</Note>
|
||||
|
||||
## Gemini Memory Agent
|
||||
|
||||
@@ -41,7 +41,7 @@ Set up your environment variables:
|
||||
- `MEM0_API_KEY`: Your Mem0 Platform API key
|
||||
- `OPENAI_API_KEY`: Your OpenAI API key
|
||||
|
||||
You can obtain your Mem0 Platform API key from the [Mem0 Platform](https://app.mem0.ai).
|
||||
You can obtain your Mem0 Platform API key from the <a href="https://app.mem0.ai" rel="nofollow">Mem0 Platform</a>.
|
||||
|
||||
## Complete Implementation
|
||||
|
||||
@@ -357,7 +357,7 @@ Based on our previous session, I remember we covered Vision Language Models and
|
||||
## Help & Resources
|
||||
|
||||
- [LlamaIndex Agent Workflows](https://docs.llamaindex.ai/en/stable/use_cases/agents/)
|
||||
- [Mem0 Platform](https://app.mem0.ai/)
|
||||
- <a href="https://app.mem0.ai/" rel="nofollow">Mem0 Platform</a>
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
|
||||
llm = OpenAI(model="gpt-4.1-nano-2025-04-14")
|
||||
```
|
||||
|
||||
Initialize the Mem0 client. You can find your API key [here](https://app.mem0.ai/dashboard/api-keys). Read about Mem0 [Open Source](https://docs.mem0.ai/open-source/overview).
|
||||
Initialize the Mem0 client. You can find your API key <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">here</a>. Read about Mem0 [Open Source](https://docs.mem0.ai/open-source/overview).
|
||||
```python
|
||||
os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
|
||||
|
||||
|
||||
@@ -754,7 +754,7 @@ Exact output varies as Mem0 automatically extracts and deduplicates entities. Th
|
||||
- [MiroFish GitHub](https://github.com/666ghj/MiroFish) — Source code and setup guide
|
||||
- [MiroFish Documentation](https://deepwiki.com/666ghj/MiroFish) — Full framework docs
|
||||
- [Mem0 Graph Memory](/open-source/features/graph-memory) — Graph Memory documentation
|
||||
- [Mem0 Documentation](https://docs.mem0.ai/) — Full API reference
|
||||
- [Mem0 Documentation](https://docs.mem0.ai/introduction) — Full API reference
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Graph Memory" icon="network-wired" href="/open-source/features/graph-memory">
|
||||
|
||||
@@ -222,8 +222,8 @@ context = Mem0Context(user_id="user123")
|
||||
|
||||
## Resources
|
||||
|
||||
- [Mem0 Documentation](https://docs.mem0.ai)
|
||||
- [Mem0 Dashboard](https://app.mem0.ai/dashboard)
|
||||
- [Mem0 Documentation](https://docs.mem0.ai/introduction)
|
||||
- <a href="https://app.mem0.ai/dashboard" rel="nofollow">Mem0 Dashboard</a>
|
||||
- [API Reference](https://docs.mem0.ai/api-reference)
|
||||
|
||||
---
|
||||
|
||||
@@ -23,7 +23,7 @@ MEM0_API_KEY=your_mem0_api_key
|
||||
OPENAI_API_KEY=your_openai_api_key
|
||||
```
|
||||
|
||||
Get your Mem0 API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys).
|
||||
Get your Mem0 API key from the <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 Dashboard</a>.
|
||||
|
||||
### Configuration
|
||||
|
||||
@@ -308,8 +308,8 @@ run().catch(console.error);
|
||||
|
||||
## Resources
|
||||
|
||||
- [Mem0 Documentation](https://docs.mem0.ai)
|
||||
- [Mem0 Dashboard](https://app.mem0.ai/dashboard)
|
||||
- [Mem0 Documentation](https://docs.mem0.ai/introduction)
|
||||
- <a href="https://app.mem0.ai/dashboard" rel="nofollow">Mem0 Dashboard</a>
|
||||
- [API Reference](https://docs.mem0.ai/api-reference)
|
||||
- [OpenAI Documentation](https://platform.openai.com/docs)
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ Adding memory is how Mem0 captures useful details from a conversation so your ag
|
||||
- **Messages** – The ordered list of user/assistant turns you send to `add`.
|
||||
- **Infer** – Controls whether Mem0 extracts structured memories (`infer=True`, default) or stores raw messages.
|
||||
- **Metadata** – Optional filters (e.g., `{"category": "movie_recommendations"}`) that improve retrieval later.
|
||||
- **User / Session identifiers** – `user_id`, `session_id`, or `run_id` that scope the memory for future searches.
|
||||
- **User / Session identifiers** – `user_id`, `agent_id`, or `run_id` that scope the memory for future searches.
|
||||
|
||||
## How does it work?
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ Mem0 maps these classic categories onto its layered storage so you can decide wh
|
||||
Mem0 stores each layer separately and merges them when you query:
|
||||
|
||||
1. **Capture** – Messages enter the conversation layer while the turn is active.
|
||||
2. **Promote** – Relevant details persist to session or user memory based on your `user_id`, `session_id`, and metadata.
|
||||
2. **Promote** – Relevant details persist to session or user memory based on your `user_id`, `run_id`, and metadata.
|
||||
3. **Retrieve** – The search pipeline pulls from all layers, ranking user memories first, then session notes, then raw history.
|
||||
|
||||
```python
|
||||
@@ -66,19 +66,19 @@ memory = Memory(api_key=os.environ["MEM0_API_KEY"])
|
||||
memory.add(
|
||||
["I'm Alex and I prefer boutique hotels."],
|
||||
user_id="alex",
|
||||
session_id="trip-planning-2025",
|
||||
run_id="trip-planning-2025",
|
||||
)
|
||||
|
||||
# Later in the session, pull long-term + session context
|
||||
results = memory.search(
|
||||
"Any hotel preferences?",
|
||||
user_id="alex",
|
||||
session_id="trip-planning-2025",
|
||||
run_id="trip-planning-2025",
|
||||
)
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Use `session_id` when you want short-term context to expire automatically; rely on `user_id` for lasting personalization.
|
||||
Use `run_id` when you want short-term context to expire automatically; rely on `user_id` for lasting personalization.
|
||||
</Tip>
|
||||
|
||||
## When should you use each layer?
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"logo": {
|
||||
"light": "/logo/light.svg",
|
||||
"dark": "/logo/dark.svg",
|
||||
"href": "https://app.mem0.ai/"
|
||||
"href": "https://mem0.ai"
|
||||
},
|
||||
"navigation": {
|
||||
"anchors": [
|
||||
|
||||
@@ -24,7 +24,7 @@ pip install mem0ai agentops python-dotenv
|
||||
2. Valid API keys:
|
||||
- [AgentOps API Key](https://app.agentops.ai/dashboard/api-keys)
|
||||
- OpenAI API Key (for LLM operations)
|
||||
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys) (optional, for cloud operations)
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 API Key</a> (optional, for cloud operations)
|
||||
|
||||
## Basic Integration Example
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ pip install agno mem0ai python-dotenv
|
||||
```
|
||||
|
||||
2. Valid API keys:
|
||||
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys)
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 API Key</a>
|
||||
- OpenAI API Key (for the agent model)
|
||||
|
||||
## Quick Integration (Using `Mem0Tools`)
|
||||
|
||||
@@ -19,7 +19,7 @@ pip install autogen mem0ai openai python-dotenv
|
||||
|
||||
First, we'll import the necessary libraries and set up our configurations.
|
||||
|
||||
<Note>Remember to get the Mem0 API key from [Mem0 Platform](https://app.mem0.ai).</Note>
|
||||
<Note>Remember to get the Mem0 API key from <a href="https://app.mem0.ai" rel="nofollow">Mem0 Platform</a>.</Note>
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
@@ -18,7 +18,7 @@ In this guide, you'll:
|
||||
- **Python 3.12+**
|
||||
- **[uv](https://docs.astral.sh/uv/)** — Python package manager
|
||||
- **Node.js 18+** and **npm** — only needed if using the web console
|
||||
- A **Mem0 API key** from [app.mem0.ai](https://app.mem0.ai)
|
||||
- A **Mem0 API key** from <a href="https://app.mem0.ai" rel="nofollow">app.mem0.ai</a>
|
||||
- An **OpenAI API key** (or another LLM provider supported by ChatDev)
|
||||
|
||||
## Setup and Configuration
|
||||
@@ -39,7 +39,7 @@ cd frontend && npm install && cd ..
|
||||
|
||||
Set up your environment variables in a `.env` file:
|
||||
|
||||
<Note>Get your Mem0 API key from [Mem0 Platform](https://app.mem0.ai).</Note>
|
||||
<Note>Get your Mem0 API key from <a href="https://app.mem0.ai" rel="nofollow">Mem0 Platform</a>.</Note>
|
||||
|
||||
```bash
|
||||
MEM0_API_KEY=your-mem0-api-key
|
||||
@@ -194,7 +194,7 @@ This means retrieval returns memories from **both** the user's scope and the age
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `api_key` | Yes | Mem0 API key from [app.mem0.ai](https://app.mem0.ai) |
|
||||
| `api_key` | Yes | Mem0 API key from <a href="https://app.mem0.ai" rel="nofollow">app.mem0.ai</a> |
|
||||
| `user_id` | No | Scope memories to a specific user |
|
||||
| `agent_id` | No | Scope memories to a specific agent |
|
||||
|
||||
@@ -216,9 +216,9 @@ This means retrieval returns memories from **both** the user's scope and the age
|
||||
|
||||
- **No memories returned on first run** — This is expected. Memories are stored *after* the agent responds, so the first interaction has no prior context. Memories appear starting from the second interaction onward.
|
||||
- **`mem0ai` not installed** — If you see `ImportError: mem0ai is required for Mem0Memory`, run `uv add mem0ai` or `pip install mem0ai` to add the dependency.
|
||||
- **Invalid API key** — A wrong or expired `MEM0_API_KEY` will log errors like `Mem0 search failed` or `Mem0 add failed` but won't crash the agent. Check your key at [app.mem0.ai](https://app.mem0.ai).
|
||||
- **Invalid API key** — A wrong or expired `MEM0_API_KEY` will log errors like `Mem0 search failed` or `Mem0 add failed` but won't crash the agent. Check your key at <a href="https://app.mem0.ai" rel="nofollow">app.mem0.ai</a>.
|
||||
- **Pipeline headers in memories** — ChatDev automatically strips internal pipeline headers (e.g., `=== INPUT FROM TASK (user) ===`) before sending text to Mem0, so your memories stay clean.
|
||||
- **Clearing test memories** — To delete memories created during testing, use the Mem0 dashboard at [app.mem0.ai](https://app.mem0.ai) or the Python SDK: `MemoryClient().delete_all(user_id="your-test-user")`.
|
||||
- **Clearing test memories** — To delete memories created during testing, use the Mem0 dashboard at <a href="https://app.mem0.ai" rel="nofollow">app.mem0.ai</a> or the Python SDK: `MemoryClient().delete_all(user_id="your-test-user")`.
|
||||
|
||||
## Key Features
|
||||
|
||||
|
||||
@@ -17,8 +17,8 @@ Add persistent memory to [**Claude Code**](https://docs.anthropic.com/en/docs/cl
|
||||
Before setting up Mem0 with Claude Code, ensure you have:
|
||||
|
||||
1. A Mem0 Platform account and API key:
|
||||
- [Sign up at app.mem0.ai](https://app.mem0.ai)
|
||||
- [Get your API key](https://app.mem0.ai/dashboard/api-keys) (starts with `m0-`)
|
||||
- <a href="https://app.mem0.ai" rel="nofollow">Sign up at app.mem0.ai</a>
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Get your API key</a> (starts with `m0-`)
|
||||
|
||||
2. Claude Code CLI or Claude Cowork desktop app installed
|
||||
|
||||
|
||||
@@ -17,8 +17,8 @@ Add persistent memory to [**OpenAI Codex**](https://openai.com/index/codex/) wit
|
||||
Before setting up Mem0 with Codex, ensure you have:
|
||||
|
||||
1. A Mem0 Platform account and API key:
|
||||
- [Sign up at app.mem0.ai](https://app.mem0.ai)
|
||||
- [Get your API key](https://app.mem0.ai/dashboard/api-keys) (starts with `m0-`)
|
||||
- <a href="https://app.mem0.ai" rel="nofollow">Sign up at app.mem0.ai</a>
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Get your API key</a> (starts with `m0-`)
|
||||
|
||||
2. OpenAI Codex access
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ pip install crewai crewai-tools mem0ai
|
||||
|
||||
Import required modules and set up configurations:
|
||||
|
||||
<Note>Remember to get your API keys from [Mem0 Platform](https://app.mem0.ai), [OpenAI](https://platform.openai.com) and [Serper Dev](https://serper.dev) for search capabilities.</Note>
|
||||
<Note>Remember to get your API keys from <a href="https://app.mem0.ai" rel="nofollow">Mem0 Platform</a>, [OpenAI](https://platform.openai.com) and [Serper Dev](https://serper.dev) for search capabilities.</Note>
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
@@ -17,8 +17,8 @@ Add persistent memory to [**Cursor**](https://cursor.com) with the Mem0 plugin.
|
||||
Before setting up Mem0 with Cursor, ensure you have:
|
||||
|
||||
1. A Mem0 Platform account and API key:
|
||||
- [Sign up at app.mem0.ai](https://app.mem0.ai)
|
||||
- [Get your API key](https://app.mem0.ai/dashboard/api-keys) (starts with `m0-`)
|
||||
- <a href="https://app.mem0.ai" rel="nofollow">Sign up at app.mem0.ai</a>
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Get your API key</a> (starts with `m0-`)
|
||||
|
||||
2. Cursor installed ([cursor.com](https://cursor.com))
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ npx flowise start
|
||||
|
||||
### 2. Obtain Your Mem0 API Key
|
||||
|
||||
1. Navigate to the [Mem0 API Key dashboard](https://app.mem0.ai/dashboard/api-keys).
|
||||
1. Navigate to the <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 API Key dashboard</a>.
|
||||
2. Generate or copy your existing Mem0 API Key.
|
||||
|
||||

|
||||
@@ -70,7 +70,7 @@ Test your memory configuration:
|
||||
|
||||
1. Save your Flowise configuration
|
||||
2. Run a test chat and store some information
|
||||
3. Verify the stored memories in the [Mem0 Dashboard](https://app.mem0.ai/dashboard/requests)
|
||||
3. Verify the stored memories in the <a href="https://app.mem0.ai/dashboard/requests" rel="nofollow">Mem0 Dashboard</a>
|
||||
|
||||

|
||||
|
||||
@@ -103,7 +103,7 @@ Available settings include:
|
||||
|
||||
### Platform Configuration
|
||||
|
||||
Additional settings available in [Mem0 Project Settings](https://app.mem0.ai/dashboard/project-settings):
|
||||
Additional settings available in <a href="https://app.mem0.ai/dashboard/project-settings" rel="nofollow">Mem0 Project Settings</a>:
|
||||
|
||||
1. **Custom Instructions**: Define memory extraction rules
|
||||
2. **Expiration Date**: Set automatic memory cleanup periods
|
||||
|
||||
@@ -22,7 +22,7 @@ pip install google-adk mem0ai python-dotenv
|
||||
```
|
||||
|
||||
2. Valid API keys:
|
||||
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys)
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 API Key</a>
|
||||
- Google AI Studio API Key
|
||||
|
||||
## Basic Integration Example
|
||||
|
||||
@@ -52,7 +52,7 @@ hermes memory setup
|
||||
|
||||
Select **mem0** as the provider and enter your Mem0 API key when prompted. The wizard writes your config to `~/.hermes/mem0.json`.
|
||||
|
||||
<Note>Get your API key from [app.mem0.ai](https://app.mem0.ai).</Note>
|
||||
<Note>Get your API key from <a href="https://app.mem0.ai" rel="nofollow">app.mem0.ai</a>.</Note>
|
||||
|
||||
### Option 2: Manual Configuration
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ Combining Mem0 with Keywords AI allows you to:
|
||||
4. Optimize token usage and reduce costs
|
||||
|
||||
<Note>
|
||||
You can get your Mem0 API key, user_id, and org_id from the [Mem0 dashboard](https://app.mem0.ai/). These are required for proper integration.
|
||||
You can get your Mem0 API key, user_id, and org_id from the <a href="https://app.mem0.ai/" rel="nofollow">Mem0 dashboard</a>. These are required for proper integration.
|
||||
</Note>
|
||||
|
||||
## Setup and Configuration
|
||||
|
||||
@@ -22,7 +22,7 @@ pip install langchain langchain_openai mem0ai python-dotenv
|
||||
|
||||
Import required modules and set up configurations:
|
||||
|
||||
<Note>Remember to get the Mem0 API key from [Mem0 Platform](https://app.mem0.ai).</Note>
|
||||
<Note>Remember to get the Mem0 API key from <a href="https://app.mem0.ai" rel="nofollow">Mem0 Platform</a>.</Note>
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
@@ -23,7 +23,7 @@ pip install langgraph langchain-openai mem0ai python-dotenv
|
||||
|
||||
Import required modules and set up configurations:
|
||||
|
||||
<Note>Remember to get the Mem0 API key from [Mem0 Platform](https://app.mem0.ai).</Note>
|
||||
<Note>Remember to get the Mem0 API key from <a href="https://app.mem0.ai" rel="nofollow">Mem0 Platform</a>.</Note>
|
||||
|
||||
```python
|
||||
from typing import Annotated, TypedDict, List
|
||||
|
||||
@@ -22,7 +22,7 @@ pip install llama-index-core llama-index-memory-mem0 python-dotenv
|
||||
Set your Mem0 Platform API key as an environment variable. You can replace `<your-mem0-api-key>` with your actual API key:
|
||||
|
||||
<Note type="info">
|
||||
You can obtain your Mem0 Platform API key from the [Mem0 Platform](https://app.mem0.ai/login).
|
||||
You can obtain your Mem0 Platform API key from the <a href="https://app.mem0.ai/login" rel="nofollow">Mem0 Platform</a>.
|
||||
</Note>
|
||||
|
||||
```python
|
||||
|
||||
@@ -23,7 +23,7 @@ npm install @mastra/core @mastra/mem0 @ai-sdk/openai zod
|
||||
|
||||
Set up your environment variables:
|
||||
|
||||
<Note>Remember to get the Mem0 API key from [Mem0 Platform](https://app.mem0.ai).</Note>
|
||||
<Note>Remember to get the Mem0 API key from <a href="https://app.mem0.ai" rel="nofollow">Mem0 Platform</a>.</Note>
|
||||
|
||||
```bash
|
||||
MEM0_API_KEY=your-mem0-api-key
|
||||
|
||||
@@ -22,7 +22,7 @@ pip install openai-agents mem0ai
|
||||
```
|
||||
|
||||
2. Valid API keys:
|
||||
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys)
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 API Key</a>
|
||||
- [OpenAI API Key](https://platform.openai.com/api-keys)
|
||||
|
||||
## Basic Integration Example
|
||||
|
||||
@@ -42,7 +42,7 @@ All memories are scoped to this `userId` — different values create separate me
|
||||
|
||||
### Platform Mode (Mem0 Cloud)
|
||||
|
||||
<Note>Get your API key from [app.mem0.ai](https://app.mem0.ai).</Note>
|
||||
<Note>Get your API key from <a href="https://app.mem0.ai" rel="nofollow">app.mem0.ai</a>.</Note>
|
||||
|
||||
Add to your `openclaw.json`:
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ Mem0 is a self-improving memory layer for LLM applications, enabling personalize
|
||||
|
||||
**Get your API Key**: You'll need a Mem0 API key to use this extension:
|
||||
|
||||
a. Sign up at [app.mem0.ai](https://app.mem0.ai)
|
||||
a. Sign up at <a href="https://app.mem0.ai" rel="nofollow">app.mem0.ai</a>
|
||||
|
||||
b. Navigate to your API Keys page
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ npm install @mem0/vercel-ai-provider
|
||||
|
||||
### Setting Up Mem0
|
||||
|
||||
1. Get your **Mem0 API Key** from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys).
|
||||
1. Get your **Mem0 API Key** from the <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">Mem0 Dashboard</a>.
|
||||
|
||||
2. Initialize the Mem0 Client in your application:
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ Move your Mem0 implementation to managed infrastructure with enterprise features
|
||||
|
||||
## Plan
|
||||
|
||||
1. **Sign up**: Create an account on [Mem0 Platform](https://app.mem0.ai).
|
||||
1. **Sign up**: Create an account on <a href="https://app.mem0.ai" rel="nofollow">Mem0 Platform</a>.
|
||||
2. **Get API Key**: Navigate to **Settings > API Keys** and generate a new key.
|
||||
3. **Review Usage**: Identify where you instantiate `Memory` and where you call `search` or `get_all`.
|
||||
|
||||
@@ -368,7 +368,7 @@ If you encounter issues, you can revert immediately by switching your import bac
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Platform Dashboard](https://app.mem0.ai) - Monitor usage and manage settings.
|
||||
- <a href="https://app.mem0.ai" rel="nofollow">Platform Dashboard</a> - Monitor usage and manage settings.
|
||||
- [Webhooks Setup](/platform/features/webhooks) - Configure real-time event notifications.
|
||||
- [Organizations & Projects](/api-reference/organizations-projects) - Set up multi-tenancy for your team.
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ estimatedTime: "~2 minutes"
|
||||
|
||||
<Info>
|
||||
**Prerequisites**
|
||||
- Mem0 Platform account ([Sign up here](https://app.mem0.ai))
|
||||
- API key ([Get one from dashboard](https://app.mem0.ai/settings/api-keys))
|
||||
- Mem0 Platform account (<a href="https://app.mem0.ai" rel="nofollow">Sign up here</a>)
|
||||
- API key (<a href="https://app.mem0.ai/settings/api-keys" rel="nofollow">Get one from dashboard</a>)
|
||||
- Node.js 14+ (for npx)
|
||||
- An MCP-compatible client (Claude, Claude Code, Cursor, Windsurf, VS Code, OpenCode)
|
||||
</Info>
|
||||
@@ -163,7 +163,7 @@ Agent: Updated your project status successfully.
|
||||
```
|
||||
|
||||
<Info icon="check">
|
||||
If you get "Connection failed", ensure you have a valid API key from [Mem0 Dashboard](https://app.mem0.ai/settings/api-keys).
|
||||
If you get "Connection failed", ensure you have a valid API key from <a href="https://app.mem0.ai/settings/api-keys" rel="nofollow">Mem0 Dashboard</a>.
|
||||
</Info>
|
||||
|
||||
---
|
||||
@@ -171,7 +171,7 @@ Agent: Updated your project status successfully.
|
||||
## Quick Recovery
|
||||
|
||||
- **"Connection refused"** → Check your internet connection and ensure the MCP client is correctly configured
|
||||
- **"Invalid API key"** → Get a new key from [Mem0 Dashboard](https://app.mem0.ai/settings/api-keys)
|
||||
- **"Invalid API key"** → Get a new key from <a href="https://app.mem0.ai/settings/api-keys" rel="nofollow">Mem0 Dashboard</a>
|
||||
- **"npx command not found"** → Install Node.js from [nodejs.org](https://nodejs.org)
|
||||
|
||||
---
|
||||
|
||||
@@ -64,7 +64,7 @@ Mem0 is the memory engine that keeps conversations contextual so users never rep
|
||||
<Card title="Connect Integrations" icon="plug" href="/integrations">
|
||||
LangChain, CrewAI, Vercel AI SDK.
|
||||
</Card>
|
||||
<Card title="Monitor in the Dashboard" icon="presentation" href="https://app.mem0.ai">
|
||||
<Card title="Monitor in the Dashboard" icon="presentation" href="https://app.mem0.ai/login">
|
||||
Track activity and manage workspaces.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -150,7 +150,7 @@ Mem0 offers two powerful ways to add memory to your AI applications. Choose base
|
||||
<Card
|
||||
title="Try Platform Free"
|
||||
icon="rocket"
|
||||
href="https://app.mem0.ai"
|
||||
href="https://app.mem0.ai/login"
|
||||
>
|
||||
Sign up and test the Platform with our free tier. No credit card required.
|
||||
</Card>
|
||||
|
||||
@@ -9,8 +9,8 @@ Get started with Mem0 Platform's hosted API in under 5 minutes. This guide shows
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Mem0 Platform account ([Sign up here](https://app.mem0.ai))
|
||||
- API key ([Get one from dashboard](https://app.mem0.ai/dashboard/settings?tab=api-keys&subtab=configuration))
|
||||
- Mem0 Platform account (<a href="https://app.mem0.ai" rel="nofollow">Sign up here</a>)
|
||||
- API key (<a href="https://app.mem0.ai/dashboard/settings?tab=api-keys&subtab=configuration" rel="nofollow">Get one from dashboard</a>)
|
||||
- Python 3.10+, Node.js 14+, or cURL
|
||||
|
||||
## Installation
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ We follow the llms.txt standard:
|
||||
- [llms.txt](https://docs.mem0.ai/llms.txt)
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Get an API Key" icon="key" href="https://app.mem0.ai">
|
||||
<Card title="Get an API Key" icon="key" href="https://app.mem0.ai/login">
|
||||
Sign up for Mem0 Platform and start building
|
||||
</Card>
|
||||
<Card title="Quickstart" icon="rocket" href="/platform/quickstart">
|
||||
@@ -34,7 +34,7 @@ Works with Claude Code, Cursor, Windsurf, and any assistant that supports skills
|
||||
|
||||
Connect Claude, Claude Code, Cursor, Windsurf, VS Code, OpenCode, or any MCP-compatible client to Mem0.
|
||||
|
||||
Get your API key from [app.mem0.ai](https://app.mem0.ai), then add Mem0 MCP with a single command:
|
||||
Get your API key from <a href="https://app.mem0.ai" rel="nofollow">app.mem0.ai</a>, then add Mem0 MCP with a single command:
|
||||
|
||||
```bash
|
||||
npx mcp-add \
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { OpenAILLM } from "./openai";
|
||||
import { LLMConfig, Message } from "../types";
|
||||
import { LLMResponse } from "./base";
|
||||
|
||||
export class DeepSeekLLM extends OpenAILLM {
|
||||
constructor(config: LLMConfig) {
|
||||
const apiKey = config.apiKey || process.env.DEEPSEEK_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error("DeepSeek API key is required");
|
||||
}
|
||||
super({
|
||||
...config,
|
||||
apiKey,
|
||||
baseURL:
|
||||
config.baseURL ||
|
||||
process.env.DEEPSEEK_API_BASE ||
|
||||
"https://api.deepseek.com",
|
||||
model: config.model || "deepseek-chat",
|
||||
});
|
||||
}
|
||||
|
||||
async generateResponse(
|
||||
messages: Message[],
|
||||
responseFormat?: { type: string },
|
||||
tools?: any[],
|
||||
): Promise<string | LLMResponse> {
|
||||
try {
|
||||
return await super.generateResponse(messages, responseFormat, tools);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`DeepSeek LLM failed: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async generateChat(messages: Message[]): Promise<LLMResponse> {
|
||||
try {
|
||||
return await super.generateChat(messages);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`DeepSeek LLM failed: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ import { LangchainEmbedder } from "../embeddings/langchain";
|
||||
import { LangchainVectorStore } from "../vector_stores/langchain";
|
||||
import { AzureAISearch } from "../vector_stores/azure_ai_search";
|
||||
import { PGVector } from "../vector_stores/pgvector";
|
||||
import { DeepSeekLLM } from "../llms/deepseek";
|
||||
|
||||
export class EmbedderFactory {
|
||||
static create(provider: string, config: EmbeddingConfig): Embedder {
|
||||
@@ -82,6 +83,8 @@ export class LLMFactory {
|
||||
return new MistralLLM(config);
|
||||
case "langchain":
|
||||
return new LangchainLLM(config);
|
||||
case "deepseek":
|
||||
return new DeepSeekLLM(config);
|
||||
default:
|
||||
throw new Error(`Unsupported LLM provider: ${provider}`);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,25 @@ try {
|
||||
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
|
||||
const POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
|
||||
|
||||
// Default sampling rate for hot-path OSS events. Lifecycle events always fire at 100%.
|
||||
// Override via MEM0_TELEMETRY_SAMPLE_RATE env var. Mirrors mem0/memory/telemetry.py.
|
||||
const DEFAULT_SAMPLE_RATE = 0.1;
|
||||
const MEM0_TELEMETRY_SAMPLE_RATE: number = ((): number => {
|
||||
try {
|
||||
const raw = process?.env?.MEM0_TELEMETRY_SAMPLE_RATE;
|
||||
if (raw !== undefined) {
|
||||
const parsed = Number(raw);
|
||||
if (Number.isFinite(parsed) && parsed >= 0 && parsed <= 1) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
return DEFAULT_SAMPLE_RATE;
|
||||
})();
|
||||
|
||||
// Events that bypass sampling. Keep in sync with _captureEvent call sites in memory/index.ts.
|
||||
const LIFECYCLE_EVENTS: ReadonlySet<string> = new Set(["init", "reset"]);
|
||||
|
||||
class UnifiedTelemetry implements TelemetryClient {
|
||||
private apiKey: string;
|
||||
private host: string;
|
||||
@@ -78,6 +97,12 @@ async function captureClientEvent(
|
||||
return;
|
||||
}
|
||||
|
||||
// >= so that rate=0 drops everything and rate=1 keeps everything (Math.random() ∈ [0, 1)).
|
||||
const isLifecycle = LIFECYCLE_EVENTS.has(eventName);
|
||||
if (!isLifecycle && Math.random() >= MEM0_TELEMETRY_SAMPLE_RATE) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventData: TelemetryEventData = {
|
||||
function: `${instance.constructor.name}`,
|
||||
method: eventName,
|
||||
@@ -86,6 +111,8 @@ async function captureClientEvent(
|
||||
client_version: version,
|
||||
client_source: "nodejs",
|
||||
...additionalData,
|
||||
// sample_rate set AFTER the spread so callers can never override it
|
||||
sample_rate: isLifecycle ? 1.0 : MEM0_TELEMETRY_SAMPLE_RATE,
|
||||
};
|
||||
|
||||
await telemetry.captureEvent(
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface TelemetryEventData {
|
||||
timestamp?: string;
|
||||
client_source: "browser" | "nodejs";
|
||||
client_version: string;
|
||||
/** Set by the sampling layer so PostHog dashboards can extrapolate via 1/sample_rate. */
|
||||
sample_rate?: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/// <reference types="jest" />
|
||||
/**
|
||||
* DeepSeek LLM — unit tests (mocked OpenAI).
|
||||
*/
|
||||
|
||||
import { DeepSeekLLM } from "../src/llms/deepseek";
|
||||
|
||||
const mockCreate = jest.fn();
|
||||
|
||||
jest.mock("openai", () => {
|
||||
return jest.fn().mockImplementation(() => ({
|
||||
chat: { completions: { create: mockCreate } },
|
||||
}));
|
||||
});
|
||||
|
||||
describe("DeepSeekLLM (unit)", () => {
|
||||
beforeEach(() => mockCreate.mockClear());
|
||||
|
||||
it("throws when no API key is provided", () => {
|
||||
const original = process.env.DEEPSEEK_API_KEY;
|
||||
delete process.env.DEEPSEEK_API_KEY;
|
||||
try {
|
||||
expect(() => new DeepSeekLLM({})).toThrow("DeepSeek API key is required");
|
||||
} finally {
|
||||
if (original !== undefined) process.env.DEEPSEEK_API_KEY = original;
|
||||
}
|
||||
});
|
||||
|
||||
it("generateResponse() returns a text response", async () => {
|
||||
mockCreate.mockResolvedValueOnce({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: "Hello, world!",
|
||||
role: "assistant",
|
||||
tool_calls: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const llm = new DeepSeekLLM({ apiKey: "test-key" });
|
||||
const result = await llm.generateResponse([
|
||||
{ role: "user", content: "Hi" },
|
||||
]);
|
||||
|
||||
expect(mockCreate).toHaveBeenCalledTimes(1);
|
||||
expect(result).toBe("Hello, world!");
|
||||
});
|
||||
|
||||
it("generateResponse() handles tool calls", async () => {
|
||||
mockCreate.mockResolvedValueOnce({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: "",
|
||||
role: "assistant",
|
||||
tool_calls: [
|
||||
{
|
||||
function: {
|
||||
name: "get_weather",
|
||||
arguments: '{"city": "London"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const llm = new DeepSeekLLM({ apiKey: "test-key" });
|
||||
const result = await llm.generateResponse(
|
||||
[{ role: "user", content: "What is the weather?" }],
|
||||
undefined,
|
||||
[{ type: "function", function: { name: "get_weather" } }],
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
content: "",
|
||||
role: "assistant",
|
||||
toolCalls: [{ name: "get_weather", arguments: '{"city": "London"}' }],
|
||||
});
|
||||
});
|
||||
|
||||
it("generateResponse() wraps API errors with a clear message", async () => {
|
||||
mockCreate.mockRejectedValueOnce(new Error("Connection refused"));
|
||||
|
||||
const llm = new DeepSeekLLM({ apiKey: "test-key" });
|
||||
|
||||
await expect(
|
||||
llm.generateResponse([{ role: "user", content: "Hi" }]),
|
||||
).rejects.toThrow("DeepSeek LLM failed: Connection refused");
|
||||
});
|
||||
|
||||
it("generateChat() returns LLMResponse shape", async () => {
|
||||
mockCreate.mockResolvedValueOnce({
|
||||
choices: [
|
||||
{
|
||||
message: { content: "I can help with that.", role: "assistant" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const llm = new DeepSeekLLM({ apiKey: "test-key" });
|
||||
const result = await llm.generateChat([
|
||||
{ role: "user", content: "Help me" },
|
||||
]);
|
||||
|
||||
expect(result).toEqual({
|
||||
content: "I can help with that.",
|
||||
role: "assistant",
|
||||
});
|
||||
});
|
||||
|
||||
it("generateChat() wraps API errors with a clear message", async () => {
|
||||
mockCreate.mockRejectedValueOnce(new Error("Timeout"));
|
||||
|
||||
const llm = new DeepSeekLLM({ apiKey: "test-key" });
|
||||
|
||||
await expect(
|
||||
llm.generateChat([{ role: "user", content: "Hi" }]),
|
||||
).rejects.toThrow("DeepSeek LLM failed: Timeout");
|
||||
});
|
||||
});
|
||||
@@ -87,6 +87,11 @@ jest.mock("../src/llms/lmstudio", () => ({
|
||||
.fn()
|
||||
.mockImplementation((config) => ({ type: "lmstudio-llm", config })),
|
||||
}));
|
||||
jest.mock("../src/llms/deepseek", () => ({
|
||||
DeepSeekLLM: jest
|
||||
.fn()
|
||||
.mockImplementation((config) => ({ type: "deepseek-llm", config })),
|
||||
}));
|
||||
|
||||
jest.mock("../src/vector_stores/qdrant", () => ({
|
||||
Qdrant: jest
|
||||
@@ -200,6 +205,7 @@ describe("LLMFactory", () => {
|
||||
["mistral"],
|
||||
["langchain"],
|
||||
["lmstudio"],
|
||||
["deepseek"],
|
||||
])("creates LLM for provider '%s'", (provider) => {
|
||||
expect(() => LLMFactory.create(provider, dummyLLMConfig)).not.toThrow();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
/// <reference types="jest" />
|
||||
/**
|
||||
* Telemetry sampling — unit tests.
|
||||
*
|
||||
* Sampling lives inside captureClientEvent in src/utils/telemetry.ts. It uses
|
||||
* Math.random() compared against MEM0_TELEMETRY_SAMPLE_RATE (default 0.1) to
|
||||
* drop hot-path events; lifecycle events ('init', 'reset') always fire.
|
||||
*
|
||||
* These tests target captureClientEvent directly. Existing OSS tests that mock
|
||||
* captureClientEvent (vector-stores-compat, dimension-autodetect, config-manager)
|
||||
* are unaffected because the function signature and contract are unchanged.
|
||||
*/
|
||||
|
||||
import type { TelemetryInstance } from "../src/utils/telemetry.types";
|
||||
|
||||
// Helper to make a fake TelemetryInstance.
|
||||
function makeInstance(
|
||||
overrides: Partial<TelemetryInstance> = {},
|
||||
): TelemetryInstance {
|
||||
return {
|
||||
telemetryId: "test-id",
|
||||
constructor: { name: "Memory" },
|
||||
host: "https://test.example.com",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("telemetry sampling", () => {
|
||||
let originalFetch: typeof global.fetch;
|
||||
let fetchMock: jest.Mock;
|
||||
let randomSpy: jest.SpyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
originalFetch = global.fetch;
|
||||
fetchMock = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
text: jest.fn().mockResolvedValue(""),
|
||||
});
|
||||
global.fetch = fetchMock as any;
|
||||
randomSpy = jest.spyOn(Math, "random");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
randomSpy.mockRestore();
|
||||
jest.resetModules();
|
||||
});
|
||||
|
||||
describe("lifecycle events always fire", () => {
|
||||
it("init event fires even at the highest random value", async () => {
|
||||
randomSpy.mockReturnValue(0.999);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("init", makeInstance());
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reset event fires even at the highest random value", async () => {
|
||||
randomSpy.mockReturnValue(0.999);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("reset", makeInstance());
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("init event payload has sample_rate: 1.0", async () => {
|
||||
randomSpy.mockReturnValue(0.999);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("init", makeInstance());
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.properties.sample_rate).toBe(1.0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hot-path events are sampled", () => {
|
||||
it("add event is dropped when random > sample_rate", async () => {
|
||||
randomSpy.mockReturnValue(0.99); // > 0.1 default rate
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("search event is dropped when random > sample_rate", async () => {
|
||||
randomSpy.mockReturnValue(0.99);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("search", makeInstance());
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("add event passes when random < sample_rate", async () => {
|
||||
randomSpy.mockReturnValue(0.05); // < 0.1 default rate
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("hot-path event payload has sample_rate: 0.1", async () => {
|
||||
randomSpy.mockReturnValue(0.05);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.properties.sample_rate).toBe(0.1);
|
||||
});
|
||||
|
||||
it("sample_rate cannot be overridden by additionalData", async () => {
|
||||
randomSpy.mockReturnValue(0.05);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance(), { sample_rate: 0.99 });
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.properties.sample_rate).toBe(0.1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("env var override", () => {
|
||||
afterEach(() => {
|
||||
delete process.env.MEM0_TELEMETRY_SAMPLE_RATE;
|
||||
});
|
||||
|
||||
it("rate 1.0 sends every event including hot-path at high random", async () => {
|
||||
process.env.MEM0_TELEMETRY_SAMPLE_RATE = "1.0";
|
||||
jest.resetModules();
|
||||
randomSpy.mockReturnValue(0.999);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
// 0.999 > 1.0 is false, so the gate never trips
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rate 0.0 drops every hot-path event including at random 0", async () => {
|
||||
// The gate is `random >= rate`, so rate=0 drops at random=0 (0 >= 0 is true).
|
||||
process.env.MEM0_TELEMETRY_SAMPLE_RATE = "0.0";
|
||||
jest.resetModules();
|
||||
randomSpy.mockReturnValue(0.0);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rate 0.0 drops at any random value", async () => {
|
||||
process.env.MEM0_TELEMETRY_SAMPLE_RATE = "0.0";
|
||||
jest.resetModules();
|
||||
randomSpy.mockReturnValue(0.5);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rate 0.0 still passes lifecycle events", async () => {
|
||||
process.env.MEM0_TELEMETRY_SAMPLE_RATE = "0.0";
|
||||
jest.resetModules();
|
||||
randomSpy.mockReturnValue(0.999);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("init", makeInstance());
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rate 0.5 passes events at random below 0.5", async () => {
|
||||
process.env.MEM0_TELEMETRY_SAMPLE_RATE = "0.5";
|
||||
jest.resetModules();
|
||||
randomSpy.mockReturnValue(0.3);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("invalid env var falls back to default rate", async () => {
|
||||
process.env.MEM0_TELEMETRY_SAMPLE_RATE = "not a number";
|
||||
jest.resetModules();
|
||||
randomSpy.mockReturnValue(0.05);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("out-of-range env var (negative) falls back to default rate", async () => {
|
||||
process.env.MEM0_TELEMETRY_SAMPLE_RATE = "-0.5";
|
||||
jest.resetModules();
|
||||
randomSpy.mockReturnValue(0.05);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("out-of-range env var (> 1) falls back to default rate", async () => {
|
||||
process.env.MEM0_TELEMETRY_SAMPLE_RATE = "5";
|
||||
jest.resetModules();
|
||||
randomSpy.mockReturnValue(0.05);
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance());
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("contract preservation", () => {
|
||||
it("lifecycle event includes additionalData", async () => {
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("init", makeInstance(), {
|
||||
api_version: "v1.1",
|
||||
client_type: "Memory",
|
||||
});
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.properties.api_version).toBe("v1.1");
|
||||
expect(body.properties.client_type).toBe("Memory");
|
||||
expect(body.properties.sample_rate).toBe(1.0);
|
||||
});
|
||||
|
||||
it("captureClientEvent without telemetryId is a no-op", async () => {
|
||||
const { captureClientEvent } = await import("../src/utils/telemetry");
|
||||
await captureClientEvent("add", makeInstance({ telemetryId: "" }));
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import atexit
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import random
|
||||
import sys
|
||||
import threading
|
||||
|
||||
@@ -22,16 +23,65 @@ if not isinstance(MEM0_TELEMETRY, bool):
|
||||
|
||||
logging.getLogger("posthog").setLevel(logging.CRITICAL + 1)
|
||||
logging.getLogger("urllib3").setLevel(logging.CRITICAL + 1)
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Default sampling rate for hot-path OSS events. Lifecycle events always fire at 100%.
|
||||
# Override via MEM0_TELEMETRY_SAMPLE_RATE env var.
|
||||
_DEFAULT_SAMPLE_RATE = 0.1
|
||||
|
||||
|
||||
def _parse_sample_rate(raw):
|
||||
"""Parse MEM0_TELEMETRY_SAMPLE_RATE env var. Never raises."""
|
||||
try:
|
||||
value = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
_logger.debug("MEM0_TELEMETRY_SAMPLE_RATE %r is not a number, defaulting to %s", raw, _DEFAULT_SAMPLE_RATE)
|
||||
return _DEFAULT_SAMPLE_RATE
|
||||
if not 0.0 <= value <= 1.0:
|
||||
_logger.debug("MEM0_TELEMETRY_SAMPLE_RATE %s out of [0.0, 1.0], defaulting to %s", value, _DEFAULT_SAMPLE_RATE)
|
||||
return _DEFAULT_SAMPLE_RATE
|
||||
return value
|
||||
|
||||
|
||||
MEM0_TELEMETRY_SAMPLE_RATE = _parse_sample_rate(os.environ.get("MEM0_TELEMETRY_SAMPLE_RATE", str(_DEFAULT_SAMPLE_RATE)))
|
||||
|
||||
# Events that bypass sampling and always fire. Keep this set in sync with the
|
||||
# event names passed to capture_event() in mem0/memory/main.py.
|
||||
_LIFECYCLE_EVENTS = frozenset({"mem0.init", "mem0.reset", "mem0._create_procedural_memory"})
|
||||
|
||||
|
||||
def _sampling_before_send(msg):
|
||||
"""PostHog before_send hook: drop sampled hot-path events, annotate survivors with sample_rate."""
|
||||
if not isinstance(msg, dict):
|
||||
return None
|
||||
|
||||
event_name = msg.get("event", "")
|
||||
is_lifecycle = event_name in _LIFECYCLE_EVENTS
|
||||
|
||||
# >= so that rate=0 drops everything and rate=1 keeps everything (random ∈ [0, 1)).
|
||||
if not is_lifecycle and random.random() >= MEM0_TELEMETRY_SAMPLE_RATE:
|
||||
return None
|
||||
|
||||
# Annotate so PostHog dashboards can extrapolate true counts via 1/sample_rate.
|
||||
properties = msg.setdefault("properties", {})
|
||||
properties["sample_rate"] = 1.0 if is_lifecycle else MEM0_TELEMETRY_SAMPLE_RATE
|
||||
return msg
|
||||
|
||||
|
||||
class AnonymousTelemetry:
|
||||
def __init__(self, vector_store=None):
|
||||
def __init__(self, vector_store=None, before_send=None):
|
||||
if not MEM0_TELEMETRY:
|
||||
self.posthog = None
|
||||
self.user_id = None
|
||||
return
|
||||
|
||||
self.posthog = Posthog(project_api_key=PROJECT_API_KEY, host=HOST)
|
||||
try:
|
||||
self.posthog = Posthog(project_api_key=PROJECT_API_KEY, host=HOST, before_send=before_send)
|
||||
except TypeError:
|
||||
# posthog <4.5.0 does not accept before_send; fall back without sampling.
|
||||
_logger.debug("posthog.Posthog does not accept before_send; upgrade to >=4.5.0 for sampling")
|
||||
self.posthog = Posthog(project_api_key=PROJECT_API_KEY, host=HOST)
|
||||
self.user_id = get_or_create_user_id(vector_store)
|
||||
|
||||
def capture_event(self, event_name, properties=None, user_email=None):
|
||||
@@ -87,7 +137,7 @@ def _get_oss_telemetry():
|
||||
# Double-checked locking
|
||||
if _oss_telemetry_instance is not None:
|
||||
return _oss_telemetry_instance
|
||||
_oss_telemetry_instance = AnonymousTelemetry()
|
||||
_oss_telemetry_instance = AnonymousTelemetry(before_send=_sampling_before_send)
|
||||
atexit.register(_shutdown_oss_telemetry)
|
||||
return _oss_telemetry_instance
|
||||
|
||||
@@ -102,6 +152,7 @@ def _shutdown_oss_telemetry():
|
||||
|
||||
|
||||
# Module-level client telemetry singleton (used by capture_client_event).
|
||||
# No before_send — hosted MemoryClient traffic must never be sampled.
|
||||
client_telemetry = AnonymousTelemetry()
|
||||
atexit.register(client_telemetry.close)
|
||||
|
||||
|
||||
@@ -149,9 +149,6 @@ openclaw mem0 dream --dry-run
|
||||
| Key | Type | Default | Description |
|
||||
| --- | ---- | ------- | ----------- |
|
||||
| `apiKey` | `string` | — | **Required.** Mem0 API key (supports `${MEM0_API_KEY}`) |
|
||||
| `orgId` | `string` | — | Organization ID |
|
||||
| `projectId` | `string` | — | Project ID |
|
||||
| `enableGraph` | `boolean` | `false` | Entity graph for relationship tracking |
|
||||
| `customInstructions` | `string` | *(built-in)* | Custom extraction rules |
|
||||
| `customCategories` | `object` | *(12 defaults)* | Category name to description map |
|
||||
|
||||
@@ -169,7 +166,6 @@ All fields optional. Defaults: `text-embedding-3-small` embeddings, local SQLite
|
||||
| `oss.llm.provider` | `string` | `"openai"` | LLM provider |
|
||||
| `oss.llm.config` | `object` | — | Provider config (`apiKey`, `model`, `baseURL`) |
|
||||
| `oss.historyDbPath` | `string` | — | SQLite path for edit history |
|
||||
| `oss.disableHistory` | `boolean` | `false` | Skip history DB |
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -621,7 +621,6 @@ export function registerCliCommands(
|
||||
runId?: string,
|
||||
): SearchOptions => {
|
||||
const base = buildSearchOptions(userIdOverride, lim, runId);
|
||||
delete (base as any).source;
|
||||
base.threshold = 0.3;
|
||||
return base;
|
||||
};
|
||||
@@ -718,7 +717,7 @@ export function registerCliCommands(
|
||||
: effectiveUserId(getCurrentSessionId());
|
||||
const result = await provider.add(
|
||||
[{ role: "user", content: text }],
|
||||
{ user_id: uid },
|
||||
{ user_id: uid, source: "OPENCLAW" },
|
||||
);
|
||||
const count = result.results?.length ?? 0;
|
||||
if (count > 0) {
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface PluginAuthConfig {
|
||||
autoRecall?: boolean;
|
||||
autoCapture?: boolean;
|
||||
topK?: number;
|
||||
anonymousTelemetryId?: string;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -78,6 +79,7 @@ export function readPluginAuth(): PluginAuthConfig {
|
||||
autoRecall: cfg.autoRecall as boolean | undefined,
|
||||
autoCapture: cfg.autoCapture as boolean | undefined,
|
||||
topK: cfg.topK as number | undefined,
|
||||
anonymousTelemetryId: cfg.anonymousTelemetryId as string | undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+11
-20
@@ -140,7 +140,7 @@ const memoryPlugin = definePluginEntry({
|
||||
(id: string) => `${cfg.userId}:agent:${id}`,
|
||||
() => ({ user_id: cfg.userId, top_k: cfg.topK }),
|
||||
() => undefined,
|
||||
(cmd: string) => _captureEvent(`openclaw.${cmd}`, { command: cmd }),
|
||||
(cmd: string) => _captureEvent(`openclaw.cli.${cmd}`, { command: cmd }),
|
||||
);
|
||||
|
||||
api.registerService({
|
||||
@@ -367,16 +367,11 @@ function registerHooks(
|
||||
}
|
||||
|
||||
const promptLower = event.prompt.toLowerCase();
|
||||
const isChannelSystemEvent = /^system(?:\s*\(untrusted\))?:\s*\[/i.test(
|
||||
event.prompt,
|
||||
);
|
||||
const isSystemPrompt =
|
||||
!isChannelSystemEvent &&
|
||||
(promptLower.includes("a new session was started") ||
|
||||
promptLower.includes("session startup sequence") ||
|
||||
promptLower.includes("/new or /reset") ||
|
||||
promptLower.startsWith("system:") ||
|
||||
promptLower.startsWith("run your session"));
|
||||
promptLower.includes("a new session was started") ||
|
||||
promptLower.includes("session startup sequence") ||
|
||||
promptLower.includes("/new or /reset") ||
|
||||
promptLower.startsWith("run your session");
|
||||
if (isSystemPrompt) {
|
||||
api.logger.info(
|
||||
"openclaw-mem0: skills-mode skipping recall for system/bootstrap prompt",
|
||||
@@ -618,16 +613,11 @@ function registerHooks(
|
||||
}
|
||||
|
||||
const promptLower = event.prompt.toLowerCase();
|
||||
const isChannelSystemEvent = /^system(?:\s*\(untrusted\))?:\s*\[/i.test(
|
||||
event.prompt,
|
||||
);
|
||||
const isSystemPrompt =
|
||||
!isChannelSystemEvent &&
|
||||
(promptLower.includes("a new session was started") ||
|
||||
promptLower.includes("session startup sequence") ||
|
||||
promptLower.includes("/new or /reset") ||
|
||||
promptLower.startsWith("system:") ||
|
||||
promptLower.startsWith("run your session"));
|
||||
promptLower.includes("a new session was started") ||
|
||||
promptLower.includes("session startup sequence") ||
|
||||
promptLower.includes("/new or /reset") ||
|
||||
promptLower.startsWith("run your session");
|
||||
if (isSystemPrompt) {
|
||||
api.logger.info(
|
||||
"openclaw-mem0: skipping recall for system/bootstrap prompt",
|
||||
@@ -806,7 +796,8 @@ function registerHooks(
|
||||
return false;
|
||||
return msg.content.some(
|
||||
(block: any) =>
|
||||
block?.type === "tool_use" && MEMORY_MUTATE_TOOLS.has(block.name),
|
||||
(block?.type === "tool_use" || block?.type === "toolCall") &&
|
||||
MEMORY_MUTATE_TOOLS.has(block.name),
|
||||
);
|
||||
});
|
||||
if (agentUsedMemoryTool) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "openclaw-mem0",
|
||||
"name": "Memory (Mem0)",
|
||||
"description": "Mem0 memory backend for OpenClaw — platform or self-hosted open-source",
|
||||
"description": "Mem0 memory backend for OpenClaw — platform or self-hosted open-source. Injects recalled memories into agent context (auto-recall) and extracts facts after each turn (auto-capture). Both configurable via autoRecall/autoCapture settings.",
|
||||
"version": "1.0.5",
|
||||
"kind": "memory",
|
||||
"skills": ["skills"],
|
||||
@@ -13,9 +13,23 @@
|
||||
},
|
||||
"providerAuthEnvVars": {
|
||||
"mem0": ["MEM0_API_KEY"],
|
||||
"mem0-oss-openai": ["OPENAI_API_KEY"],
|
||||
"mem0-oss-anthropic": ["ANTHROPIC_API_KEY"]
|
||||
"openclaw-mem0-oss": ["OPENAI_API_KEY"]
|
||||
},
|
||||
"providerAuthChoices": [
|
||||
{
|
||||
"provider": "mem0",
|
||||
"method": "api-key",
|
||||
"choiceId": "mem0-api-key",
|
||||
"choiceLabel": "Mem0 API key",
|
||||
"choiceHint": "Required for platform mode. Get your key at https://app.mem0.ai/dashboard/api-keys",
|
||||
"groupId": "mem0",
|
||||
"groupLabel": "Mem0",
|
||||
"optionKey": "apiKey",
|
||||
"cliFlag": "--mem0-api-key",
|
||||
"cliOption": "--mem0-api-key <key>",
|
||||
"cliDescription": "Mem0 platform API key"
|
||||
}
|
||||
],
|
||||
"uiHints": {
|
||||
"mode": {
|
||||
"label": "Mode",
|
||||
@@ -32,16 +46,6 @@
|
||||
"placeholder": "default",
|
||||
"help": "User ID for scoping memories"
|
||||
},
|
||||
"orgId": {
|
||||
"label": "Organization ID",
|
||||
"placeholder": "org-...",
|
||||
"advanced": true
|
||||
},
|
||||
"projectId": {
|
||||
"label": "Project ID",
|
||||
"placeholder": "proj-...",
|
||||
"advanced": true
|
||||
},
|
||||
"autoCapture": {
|
||||
"label": "Auto-Capture",
|
||||
"help": "Automatically store conversation context after each agent turn"
|
||||
@@ -65,10 +69,6 @@
|
||||
"advanced": true,
|
||||
"help": "Custom prompt for open-source mode memory extraction."
|
||||
},
|
||||
"enableGraph": {
|
||||
"label": "Enable Graph Memory",
|
||||
"help": "Enable Mem0 graph memory for entity relationships (platform mode only)"
|
||||
},
|
||||
"searchThreshold": {
|
||||
"label": "Search Threshold",
|
||||
"placeholder": "0.5",
|
||||
@@ -110,12 +110,6 @@
|
||||
"userEmail": {
|
||||
"type": "string"
|
||||
},
|
||||
"orgId": {
|
||||
"type": "string"
|
||||
},
|
||||
"projectId": {
|
||||
"type": "string"
|
||||
},
|
||||
"autoCapture": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -134,9 +128,6 @@
|
||||
"customPrompt": {
|
||||
"type": "string"
|
||||
},
|
||||
"enableGraph": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"searchThreshold": {
|
||||
"type": "number"
|
||||
},
|
||||
@@ -192,7 +183,6 @@
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean" },
|
||||
"importanceThreshold": { "type": "number" },
|
||||
"enableGraph": { "type": "boolean" },
|
||||
"credentialPatterns": { "type": "array", "items": { "type": "string" } }
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@mem0/openclaw-mem0",
|
||||
"version": "1.0.5",
|
||||
"version": "1.0.6",
|
||||
"type": "module",
|
||||
"description": "Mem0 memory backend for OpenClaw — platform or self-hosted open-source",
|
||||
"license": "Apache-2.0",
|
||||
@@ -42,8 +42,8 @@
|
||||
"./dist/index.js"
|
||||
],
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.3.28 <=2026.4.2",
|
||||
"minGatewayVersion": "2026.3.28"
|
||||
"pluginApi": ">=2026.3.28",
|
||||
"minGatewayVersion": ">=2026.3.28"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.4.1",
|
||||
|
||||
@@ -506,6 +506,7 @@ export function providerToBackend(
|
||||
msgs as Array<{ role: string; content: string }>,
|
||||
{
|
||||
user_id: opts.userId ?? userId,
|
||||
source: "OPENCLAW",
|
||||
...(opts.runId && { run_id: opts.runId }),
|
||||
...(opts.metadata && { metadata: opts.metadata }),
|
||||
...(opts.immutable && { immutable: true }),
|
||||
@@ -524,6 +525,7 @@ export function providerToBackend(
|
||||
keyword_search: opts.keyword,
|
||||
reranking: opts.rerank,
|
||||
filters: opts.filters,
|
||||
source: "OPENCLAW",
|
||||
});
|
||||
return results as unknown as Record<string, unknown>[];
|
||||
},
|
||||
@@ -537,6 +539,7 @@ export function providerToBackend(
|
||||
const items = await provider.getAll({
|
||||
user_id: opts.userId ?? userId,
|
||||
page_size: opts.pageSize,
|
||||
source: "OPENCLAW",
|
||||
});
|
||||
return items as unknown as Record<string, unknown>[];
|
||||
},
|
||||
|
||||
@@ -260,6 +260,7 @@ export async function recall(
|
||||
threshold,
|
||||
keyword_search: recallConfig.keywordSearch !== false, // Default on
|
||||
reranking: recallConfig.rerank !== false, // Default on
|
||||
source: "OPENCLAW",
|
||||
};
|
||||
if (recallConfig.filterMemories) {
|
||||
searchOpts.filter_memories = true;
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
---
|
||||
name: memory-triage
|
||||
description: >
|
||||
ALWAYS USE THIS SKILL. Persistent long-term memory protocol powered by mem0.
|
||||
After EVERY response, evaluate the conversation for durable facts worth storing
|
||||
via memory_add. Handles identity, preferences, decisions, configurations, rules,
|
||||
projects, and relationships. Use memory_add (NOT workspace files) for all user facts.
|
||||
Read this skill at the start of every session.
|
||||
Persistent long-term memory protocol powered by mem0.
|
||||
Evaluate conversations for durable facts worth storing via memory_add.
|
||||
Handles identity, preferences, decisions, configurations, rules,
|
||||
projects, and relationships. Loaded by the openclaw-mem0 plugin when skills mode is active.
|
||||
user-invocable: false
|
||||
metadata:
|
||||
{"openclaw": {"always": true, "emoji": "🧠", "requires": {"env": ["MEM0_API_KEY"], "bins": []}}}
|
||||
{"openclaw": {"always": false, "emoji": "🧠", "requires": {"env": ["MEM0_API_KEY"], "bins": []}}}
|
||||
---
|
||||
|
||||
# Memory Protocol
|
||||
|
||||
+186
-5
@@ -8,10 +8,10 @@
|
||||
* Disable with: MEM0_TELEMETRY=false
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { readPluginAuth } from "./cli/config-file.ts";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { readPluginAuth, writePluginAuth, getBaseUrl } from "./cli/config-file.ts";
|
||||
|
||||
export const PLUGIN_VERSION = "1.0.4";
|
||||
export const PLUGIN_VERSION = "1.0.6";
|
||||
|
||||
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
|
||||
const POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
|
||||
@@ -22,6 +22,133 @@ const FLUSH_THRESHOLD = 10;
|
||||
let eventQueue: Record<string, unknown>[] = [];
|
||||
let flushTimer: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
let _cachedAnonymousId: string | undefined;
|
||||
let _aliasCheckDone = false;
|
||||
|
||||
/**
|
||||
* Return a persistent per-machine anonymous ID, generating one if needed.
|
||||
*
|
||||
* Stored in ~/.openclaw/openclaw.json under the plugin's `anonymousTelemetryId`
|
||||
* field so repeat sessions on the same machine share one PostHog identity
|
||||
* instead of collapsing into a single shared fallback string. The result is
|
||||
* cached in module memory after the first read so we don't re-touch disk on
|
||||
* every queued event.
|
||||
*/
|
||||
function getOrCreateAnonymousId(): string {
|
||||
if (_cachedAnonymousId) return _cachedAnonymousId;
|
||||
try {
|
||||
const auth = readPluginAuth();
|
||||
if (auth.anonymousTelemetryId) {
|
||||
_cachedAnonymousId = auth.anonymousTelemetryId;
|
||||
return _cachedAnonymousId;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
const newId = `openclaw-anon-${randomUUID().replace(/-/g, "")}`;
|
||||
try {
|
||||
writePluginAuth({ anonymousTelemetryId: newId });
|
||||
} catch {
|
||||
/* ignore — return generated id anyway */
|
||||
}
|
||||
_cachedAnonymousId = newId;
|
||||
return newId;
|
||||
}
|
||||
|
||||
/**
|
||||
* If we just resolved to a real identity but a stored anonymous id exists,
|
||||
* build a one-shot PostHog $identify event so the pre-signup history gets
|
||||
* stitched onto the authenticated profile. Returns null when no aliasing is
|
||||
* needed (already done, or no anon id on disk, or still anonymous).
|
||||
*
|
||||
* Caller is responsible for pushing the returned event onto eventQueue ahead
|
||||
* of the regular event.
|
||||
*/
|
||||
function maybeBuildIdentifyEvent(
|
||||
distinctId: string,
|
||||
): Record<string, unknown> | null {
|
||||
if (_aliasCheckDone) return null;
|
||||
if (!distinctId || distinctId.startsWith("openclaw-anon-")) return null;
|
||||
try {
|
||||
const auth = readPluginAuth();
|
||||
const storedAnon = auth.anonymousTelemetryId;
|
||||
if (!storedAnon) {
|
||||
_aliasCheckDone = true;
|
||||
return null;
|
||||
}
|
||||
const identifyEvent = {
|
||||
event: "$identify",
|
||||
distinct_id: distinctId,
|
||||
properties: {
|
||||
$anon_distinct_id: storedAnon,
|
||||
$lib: "posthog-node",
|
||||
},
|
||||
};
|
||||
try {
|
||||
writePluginAuth({ anonymousTelemetryId: "" });
|
||||
} catch {
|
||||
/* ignore — alias may double-fire next session, harmless */
|
||||
}
|
||||
_aliasCheckDone = true;
|
||||
_cachedAnonymousId = undefined;
|
||||
return identifyEvent;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let _emailResolutionAttempted = false;
|
||||
|
||||
/**
|
||||
* If we have an apiKey but no cached userEmail, do a one-shot /v1/ping/
|
||||
* call to resolve the email and cache it. This runs async as a side-effect;
|
||||
* the current event ships with md5(apiKey) but subsequent events (including
|
||||
* those flushed by the beforeExit handler in the same process) will use
|
||||
* the resolved email.
|
||||
*/
|
||||
function maybeResolveEmail(apiKey: string): void {
|
||||
if (_emailResolutionAttempted) return;
|
||||
_emailResolutionAttempted = true;
|
||||
|
||||
const baseUrl = getBaseUrl().replace(/\/+$/, "");
|
||||
fetch(`${baseUrl}/v1/ping/`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Token ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((data: any) => {
|
||||
const email = data?.user_email;
|
||||
if (email) {
|
||||
try {
|
||||
writePluginAuth({ userEmail: email });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
// Upgrade any already-queued events from md5(apiKey) to email
|
||||
const oldId = createHash("md5").update(apiKey).digest("hex");
|
||||
for (const ev of eventQueue) {
|
||||
if (ev.distinct_id === oldId) {
|
||||
ev.distinct_id = email;
|
||||
}
|
||||
// Also upgrade $identify's distinct_id if present
|
||||
if (
|
||||
ev.event === "$identify" &&
|
||||
ev.distinct_id === oldId
|
||||
) {
|
||||
ev.distinct_id = email;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
/* silently swallow — md5(apiKey) is used as fallback */
|
||||
});
|
||||
}
|
||||
|
||||
let _telemetryEnabled: boolean | undefined;
|
||||
function isTelemetryEnabled(): boolean {
|
||||
if (_telemetryEnabled !== undefined) return _telemetryEnabled;
|
||||
@@ -42,7 +169,8 @@ function isTelemetryEnabled(): boolean {
|
||||
/**
|
||||
* Return a stable anonymous identifier for the current user.
|
||||
*
|
||||
* Priority: cached userEmail (from /v1/ping/) > MD5(apiKey) > fallback.
|
||||
* Priority: cached userEmail (from /v1/ping/) > MD5(apiKey) >
|
||||
* persistent per-machine anonymous ID.
|
||||
*/
|
||||
function getDistinctId(apiKey?: string): string {
|
||||
try {
|
||||
@@ -54,7 +182,7 @@ function getDistinctId(apiKey?: string): string {
|
||||
if (apiKey) {
|
||||
return createHash("md5").update(apiKey).digest("hex");
|
||||
}
|
||||
return "anonymous-openclaw";
|
||||
return getOrCreateAnonymousId();
|
||||
}
|
||||
|
||||
function ensureFlushTimer(): void {
|
||||
@@ -65,6 +193,42 @@ function ensureFlushTimer(): void {
|
||||
}
|
||||
}
|
||||
|
||||
let _exitHandlerInstalled = false;
|
||||
|
||||
/**
|
||||
* Install a one-time `beforeExit` handler that drains queued events on
|
||||
* process exit. Without this, short-lived CLI invocations (e.g. one
|
||||
* `openclaw mem0 status` call) exit before the unref'd flushTimer fires
|
||||
* and before FLUSH_THRESHOLD is hit, dropping every queued event silently.
|
||||
*
|
||||
* Returning a Promise from a `beforeExit` handler keeps the event loop
|
||||
* alive until that Promise resolves, so the awaited fetch actually has
|
||||
* time to land at PostHog.
|
||||
*/
|
||||
function ensureExitHandler(): void {
|
||||
if (_exitHandlerInstalled) return;
|
||||
_exitHandlerInstalled = true;
|
||||
process.on("beforeExit", async () => {
|
||||
if (eventQueue.length === 0) return;
|
||||
const batch = eventQueue;
|
||||
eventQueue = [];
|
||||
const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch });
|
||||
try {
|
||||
await fetch(POSTHOG_HOST, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": String(Buffer.byteLength(body)),
|
||||
},
|
||||
body,
|
||||
signal: AbortSignal.timeout(3_000),
|
||||
});
|
||||
} catch {
|
||||
/* silently swallow */
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function flushEvents(): void {
|
||||
if (eventQueue.length === 0) return;
|
||||
const batch = eventQueue;
|
||||
@@ -97,6 +261,22 @@ export function captureEvent(
|
||||
try {
|
||||
const distinctId = getDistinctId(ctx?.apiKey);
|
||||
|
||||
// If we resolved to md5(apiKey) instead of email, kick off a background
|
||||
// /v1/ping/ to resolve and cache the email. The current event ships with
|
||||
// the hash, but the async resolution upgrades any still-queued events
|
||||
// (including this one) before the beforeExit flush fires.
|
||||
if (ctx?.apiKey && distinctId && !distinctId.includes("@") && !distinctId.startsWith("openclaw-anon-")) {
|
||||
maybeResolveEmail(ctx.apiKey);
|
||||
}
|
||||
|
||||
// First authenticated event after a previous anonymous session: queue a
|
||||
// $identify ahead of the regular event so PostHog merges the anonymous
|
||||
// history onto the authenticated profile in the same batch flush.
|
||||
const identifyEvent = maybeBuildIdentifyEvent(distinctId);
|
||||
if (identifyEvent) {
|
||||
eventQueue.push(identifyEvent);
|
||||
}
|
||||
|
||||
eventQueue.push({
|
||||
event: eventName,
|
||||
distinct_id: distinctId,
|
||||
@@ -115,6 +295,7 @@ export function captureEvent(
|
||||
});
|
||||
|
||||
ensureFlushTimer();
|
||||
ensureExitHandler();
|
||||
|
||||
if (eventQueue.length >= FLUSH_THRESHOLD) {
|
||||
flushEvents();
|
||||
|
||||
@@ -61,6 +61,7 @@ describe("providerToBackend — search", () => {
|
||||
keyword_search: true,
|
||||
reranking: true,
|
||||
filters: { category: "preference" },
|
||||
source: "OPENCLAW",
|
||||
});
|
||||
expect(results).toHaveLength(1);
|
||||
expect((results[0] as any).id).toBe("m1");
|
||||
@@ -79,6 +80,7 @@ describe("providerToBackend — search", () => {
|
||||
keyword_search: undefined,
|
||||
reranking: undefined,
|
||||
filters: undefined,
|
||||
source: "OPENCLAW",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -173,6 +175,7 @@ describe("providerToBackend — listMemories", () => {
|
||||
expect(provider.getAll).toHaveBeenCalledWith({
|
||||
user_id: DEFAULT_USER,
|
||||
page_size: 50,
|
||||
source: "OPENCLAW",
|
||||
});
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
@@ -186,6 +189,7 @@ describe("providerToBackend — listMemories", () => {
|
||||
expect(provider.getAll).toHaveBeenCalledWith({
|
||||
user_id: DEFAULT_USER,
|
||||
page_size: undefined,
|
||||
source: "OPENCLAW",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,7 +24,7 @@ describe("telemetry", () => {
|
||||
});
|
||||
|
||||
it("exports PLUGIN_VERSION", () => {
|
||||
expect(PLUGIN_VERSION).toBe("1.0.4");
|
||||
expect(PLUGIN_VERSION).toBe("1.0.6");
|
||||
});
|
||||
|
||||
it("captureEvent does not throw", () => {
|
||||
@@ -51,7 +51,7 @@ describe("telemetry", () => {
|
||||
expect(() => captureEvent("test_event")).not.toThrow();
|
||||
});
|
||||
|
||||
it("falls back to anonymous-openclaw when no apiKey", () => {
|
||||
it("falls back to a generated anonymous id when no apiKey", () => {
|
||||
(readPluginAuth as ReturnType<typeof vi.fn>).mockReturnValueOnce({});
|
||||
expect(() => captureEvent("test_event", {}, {})).not.toThrow();
|
||||
});
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ dependencies = [
|
||||
"qdrant-client>=1.9.1",
|
||||
"pydantic>=2.7.3",
|
||||
"openai>=1.90.0",
|
||||
"posthog>=3.5.0",
|
||||
"posthog>=4.5.0",
|
||||
"pytz>=2024.1",
|
||||
"sqlalchemy>=2.0.31",
|
||||
"protobuf>=5.29.6,<7.0.0",
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Tests for OSS telemetry sampling.
|
||||
|
||||
Tests target _sampling_before_send and its wiring directly. Existing tests in
|
||||
test_telemetry.py cover opt-out, singleton, and lifecycle behavior and are
|
||||
unaffected by sampling.
|
||||
"""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
import mem0.memory.telemetry as telemetry_module
|
||||
|
||||
|
||||
class TestParseSampleRate:
|
||||
"""Verify the env var parsing helper. Must never raise."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw,expected",
|
||||
[
|
||||
("0.0", 0.0),
|
||||
("0.1", 0.1),
|
||||
("0.5", 0.5),
|
||||
("1.0", 1.0),
|
||||
("0.05", 0.05),
|
||||
],
|
||||
)
|
||||
def test_valid_values(self, raw, expected):
|
||||
assert telemetry_module._parse_sample_rate(raw) == expected
|
||||
|
||||
@pytest.mark.parametrize("raw", ["abc", "", "5.0", "-1", "-0.5", "1.5", "2", "nan"])
|
||||
def test_invalid_values_fall_back_to_default(self, raw):
|
||||
assert telemetry_module._parse_sample_rate(raw) == telemetry_module._DEFAULT_SAMPLE_RATE
|
||||
|
||||
def test_none_falls_back(self):
|
||||
assert telemetry_module._parse_sample_rate(None) == telemetry_module._DEFAULT_SAMPLE_RATE
|
||||
|
||||
|
||||
class TestSamplingBeforeSend:
|
||||
"""Verify _sampling_before_send: the PostHog hook that drops/keeps events."""
|
||||
|
||||
def _msg(self, event_name, properties=None):
|
||||
return {"event": event_name, "properties": properties or {}}
|
||||
|
||||
def test_lifecycle_event_passes_through_at_high_random(self):
|
||||
"""Lifecycle events always fire even when random is near 1.0."""
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.999):
|
||||
for event in ("mem0.init", "mem0.reset", "mem0._create_procedural_memory"):
|
||||
result = telemetry_module._sampling_before_send(self._msg(event))
|
||||
assert result is not None
|
||||
assert result["properties"]["sample_rate"] == 1.0
|
||||
|
||||
def test_hot_path_event_dropped_when_random_above_rate(self):
|
||||
"""At default rate 0.1, random=0.99 should drop the event."""
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY_SAMPLE_RATE", 0.1):
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.99):
|
||||
assert telemetry_module._sampling_before_send(self._msg("mem0.add")) is None
|
||||
|
||||
def test_hot_path_event_passes_when_random_below_rate(self):
|
||||
"""At default rate 0.1, random=0.05 should pass the event through."""
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY_SAMPLE_RATE", 0.1):
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.05):
|
||||
result = telemetry_module._sampling_before_send(self._msg("mem0.add"))
|
||||
assert result is not None
|
||||
assert result["properties"]["sample_rate"] == 0.1
|
||||
|
||||
def test_hot_path_annotates_sample_rate(self):
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY_SAMPLE_RATE", 0.1):
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.0):
|
||||
result = telemetry_module._sampling_before_send(self._msg("mem0.search"))
|
||||
assert result["properties"]["sample_rate"] == 0.1
|
||||
|
||||
def test_lifecycle_annotates_sample_rate_one(self):
|
||||
result = telemetry_module._sampling_before_send(self._msg("mem0.init"))
|
||||
assert result["properties"]["sample_rate"] == 1.0
|
||||
|
||||
def test_rate_zero_drops_all_hot_path(self):
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY_SAMPLE_RATE", 0.0):
|
||||
# Gate is `random >= rate`, so 0.0 >= 0.0 → drop. random ∈ [0, 1) means
|
||||
# rate=0 drops every event.
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.0):
|
||||
assert telemetry_module._sampling_before_send(self._msg("mem0.add")) is None
|
||||
|
||||
def test_rate_zero_still_passes_lifecycle(self):
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY_SAMPLE_RATE", 0.0):
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.999):
|
||||
assert telemetry_module._sampling_before_send(self._msg("mem0.init")) is not None
|
||||
|
||||
def test_rate_one_passes_all_events(self):
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY_SAMPLE_RATE", 1.0):
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.999):
|
||||
# 0.999 > 1.0 is False, so the gate never trips
|
||||
assert telemetry_module._sampling_before_send(self._msg("mem0.add")) is not None
|
||||
|
||||
def test_does_not_override_caller_supplied_sample_rate_for_hot_path(self):
|
||||
"""If a caller pre-populates sample_rate, our value still wins (we're authoritative)."""
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY_SAMPLE_RATE", 0.1):
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.0):
|
||||
msg = self._msg("mem0.add", {"sample_rate": 0.99, "other": "x"})
|
||||
result = telemetry_module._sampling_before_send(msg)
|
||||
assert result["properties"]["sample_rate"] == 0.1
|
||||
assert result["properties"]["other"] == "x"
|
||||
|
||||
def test_handles_missing_properties_dict(self):
|
||||
"""If a msg arrives without a properties key, we create it before annotating."""
|
||||
msg = {"event": "mem0.init"} # no properties
|
||||
result = telemetry_module._sampling_before_send(msg)
|
||||
assert result is not None
|
||||
assert result["properties"]["sample_rate"] == 1.0
|
||||
|
||||
def test_handles_missing_event_field(self):
|
||||
"""Defensive: a msg with no event field is treated as a hot-path event (gets sampled)."""
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY_SAMPLE_RATE", 0.1):
|
||||
with patch("mem0.memory.telemetry.random.random", return_value=0.99):
|
||||
# event is missing -> treated as hot-path -> dropped at high random
|
||||
assert telemetry_module._sampling_before_send({"properties": {}}) is None
|
||||
|
||||
def test_handles_non_dict_input(self):
|
||||
"""Defensive: if PostHog ever passes us a non-dict, we drop the event."""
|
||||
assert telemetry_module._sampling_before_send("not a dict") is None
|
||||
assert telemetry_module._sampling_before_send(None) is None
|
||||
assert telemetry_module._sampling_before_send(42) is None
|
||||
assert telemetry_module._sampling_before_send(["list"]) is None
|
||||
|
||||
|
||||
class TestBeforeSendWiring:
|
||||
"""Verify the hook is wired into the OSS singleton but NOT client_telemetry."""
|
||||
|
||||
def setup_method(self):
|
||||
telemetry_module._oss_telemetry_instance = None
|
||||
telemetry_module._oss_telemetry_shutting_down = False
|
||||
|
||||
def teardown_method(self):
|
||||
telemetry_module._oss_telemetry_instance = None
|
||||
telemetry_module._oss_telemetry_shutting_down = False
|
||||
|
||||
def test_oss_singleton_constructed_with_before_send_hook(self):
|
||||
"""_get_oss_telemetry() should pass _sampling_before_send to AnonymousTelemetry."""
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY", True):
|
||||
with patch("mem0.memory.telemetry.Posthog") as mock_posthog_cls:
|
||||
with patch("mem0.memory.telemetry.get_or_create_user_id", return_value="u"):
|
||||
with patch("atexit.register"):
|
||||
telemetry_module._get_oss_telemetry()
|
||||
# Verify Posthog() was constructed with before_send=_sampling_before_send
|
||||
_, kwargs = mock_posthog_cls.call_args
|
||||
assert kwargs.get("before_send") is telemetry_module._sampling_before_send
|
||||
|
||||
def test_client_telemetry_constructed_without_before_send(self):
|
||||
"""The module-level client_telemetry must NOT receive before_send.
|
||||
|
||||
client_telemetry is created at import time, so this test verifies the
|
||||
existing instance has no sampling hook attached to its underlying Posthog.
|
||||
"""
|
||||
# client_telemetry is created at module import time. We verify the
|
||||
# construction call site by re-constructing AnonymousTelemetry() the
|
||||
# same way and checking the kwargs.
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY", True):
|
||||
with patch("mem0.memory.telemetry.Posthog") as mock_posthog_cls:
|
||||
with patch("mem0.memory.telemetry.get_or_create_user_id", return_value="u"):
|
||||
telemetry_module.AnonymousTelemetry() # mirrors client_telemetry construction
|
||||
_, kwargs = mock_posthog_cls.call_args
|
||||
# before_send is None (default), not _sampling_before_send
|
||||
assert kwargs.get("before_send") is None
|
||||
|
||||
def test_anonymous_telemetry_falls_back_when_posthog_rejects_before_send(self):
|
||||
"""If posthog (older version) rejects before_send, construction still succeeds."""
|
||||
with patch.object(telemetry_module, "MEM0_TELEMETRY", True):
|
||||
with patch("mem0.memory.telemetry.Posthog") as mock_posthog_cls:
|
||||
with patch("mem0.memory.telemetry.get_or_create_user_id", return_value="u"):
|
||||
# First call (with before_send) raises TypeError; second call succeeds.
|
||||
mock_posthog_cls.side_effect = [TypeError("unexpected kwarg before_send"), object()]
|
||||
at = telemetry_module.AnonymousTelemetry(before_send=telemetry_module._sampling_before_send)
|
||||
# Constructor was called twice: once with before_send, once without
|
||||
assert mock_posthog_cls.call_count == 2
|
||||
assert at.posthog is not None
|
||||
|
||||
|
||||
class TestSamplingDoesNotBreakExistingBehavior:
|
||||
"""Regression checks: sampling must be invisible above the SDK boundary."""
|
||||
|
||||
def setup_method(self):
|
||||
telemetry_module._oss_telemetry_instance = None
|
||||
telemetry_module._oss_telemetry_shutting_down = False
|
||||
|
||||
def teardown_method(self):
|
||||
telemetry_module._oss_telemetry_instance = None
|
||||
telemetry_module._oss_telemetry_shutting_down = False
|
||||
|
||||
def test_capture_event_signature_unchanged(self):
|
||||
"""The public capture_event() function still accepts the same args."""
|
||||
from inspect import signature
|
||||
|
||||
params = list(signature(telemetry_module.capture_event).parameters)
|
||||
assert params == ["event_name", "memory_instance", "additional_data"]
|
||||
|
||||
def test_capture_client_event_signature_unchanged(self):
|
||||
from inspect import signature
|
||||
|
||||
params = list(signature(telemetry_module.capture_client_event).parameters)
|
||||
assert params == ["event_name", "instance", "additional_data"]
|
||||
|
||||
def test_default_sample_rate_is_ten_percent(self):
|
||||
"""Module loads with the documented default."""
|
||||
# We can't assert MEM0_TELEMETRY_SAMPLE_RATE directly because the user
|
||||
# may have set the env var, so assert the default constant instead.
|
||||
assert telemetry_module._DEFAULT_SAMPLE_RATE == 0.1
|
||||
Reference in New Issue
Block a user