Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44dc74d78f | ||
|
|
d258b638ef | ||
|
|
bbbfcfea07 | ||
|
|
fbef369b91 | ||
|
|
a7ed68e697 | ||
|
|
8a92cf0306 | ||
|
|
0fbbb2f525 | ||
|
|
818c2981b7 | ||
|
|
1f66aadfa3 | ||
|
|
b91c745fbc | ||
|
|
af70668308 | ||
|
|
890473f891 | ||
|
|
d2ff83cf72 | ||
|
|
0e02effaf7 | ||
|
|
9269a0ad6e | ||
|
|
3d06006f36 | ||
|
|
6bb1d328ad | ||
|
|
ac296f7534 | ||
|
|
ac8f862ff7 | ||
|
|
b33fa5427c | ||
|
|
5d573dd2ae | ||
|
|
98dbf90864 | ||
|
|
6ddf1669f4 | ||
|
|
d3d2e89fd5 | ||
|
|
43175d85f2 | ||
|
|
661ecb9f0f | ||
|
|
09f181c577 | ||
|
|
3497f26a00 | ||
|
|
e9c0547423 | ||
|
|
25bc1b7426 | ||
|
|
fee344db85 | ||
|
|
b611f69381 | ||
|
|
c2862831db |
@@ -12,7 +12,7 @@
|
||||
"name": "mem0",
|
||||
"source": "./integrations/mem0-plugin",
|
||||
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search to Claude workflows.",
|
||||
"version": "0.2.10"
|
||||
"version": "0.2.11"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"name": "mem0",
|
||||
"source": "./integrations/mem0-plugin",
|
||||
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search.",
|
||||
"version": "0.2.10"
|
||||
"version": "0.2.11"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ Provide conversation messages for Mem0 to extract memories from. At least one en
|
||||
| `app_id` | string | No* | Associates the memory with an app. |
|
||||
| `metadata` | object | Optional | Custom key/value metadata (e.g., `{"topic": "preferences"}`). |
|
||||
| `infer` | boolean (default `true`) | Optional | Set to `false` to skip inference and store the provided text as-is. |
|
||||
| `expiration_date` | string | Optional | Date in `YYYY-MM-DD` format. The memory is visible through this date and hidden by default after it passes. |
|
||||
|
||||
> \* At least one entity ID (`user_id`, `agent_id`, `app_id`, or `run_id`) is required.
|
||||
|
||||
@@ -83,3 +84,11 @@ The request is queued for background processing. The response contains an `event
|
||||
<Info>
|
||||
Poll the event status via `GET /v1/event/{event_id}/`. Status will be `SUCCEEDED` or `FAILED` once processing completes.
|
||||
</Info>
|
||||
|
||||
<Info>
|
||||
Memories with `expiration_date` remain stored after they expire. Search and get-all hide them by default; pass `show_expired: true` to include them.
|
||||
</Info>
|
||||
|
||||
<Info>
|
||||
Python uses `expiration_date`; TypeScript uses `expirationDate`.
|
||||
</Info>
|
||||
|
||||
@@ -6,6 +6,10 @@ openapi: post /v3/memories/
|
||||
|
||||
List memories scoped by filters with paginated results. Entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) **must** be passed inside the `filters` object — top-level entity IDs are rejected with 400.
|
||||
|
||||
Expired memories are hidden by default. Pass `show_expired: true` to include memories whose `expiration_date` has passed.
|
||||
|
||||
Python uses `show_expired`; TypeScript uses `showExpired`.
|
||||
|
||||
The `filters` object supports complex logical operations (AND, OR, NOT) and comparison operators:
|
||||
|
||||
- `in`: Matches any of the values specified
|
||||
@@ -32,6 +36,7 @@ memories = client.get_all(
|
||||
}
|
||||
]
|
||||
},
|
||||
show_expired=False,
|
||||
page=1,
|
||||
page_size=50
|
||||
)
|
||||
@@ -46,12 +51,14 @@ memories = client.get_all(
|
||||
{
|
||||
"id": "f4cbdb08-7062-4f3e-8eb2-9f5c80dfe64c",
|
||||
"memory": "Alex is planning a trip to San Francisco from July 1st to July 10th",
|
||||
"expiration_date": null,
|
||||
"created_at": "2024-07-01T12:00:00Z",
|
||||
"updated_at": "2024-07-01T12:00:00Z"
|
||||
},
|
||||
{
|
||||
"id": "a2b8c3d4-5e6f-7g8h-9i0j-1k2l3m4n5o6p",
|
||||
"memory": "Alex prefers vegetarian restaurants",
|
||||
"expiration_date": null,
|
||||
"created_at": "2024-07-05T15:30:00Z",
|
||||
"updated_at": "2024-07-05T15:30:00Z"
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@ Relevance-ranked hybrid search across stored memories. V3 uses multi-signal retr
|
||||
|
||||
Entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) **must** be passed inside the `filters` object — top-level entity IDs are rejected with 400. At least one entity ID is required.
|
||||
|
||||
Expired memories are hidden by default. Pass `show_expired: true` to include memories whose `expiration_date` has passed.
|
||||
|
||||
Python uses `show_expired`; TypeScript uses `showExpired`.
|
||||
|
||||
The `filters` object supports complex logical operations (AND, OR, NOT) and comparison operators:
|
||||
- `in`: Matches any of the values specified
|
||||
- `gte`: Greater than or equal to
|
||||
@@ -30,6 +34,7 @@ The `filters` object supports complex logical operations (AND, OR, NOT) and comp
|
||||
```python Platform API Example
|
||||
related_memories = client.search(
|
||||
query="What are Alice's hobbies?",
|
||||
show_expired=False,
|
||||
filters={
|
||||
"OR": [
|
||||
{
|
||||
@@ -54,6 +59,7 @@ related_memories = client.search(
|
||||
"category": "hobbies"
|
||||
},
|
||||
"score": 0.82,
|
||||
"expiration_date": null,
|
||||
"created_at": "2024-07-26T10:29:36.630547-07:00",
|
||||
"updated_at": null,
|
||||
"categories": ["hobbies"]
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
---
|
||||
title: 'Update Memory'
|
||||
description: "Update the content or metadata of a single memory by its unique ID using the PUT endpoint."
|
||||
description: "Update the content, metadata, timestamp, or expiration date of a single memory by its unique ID using the PUT endpoint."
|
||||
openapi: put /v1/memories/{memory_id}/
|
||||
---
|
||||
---
|
||||
|
||||
Use this endpoint to update mutable memory fields. To make a memory expire, set `expiration_date` to a `YYYY-MM-DD` date. To make it permanent again, send `expiration_date: null`.
|
||||
|
||||
```python
|
||||
client.update("mem_123", expiration_date="2030-01-31")
|
||||
client.update("mem_123", expiration_date=None)
|
||||
```
|
||||
|
||||
TypeScript uses `expirationDate`.
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: "Remove Organization Member"
|
||||
description: "Remove a member from a Mem0 organization by revoking their access and clearing their assigned role."
|
||||
openapi: "delete /api/v1/orgs/organizations/{org_id}/members/"
|
||||
---
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: "Update Organization Member"
|
||||
description: "Update the role assigned to an existing member of a Mem0 organization to change their permissions."
|
||||
openapi: "put /api/v1/orgs/organizations/{org_id}/members/"
|
||||
---
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: "Remove Project Member"
|
||||
description: "Remove a member from a Mem0 project to revoke their access and unassign their project-level role."
|
||||
openapi: "delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/"
|
||||
---
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: "Update Project Member"
|
||||
description: "Update the role assigned to an existing member of a Mem0 project to change their project-level permissions."
|
||||
openapi: "put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/"
|
||||
---
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: "Update Project"
|
||||
description: "Update settings and configuration for an existing Mem0 project, including name and project-level options."
|
||||
openapi: "patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/"
|
||||
---
|
||||
@@ -7,6 +7,65 @@ mode: "wide"
|
||||
<Tabs>
|
||||
<Tab title="Python">
|
||||
|
||||
<Update label="2026-06-24" description="v2.0.9">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Memory (OSS):** Improve entity extraction precision by avoiding sentence-start common noun noise, preserving useful topic phrases, and exact-deduplicating entity links before semantic matching ([#5829](https://github.com/mem0ai/mem0/pull/5829))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-24" description="v2.0.8">
|
||||
|
||||
**New Features:**
|
||||
- **Embeddings:** Add native `embed_batch` to five embedders — LM Studio, Together, HuggingFace, Vertex AI, and Google GenAI — for batched embedding requests ([#5609](https://github.com/mem0ai/mem0/pull/5609))
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Core:** Guard against malformed `image_url` entries in `parse_vision_messages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631))
|
||||
- **Core:** Return `attributed_to` from `get()`, `get_all()`, and `search()` ([#5629](https://github.com/mem0ai/mem0/pull/5629))
|
||||
- **Core:** Fix `reset()` only dropping the history table and leaving stale messages behind ([#5541](https://github.com/mem0ai/mem0/pull/5541))
|
||||
- **Core:** Guard against an entity `embed_batch` count mismatch in the v3 add pipeline ([#5604](https://github.com/mem0ai/mem0/pull/5604))
|
||||
- **Core:** Fix an async `delete_all` race condition that corrupted the entity store's `linked_memory_ids` ([#5553](https://github.com/mem0ai/mem0/pull/5553))
|
||||
- **LLMs:** Skip the JSON `response_format` for Groq compound models that reject it ([#5513](https://github.com/mem0ai/mem0/pull/5513))
|
||||
- **LLMs:** Preserve reasoning fields during base-to-provider config conversion ([#5638](https://github.com/mem0ai/mem0/pull/5638))
|
||||
- **LLMs:** Pass the configured `anthropic_base_url` to the Anthropic client ([#5626](https://github.com/mem0ai/mem0/pull/5626))
|
||||
- **LLMs:** Stop the Azure provider from mutating and corrupting caller messages during content rewrite ([#5731](https://github.com/mem0ai/mem0/pull/5731))
|
||||
- **LLMs & Embeddings:** Repair HTTP proxy support for `httpx>=0.28` and preserve `proxies` in `LlmFactory` ([#5447](https://github.com/mem0ai/mem0/pull/5447))
|
||||
- **Embeddings:** Forward `embedding_dims` to Titan V2 in the AWS Bedrock embedder ([#5671](https://github.com/mem0ai/mem0/pull/5671))
|
||||
- **Rerankers:** Log reranking failures instead of swallowing them silently ([#5717](https://github.com/mem0ai/mem0/pull/5717))
|
||||
- **Rerankers:** Clamp out-of-range LLM scores instead of mis-parsing them ([#5635](https://github.com/mem0ai/mem0/pull/5635))
|
||||
- **Rerankers:** Export all five rerankers from the package root ([#5636](https://github.com/mem0ai/mem0/pull/5636))
|
||||
- **Vector Stores:** Point the FastEmbed-missing warning at `mem0ai[extras]` ([#5622](https://github.com/mem0ai/mem0/pull/5622))
|
||||
- **Vector Stores:** Preserve empty Azure AI Search update values ([#5524](https://github.com/mem0ai/mem0/pull/5524))
|
||||
- **Vector Stores:** Add an `auto_refresh` option for OpenSearch Serverless compatibility ([#3893](https://github.com/mem0ai/mem0/pull/3893))
|
||||
- **Vector Stores:** Wrap a scalar `vector_id` in a list for Chroma `delete()` ([#5703](https://github.com/mem0ai/mem0/pull/5703))
|
||||
- **Vector Stores:** Wrap Chroma `update()` ids, embeddings, and metadatas in lists ([#5757](https://github.com/mem0ai/mem0/pull/5757))
|
||||
- **Vector Stores:** Wrap a scalar `vector_id` in a list for Milvus `delete()` ([#5704](https://github.com/mem0ai/mem0/pull/5704))
|
||||
- **Vector Stores:** Map all comparison operators in the Pinecone `_create_filter()` ([#5707](https://github.com/mem0ai/mem0/pull/5707))
|
||||
- **Vector Stores:** Return `None` instead of `{}` from Chroma `_generate_where_clause` for empty filters ([#5713](https://github.com/mem0ai/mem0/pull/5713))
|
||||
- **Vector Stores:** Return `[[]]` from the OpenSearch `list()` error path to honor the `list()` contract ([#5727](https://github.com/mem0ai/mem0/pull/5727))
|
||||
- **Vector Stores:** Return `[[]]` from the Pinecone `list()` error path instead of a dict ([#5706](https://github.com/mem0ai/mem0/pull/5706))
|
||||
- **Vector Stores:** Return `[[]]` for an uninitialized FAISS index to honor the `list()` contract ([#5725](https://github.com/mem0ai/mem0/pull/5725))
|
||||
- **Vector Stores:** Wrap the MongoDB `list()` return in an outer list to match the interface contract ([#5729](https://github.com/mem0ai/mem0/pull/5729))
|
||||
- **Vector Stores:** Deep-copy Redis `DEFAULT_FIELDS` so instances keep distinct dims ([#5633](https://github.com/mem0ai/mem0/pull/5633))
|
||||
- **Vector Stores:** Pass the required `vectors` arg in Vertex AI `list()` and similarity search ([#5627](https://github.com/mem0ai/mem0/pull/5627))
|
||||
- **Vector Stores:** Return `None` from Redis `get()` for missing IDs ([#5625](https://github.com/mem0ai/mem0/pull/5625))
|
||||
- **Vector Stores:** Drop a stray `print` in Weaviate `list_cols` ([#5637](https://github.com/mem0ai/mem0/pull/5637))
|
||||
- **Graph:** Keep distinct entities that share a substring prefix ([#5630](https://github.com/mem0ai/mem0/pull/5630))
|
||||
- **Client:** Check the HTTP status before parsing the ping response in `_validate_api_key` ([#5639](https://github.com/mem0ai/mem0/pull/5639))
|
||||
- **Server:** Fetch filtered dashboard memories beyond the default page ([#5753](https://github.com/mem0ai/mem0/pull/5753))
|
||||
- **Server:** Return 404/400 instead of 502 for not-found and invalid input ([#5634](https://github.com/mem0ai/mem0/pull/5634))
|
||||
- **Server:** Return 404 instead of 500 for a malformed API key id on revoke ([#5640](https://github.com/mem0ai/mem0/pull/5640))
|
||||
- **Server:** Use `127.0.0.1` in the dashboard healthcheck to avoid IPv6 localhost resolution ([#5612](https://github.com/mem0ai/mem0/pull/5612))
|
||||
|
||||
**Improvements:**
|
||||
- **Vector Stores:** Batch BM25 sparse encoding in Qdrant insert ([#5592](https://github.com/mem0ai/mem0/pull/5592))
|
||||
|
||||
**Security:**
|
||||
- **Vector Stores:** Sanitize Milvus and Baidu filter values to prevent expression injection ([#5746](https://github.com/mem0ai/mem0/pull/5746))
|
||||
- **Vector Stores:** Reject dict filter values in MongoDB to prevent NoSQL operator injection ([#5748](https://github.com/mem0ai/mem0/pull/5748))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-17" description="v2.0.7">
|
||||
|
||||
**New Features:**
|
||||
@@ -1011,6 +1070,31 @@ See the [OSS v1 to v2 migration guide](https://docs.mem0.ai/migration/oss-v1-to-
|
||||
|
||||
<Tab title="TypeScript">
|
||||
|
||||
<Update label="2026-06-24" description="v3.0.11">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Memory (OSS):** Align entity extraction with Python by reducing generic entity noise, preserving useful topic phrases, and exact-deduplicating entity links before semantic matching ([#5829](https://github.com/mem0ai/mem0/pull/5829))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-24" description="v3.0.10">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Memory (OSS):** Guard against malformed `image_url` entries in `parseVisionMessages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631))
|
||||
- **Memory (OSS):** Return `attributedTo` from `get()`, `search()`, and `getAll()` ([#5675](https://github.com/mem0ai/mem0/pull/5675))
|
||||
- **Memory (OSS):** Preserve message roles in the extraction input so assistant facts aren't attributed to the user ([#5643](https://github.com/mem0ai/mem0/pull/5643))
|
||||
- **Memory (OSS):** Reject empty or blank messages in `Memory.add()` to prevent hallucinated memories ([#5545](https://github.com/mem0ai/mem0/pull/5545))
|
||||
- **Memory (OSS):** Check `message.role` instead of `content` when detecting system messages ([#3921](https://github.com/mem0ai/mem0/pull/3921))
|
||||
- **LLMs:** Honor the configured `baseURL` in `AnthropicLLM` ([#5740](https://github.com/mem0ai/mem0/pull/5740))
|
||||
- **Client:** Preserve `customCategories` names through key conversion ([#5741](https://github.com/mem0ai/mem0/pull/5741))
|
||||
- **Client:** Prevent hallucinated memories on an empty messages payload ([#5613](https://github.com/mem0ai/mem0/pull/5613))
|
||||
- **Client:** Preserve user metadata keys across the case-conversion round-trip ([#5515](https://github.com/mem0ai/mem0/pull/5515))
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Upgrade `form-data` to `>=4.0.6` across pnpm workspaces to remediate CVE-2026-12143 ([#5618](https://github.com/mem0ai/mem0/pull/5618))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-17" description="v3.0.9">
|
||||
|
||||
**Bug Fixes:**
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: "FastEmbed"
|
||||
description: "Configure FastEmbed as an embedding provider in Mem0 to generate embeddings locally using ONNX-based models without a GPU."
|
||||
---
|
||||
|
||||
You can use FastEmbed to run embedding models locally in Mem0. FastEmbed is an ONNX-based embedding library that runs efficiently on CPU without requiring a GPU or an external API key.
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
pip install fastembed
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
|
||||
|
||||
config = {
|
||||
"embedder": {
|
||||
"provider": "fastembed",
|
||||
"config": {
|
||||
"model": "thenlper/gte-large"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
|
||||
]
|
||||
m.add(messages, user_id="john")
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### Config
|
||||
|
||||
Here are the parameters available for configuring FastEmbed embedder:
|
||||
|
||||
| Parameter | Description | Default Value |
|
||||
| --- | --- | --- |
|
||||
| `model` | The name of the FastEmbed model to use | `thenlper/gte-large` |
|
||||
| `embedding_dims` | Dimensions of the embedding model (auto-derived from the model if not set) | `None` |
|
||||
@@ -7,7 +7,8 @@ To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment v
|
||||
|
||||
## Usage
|
||||
|
||||
```python
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
@@ -36,6 +37,32 @@ messages = [
|
||||
m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { Memory } from 'mem0ai/oss';
|
||||
|
||||
const config = {
|
||||
llm: {
|
||||
provider: 'deepseek',
|
||||
config: {
|
||||
apiKey: process.env.DEEPSEEK_API_KEY || '',
|
||||
model: 'deepseek-chat',
|
||||
temperature: 0.2,
|
||||
maxTokens: 2000,
|
||||
top_p: 1.0,
|
||||
},
|
||||
},
|
||||
};
|
||||
const memory = new Memory(config);
|
||||
const messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
|
||||
];
|
||||
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
You can also configure the API base URL in the config:
|
||||
|
||||
```python
|
||||
|
||||
@@ -4,9 +4,12 @@ description: "Use LiteLLM as an LLM provider in Mem0 to access over 100 language
|
||||
---
|
||||
[Litellm](https://litellm.vercel.app/docs/) is compatible with over 100 large language models (LLMs), all using a standardized input/output format. You can explore the [available models](https://litellm.vercel.app/docs/providers) to use with Litellm. Ensure you set the `API_KEY` for the model you choose to use.
|
||||
|
||||
In the TypeScript SDK, run LiteLLM as a [proxy server](https://docs.litellm.ai/docs/simple_proxy) (an OpenAI-compatible endpoint) and point Mem0 at it via `LITELLM_API_BASE` (defaults to `http://localhost:4000`).
|
||||
|
||||
## Usage
|
||||
|
||||
```python
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
@@ -33,6 +36,33 @@ messages = [
|
||||
m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { Memory } from 'mem0ai/oss';
|
||||
|
||||
// Point Mem0 at your LiteLLM proxy. apiKey defaults to "sk-anything"
|
||||
// (the proxy handles real auth); baseURL defaults to http://localhost:4000.
|
||||
const config = {
|
||||
llm: {
|
||||
provider: 'litellm',
|
||||
config: {
|
||||
apiKey: process.env.LITELLM_API_KEY || 'sk-anything',
|
||||
baseURL: process.env.LITELLM_API_BASE || 'http://localhost:4000',
|
||||
model: 'gpt-5-mini',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const memory = new Memory(config);
|
||||
const messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
|
||||
];
|
||||
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Config
|
||||
|
||||
All available parameters for the `litellm` config are present in [Master List of All Params in Config](../config).
|
||||
@@ -7,7 +7,8 @@ To use MiniMax LLM models, you have to set the `MINIMAX_API_KEY` environment var
|
||||
|
||||
## Usage
|
||||
|
||||
```python
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
@@ -36,9 +37,37 @@ messages = [
|
||||
m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { Memory } from 'mem0ai/oss';
|
||||
|
||||
const config = {
|
||||
llm: {
|
||||
provider: 'minimax',
|
||||
config: {
|
||||
apiKey: process.env.MINIMAX_API_KEY || '',
|
||||
model: 'MiniMax-M2.7',
|
||||
temperature: 0.2,
|
||||
maxTokens: 2000,
|
||||
topP: 1.0,
|
||||
},
|
||||
},
|
||||
};
|
||||
const memory = new Memory(config);
|
||||
const messages = [
|
||||
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
|
||||
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
|
||||
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
|
||||
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
|
||||
];
|
||||
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
You can also configure the API base URL in the config:
|
||||
|
||||
```python
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "minimax",
|
||||
@@ -51,6 +80,20 @@ config = {
|
||||
}
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
const config = {
|
||||
llm: {
|
||||
provider: 'minimax',
|
||||
config: {
|
||||
model: 'MiniMax-M2.7',
|
||||
baseURL: 'https://your-custom-endpoint.com',
|
||||
apiKey: 'your-api-key', // alternatively to using the environment variable
|
||||
},
|
||||
},
|
||||
};
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Config
|
||||
|
||||
All available parameters for the `minimax` config are present in [Master List of All Params in Config](../config).
|
||||
|
||||
@@ -1,226 +0,0 @@
|
||||
---
|
||||
title: LLM as Reranker
|
||||
description: "Use any LLM as a flexible reranker in Mem0 with custom prompts and domain-specific scoring logic."
|
||||
---
|
||||
|
||||
<Warning>
|
||||
**This page has been superseded.** Please see [LLM Reranker](/components/rerankers/models/llm_reranker) for the complete and up-to-date documentation on using LLMs for reranking.
|
||||
</Warning>
|
||||
|
||||
LLM-based reranker provides maximum flexibility by using any Large Language Model to score document relevance. This approach allows for custom prompts and domain-specific scoring logic.
|
||||
|
||||
## Supported LLM Providers
|
||||
|
||||
Any LLM provider supported by Mem0 can be used for reranking:
|
||||
|
||||
- **OpenAI**: GPT-4, GPT-3.5-turbo, etc.
|
||||
- **Anthropic**: Claude models
|
||||
- **Together**: Open-source models
|
||||
- **Groq**: Fast inference
|
||||
- **Ollama**: Local models
|
||||
- And more...
|
||||
|
||||
## Configuration
|
||||
|
||||
```python Python
|
||||
from mem0 import Memory
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"collection_name": "my_memories",
|
||||
"path": "./chroma_db"
|
||||
}
|
||||
},
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4o-mini"
|
||||
}
|
||||
},
|
||||
"reranker": {
|
||||
"provider": "llm",
|
||||
"config": {
|
||||
"model": "gpt-4o-mini",
|
||||
"provider": "openai",
|
||||
"api_key": "your-openai-api-key", # or set OPENAI_API_KEY
|
||||
"top_k": 5,
|
||||
"temperature": 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
memory = Memory.from_config(config)
|
||||
```
|
||||
|
||||
## Custom Scoring Prompt
|
||||
|
||||
You can provide a custom prompt for relevance scoring:
|
||||
|
||||
```python Python
|
||||
custom_prompt = """You are a relevance scoring assistant. Rate how well this document answers the query.
|
||||
|
||||
Query: "{query}"
|
||||
Document: "{document}"
|
||||
|
||||
Score from 0.0 to 1.0 where:
|
||||
- 1.0: Perfect match, directly answers the query
|
||||
- 0.8-0.9: Highly relevant, good match
|
||||
- 0.6-0.7: Moderately relevant, partial match
|
||||
- 0.4-0.5: Slightly relevant, limited useful information
|
||||
- 0.0-0.3: Not relevant or no useful information
|
||||
|
||||
Provide only a single numerical score between 0.0 and 1.0."""
|
||||
|
||||
config["reranker"]["config"]["scoring_prompt"] = custom_prompt
|
||||
```
|
||||
|
||||
## Usage Example
|
||||
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
# Set API key
|
||||
os.environ["OPENAI_API_KEY"] = "your-api-key"
|
||||
|
||||
# Initialize memory with LLM reranker
|
||||
config = {
|
||||
"vector_store": {"provider": "chroma"},
|
||||
"llm": {"provider": "openai", "config": {"model": "gpt-4o-mini"}},
|
||||
"reranker": {
|
||||
"provider": "llm",
|
||||
"config": {
|
||||
"model": "gpt-4o-mini",
|
||||
"provider": "openai",
|
||||
"temperature": 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
memory = Memory.from_config(config)
|
||||
|
||||
# Add memories
|
||||
messages = [
|
||||
{"role": "user", "content": "I'm learning Python programming"},
|
||||
{"role": "user", "content": "I find object-oriented programming challenging"},
|
||||
{"role": "user", "content": "I love hiking in national parks"}
|
||||
]
|
||||
|
||||
memory.add(messages, user_id="david")
|
||||
|
||||
# Search with LLM reranking
|
||||
results = memory.search("What programming topics is the user studying?", filters={"user_id": "david"})
|
||||
|
||||
for result in results['results']:
|
||||
print(f"Memory: {result['memory']}")
|
||||
print(f"Vector Score: {result['score']:.3f}")
|
||||
print(f"Rerank Score: {result['rerank_score']:.3f}")
|
||||
print()
|
||||
```
|
||||
|
||||
```text Output
|
||||
Memory: I'm learning Python programming
|
||||
Vector Score: 0.856
|
||||
Rerank Score: 0.920
|
||||
|
||||
Memory: I find object-oriented programming challenging
|
||||
Vector Score: 0.782
|
||||
Rerank Score: 0.850
|
||||
```
|
||||
|
||||
## Domain-Specific Scoring
|
||||
|
||||
Create specialized scoring for your domain:
|
||||
|
||||
```python Python
|
||||
medical_prompt = """You are a medical relevance expert. Score how relevant this medical record is to the clinical query.
|
||||
|
||||
Clinical Query: "{query}"
|
||||
Medical Record: "{document}"
|
||||
|
||||
Consider:
|
||||
- Clinical relevance and accuracy
|
||||
- Patient safety implications
|
||||
- Diagnostic value
|
||||
- Treatment relevance
|
||||
|
||||
Score from 0.0 to 1.0. Provide only the numerical score."""
|
||||
|
||||
config = {
|
||||
"reranker": {
|
||||
"provider": "llm",
|
||||
"config": {
|
||||
"model": "gpt-4o-mini",
|
||||
"provider": "openai",
|
||||
"scoring_prompt": medical_prompt,
|
||||
"temperature": 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Multiple LLM Providers
|
||||
|
||||
Use different LLM providers for reranking:
|
||||
|
||||
```python Python
|
||||
# Using Anthropic Claude
|
||||
anthropic_config = {
|
||||
"reranker": {
|
||||
"provider": "llm",
|
||||
"config": {
|
||||
"model": "claude-3-haiku-20240307",
|
||||
"provider": "anthropic",
|
||||
"temperature": 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Using local Ollama model
|
||||
ollama_config = {
|
||||
"reranker": {
|
||||
"provider": "llm",
|
||||
"config": {
|
||||
"model": "llama2:7b",
|
||||
"provider": "ollama",
|
||||
"temperature": 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration Parameters
|
||||
|
||||
| Parameter | Description | Type | Default |
|
||||
|-----------|-------------|------|---------|
|
||||
| `model` | LLM model to use for scoring | `str` | `"gpt-4o-mini"` |
|
||||
| `provider` | LLM provider name | `str` | `"openai"` |
|
||||
| `api_key` | API key for the LLM provider | `str` | `None` |
|
||||
| `top_k` | Maximum documents to return | `int` | `None` |
|
||||
| `temperature` | Temperature for LLM generation | `float` | `0.0` |
|
||||
| `max_tokens` | Maximum tokens for LLM response | `int` | `100` |
|
||||
| `scoring_prompt` | Custom prompt template | `str` | Default prompt |
|
||||
|
||||
## Advantages
|
||||
|
||||
- **Maximum Flexibility**: Custom prompts for any use case
|
||||
- **Domain Expertise**: Leverage LLM knowledge for specialized domains
|
||||
- **Interpretability**: Understand scoring through prompt engineering
|
||||
- **Multi-criteria**: Score based on multiple relevance factors
|
||||
|
||||
## Considerations
|
||||
|
||||
- **Latency**: Higher latency than specialized rerankers
|
||||
- **Cost**: LLM API costs per reranking operation
|
||||
- **Consistency**: May have slight variations in scoring
|
||||
- **Prompt Engineering**: Requires careful prompt design
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Temperature**: Use 0.0 for consistent scoring
|
||||
2. **Prompt Design**: Be specific about scoring criteria
|
||||
3. **Token Efficiency**: Keep prompts concise to reduce costs
|
||||
4. **Caching**: Cache results for repeated queries when possible
|
||||
5. **Fallback**: Handle API errors gracefully
|
||||
@@ -21,49 +21,47 @@ from mem0 import Memory
|
||||
load_dotenv()
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "pgvector",
|
||||
"config": {
|
||||
"connection_string": os.environ["DATABASE_URL"],
|
||||
"collection_name": "memories",
|
||||
"embedding_model_dims": 1536,
|
||||
"hnsw": True,
|
||||
},
|
||||
},
|
||||
"vector_store": {
|
||||
"provider": "pgvector",
|
||||
"config": {
|
||||
"connection_string": os.environ["DATABASE_URL"],
|
||||
"collection_name": "memories",
|
||||
"embedding_model_dims": 1536,
|
||||
"hnsw": True,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."},
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."},
|
||||
]
|
||||
m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
|
||||
results = m.search(
|
||||
"What movies should I recommend?",
|
||||
filters={"user_id": "alice"},
|
||||
"What movies should I recommend?",
|
||||
filters={"user_id": "alice"},
|
||||
)
|
||||
|
||||
print(results)
|
||||
```
|
||||
|
||||
````
|
||||
|
||||
```typescript TypeScript
|
||||
import "dotenv/config";
|
||||
import { Memory } from "mem0ai/oss";
|
||||
|
||||
const databaseUrl = new URL(process.env.DATABASE_URL!);
|
||||
|
||||
const m = new Memory({
|
||||
vectorStore: {
|
||||
provider: "pgvector",
|
||||
config: {
|
||||
user: decodeURIComponent(databaseUrl.username),
|
||||
password: decodeURIComponent(databaseUrl.password),
|
||||
host: databaseUrl.hostname,
|
||||
port: Number(databaseUrl.port || 5432),
|
||||
dbname: databaseUrl.pathname.slice(1) || "neondb",
|
||||
connectionString: process.env.DATABASE_URL!,
|
||||
ssl: {
|
||||
rejectUnauthorized: false,
|
||||
},
|
||||
collectionName: "memories",
|
||||
dimension: 1536,
|
||||
embeddingModelDims: 1536,
|
||||
@@ -89,7 +87,8 @@ const results = await m.search("What movies should I recommend?", {
|
||||
});
|
||||
|
||||
console.log(results);
|
||||
```
|
||||
````
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## SQL Migration
|
||||
@@ -116,20 +115,19 @@ DATABASE_URL=postgresql://user:password@ep-example.us-east-2.aws.neon.tech/neond
|
||||
| `sslmode` | PostgreSQL SSL mode. Use `require` for Neon. | Driver default |
|
||||
</Tab>
|
||||
<Tab title="TypeScript">
|
||||
The current Mem0 TypeScript `pgvector` adapter takes individual Postgres fields,
|
||||
so parse `DATABASE_URL` before creating `Memory`.
|
||||
Use the Neon `DATABASE_URL` directly with `connectionString`. Set `ssl` if your runtime needs an explicit TLS config object.
|
||||
|
||||
| Parameter | Description | Default |
|
||||
| -------------------- | ---------------------------------------------- | -------------- |
|
||||
| `connectionString` | Neon Postgres connection string. | Required |
|
||||
| `ssl` | Optional TLS settings passed directly to `pg`. | Driver default |
|
||||
| `collectionName` | Name for the vector collection. | `memories` |
|
||||
| `dimension` | Vector dimension for Mem0 config. | Auto-detected |
|
||||
| `embeddingModelDims` | Embedding model dimensions for table creation. | Required |
|
||||
| `hnsw` | Enables HNSW indexing. | `false` |
|
||||
|
||||
**TLS note:** `ssl: true` is sufficient for most Neon connections since Neon uses valid certificates. Use `ssl: { rejectUnauthorized: false }` only when connecting through Neon's connection pooler on certain edge runtimes (e.g. Cloudflare Workers) that require it, or when your environment does not trust the Neon CA chain.
|
||||
|
||||
| Parameter | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| `user` | Database user. | Required |
|
||||
| `password` | Database password. | Required |
|
||||
| `host` | Database host. | Required |
|
||||
| `port` | Database port. | `5432` |
|
||||
| `dbname` | Database name. | `vector_store` |
|
||||
| `collectionName` | Name for the vector collection. | `memories` |
|
||||
| `dimension` | Vector dimension for Mem0 config. | Auto-detected |
|
||||
| `embeddingModelDims` | Embedding model dimensions for table creation. | Required |
|
||||
| `hnsw` | Enables HNSW indexing. | `false` |
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
|
||||
@@ -56,6 +56,30 @@ config = {
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Options
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `collection_name` | string | required | Name of the OpenSearch index |
|
||||
| `host` | string | required | OpenSearch endpoint URL |
|
||||
| `port` | int | 9200 | Port number |
|
||||
| `http_auth` | object | None | Authentication credentials (e.g., AWSV4SignerAuth) |
|
||||
| `embedding_model_dims` | int | 1536 | Dimension of embedding vectors |
|
||||
| `use_ssl` | bool | False | Enable SSL/TLS connection |
|
||||
| `verify_certs` | bool | False | Verify SSL certificates |
|
||||
| `auto_refresh` | bool | False | Automatically refresh index after insert. OpenSearch refreshes every ~1 second by default, so this is rarely needed. |
|
||||
|
||||
<Note>
|
||||
The defaults above match a local OpenSearch instance. The AWS OpenSearch Serverless
|
||||
example earlier on this page intentionally overrides them with `port=443`, `use_ssl=True`,
|
||||
and `verify_certs=True`, which are required when connecting to a Serverless collection.
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
For **AWS OpenSearch Serverless**, keep `auto_refresh=False` (the default).
|
||||
The `indices.refresh()` API is not supported on Serverless collections.
|
||||
</Note>
|
||||
|
||||
### Add Memories
|
||||
|
||||
```python
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
title: "pgvector"
|
||||
description: "Use pgvector as a vector store in Mem0 for PostgreSQL-based vector similarity search with open-source simplicity."
|
||||
---
|
||||
|
||||
[pgvector](https://github.com/pgvector/pgvector) is an open-source vector similarity search extension for Postgres. After connecting to Postgres, run `CREATE EXTENSION IF NOT EXISTS vector;` to create the vector extension.
|
||||
|
||||
### Usage
|
||||
@@ -14,41 +15,38 @@ from mem0 import Memory
|
||||
os.environ["OPENAI_API_KEY"] = "sk-xx"
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "pgvector",
|
||||
"config": {
|
||||
"user": "test",
|
||||
"password": "123",
|
||||
"host": "127.0.0.1",
|
||||
"port": "5432",
|
||||
}
|
||||
}
|
||||
"vector_store": {
|
||||
"provider": "pgvector",
|
||||
"config": {
|
||||
"user": "test",
|
||||
"password": "123",
|
||||
"host": "127.0.0.1",
|
||||
"port": "5432",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."},
|
||||
]
|
||||
m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
```
|
||||
|
||||
````
|
||||
|
||||
```typescript TypeScript
|
||||
import { Memory } from 'mem0ai/oss';
|
||||
import { Memory } from "mem0ai/oss";
|
||||
|
||||
const config = {
|
||||
vectorStore: {
|
||||
provider: 'pgvector',
|
||||
provider: "pgvector",
|
||||
config: {
|
||||
collectionName: 'memories',
|
||||
collectionName: "memories",
|
||||
embeddingModelDims: 1536,
|
||||
user: 'test',
|
||||
password: '123',
|
||||
host: '127.0.0.1',
|
||||
port: 5432,
|
||||
dbname: 'vector_store', // Optional; TypeScript OSS defaults to `vector_store` when omitted
|
||||
connectionString: "postgresql://test:123@localhost:5432/vector_store",
|
||||
diskann: false, // Optional, requires pgvectorscale extension
|
||||
hnsw: false, // Optional, for HNSW indexing
|
||||
},
|
||||
@@ -57,37 +55,44 @@ const config = {
|
||||
|
||||
const memory = new Memory(config);
|
||||
const messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
|
||||
]
|
||||
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
|
||||
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
|
||||
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
|
||||
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
|
||||
];
|
||||
|
||||
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
|
||||
```
|
||||
````
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Config
|
||||
|
||||
Here are the parameters available for configuring pgvector:
|
||||
|
||||
| Parameter | Description | Default Value |
|
||||
| --- | --- | --- |
|
||||
| `dbname` | The name of the database | `postgres` |
|
||||
| `collection_name` | The name of the collection | `mem0` |
|
||||
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
|
||||
| `user` | User name to connect to the database | `None` |
|
||||
| `password` | Password to connect to the database | `None` |
|
||||
| `host` | The host where the Postgres server is running | `None` |
|
||||
| `port` | The port where the Postgres server is running | `None` |
|
||||
| `diskann` | Whether to use diskann for vector similarity search (requires pgvectorscale) | `True` |
|
||||
| `hnsw` | Whether to use hnsw for vector similarity search | `False` |
|
||||
| `sslmode` | SSL mode for PostgreSQL connection (e.g., 'require', 'prefer', 'disable') | `None` |
|
||||
| `connection_string` | PostgreSQL connection string (overrides individual connection parameters) | `None` |
|
||||
| `connection_pool` | psycopg2 connection pool object (overrides connection string and individual parameters) | `None` |
|
||||
| Parameter | SDK | Description | Default Value |
|
||||
| -------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
|
||||
| `connectionString` | TypeScript OSS | PostgreSQL connection string for direct connections. When set, Mem0 connects to the target database directly and skips the bootstrap `postgres` database flow. | `None` |
|
||||
| `ssl` | TypeScript OSS | SSL option passed directly to `pg`, either `true` or an SSL config object, for both `connectionString` and split-field connections. | `None` |
|
||||
| `dbname` | TypeScript OSS | Split-field database name. This is only used when `connectionString` is absent. | `vector_store` |
|
||||
| `collectionName` | TypeScript OSS | Collection name. | `memories` |
|
||||
| `embeddingModelDims` | TypeScript OSS | Dimensions of the embedding model. | Required |
|
||||
| `user` | TypeScript OSS + Python | Database user for split-field connections. | `None` |
|
||||
| `password` | TypeScript OSS + Python | Database password for split-field connections. | `None` |
|
||||
| `host` | TypeScript OSS + Python | Database host for split-field connections. | `None` |
|
||||
| `port` | TypeScript OSS + Python | Database port for split-field connections. | `None` |
|
||||
| `diskann` | TypeScript OSS + Python | Whether to use DiskANN for vector similarity search, requires pgvectorscale. | `False` |
|
||||
| `hnsw` | TypeScript OSS + Python | Whether to use HNSW for vector similarity search. | TypeScript OSS: `False`, Python: `True` |
|
||||
| `connection_string` | Python only | PostgreSQL connection string, overrides individual connection parameters. | `None` |
|
||||
| `sslmode` | Python only | SSL mode for PostgreSQL connections, such as `require`, `prefer`, or `disable`. | `None` |
|
||||
| `connection_pool` | Python only | psycopg connection pool object, overrides connection string and individual connection parameters. | `None` |
|
||||
|
||||
**Note (TypeScript OSS):** If you omit `dbname`, the TypeScript client uses the database name `vector_store`. Python defaults to `postgres` for `dbname`, as in the table above.
|
||||
**TypeScript OSS:** Use `connectionString` plus optional `ssl` for managed Postgres setups. If you omit `connectionString`, Mem0 falls back to split fields and uses `dbname`, `user`, `password`, `host`, `port`, and optional `ssl`.
|
||||
|
||||
**Python:** The Python SDK uses snake_case keys such as `connection_string`, `sslmode`, `collection_name`, and `embedding_model_dims`.
|
||||
|
||||
**Python connection priority**:
|
||||
|
||||
**Note**: The connection parameters have the following priority:
|
||||
1. `connection_pool` (highest priority)
|
||||
2. `connection_string`
|
||||
3. Individual connection parameters (`user`, `password`, `host`, `port`, `sslmode`)
|
||||
3. Individual connection parameters (`user`, `password`, `host`, `port`, `sslmode`)
|
||||
|
||||
@@ -345,7 +345,7 @@ When evaluating memory systems, keep these considerations in mind:
|
||||
<Card title="Research" icon="flask" href="https://mem0.ai/research">
|
||||
Published research papers and technical reports
|
||||
</Card>
|
||||
<Card title="Blog Post" icon="newspaper" href="https://mem0.ai/blog/new-algorithm">
|
||||
<Card title="Blog Post" icon="newspaper" href="https://mem0.ai/blog/the-token-efficient-memory-algorithm-now-has-temporal-reasoning">
|
||||
Detailed writeup of the new algorithm design and results
|
||||
</Card>
|
||||
<Card title="Platform Migration" icon="arrow-right" href="/migration/platform-v2-to-v3">
|
||||
|
||||
+11
-1
@@ -273,7 +273,8 @@
|
||||
"components/embedders/models/lmstudio",
|
||||
"components/embedders/models/together",
|
||||
"components/embedders/models/langchain",
|
||||
"components/embedders/models/aws_bedrock"
|
||||
"components/embedders/models/aws_bedrock",
|
||||
"components/embedders/models/fastembed"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -533,6 +534,8 @@
|
||||
"api-reference/organization/get-org",
|
||||
"api-reference/organization/get-org-members",
|
||||
"api-reference/organization/add-org-member",
|
||||
"api-reference/organization/update-org-member",
|
||||
"api-reference/organization/remove-org-member",
|
||||
"api-reference/organization/delete-org"
|
||||
]
|
||||
},
|
||||
@@ -545,6 +548,9 @@
|
||||
"api-reference/project/get-project",
|
||||
"api-reference/project/get-project-members",
|
||||
"api-reference/project/add-project-member",
|
||||
"api-reference/project/update-project",
|
||||
"api-reference/project/update-project-member",
|
||||
"api-reference/project/remove-project-member",
|
||||
"api-reference/project/delete-project"
|
||||
]
|
||||
},
|
||||
@@ -624,6 +630,10 @@
|
||||
]
|
||||
},
|
||||
"redirects": [
|
||||
{
|
||||
"source": "/components/rerankers/models/llm",
|
||||
"destination": "/components/rerankers/models/llm_reranker"
|
||||
},
|
||||
{
|
||||
"source": "/migration/breaking-changes",
|
||||
"destination": "/"
|
||||
|
||||
@@ -73,7 +73,7 @@ client = MemoryClient()
|
||||
# Define the agent
|
||||
agent = Agent(
|
||||
name="Personal Agent",
|
||||
model=OpenAIChat(id="gpt-4"),
|
||||
model=OpenAIChat(id="gpt-5-mini"),
|
||||
description="You are a helpful personal agent that helps me with day to day activities."
|
||||
"You can process both text and images.",
|
||||
markdown=True
|
||||
|
||||
@@ -65,6 +65,7 @@ The plugin uses the same shell scripts as Claude Code, Cursor, and Codex — hoo
|
||||
| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message |
|
||||
| **Pre-tool** | `PreToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tools |
|
||||
| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Stop** | `Stop` | Stores a session summary when the session ends |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
|
||||
memory_client = MemoryClient()
|
||||
agent = ConversableAgent(
|
||||
"chatbot",
|
||||
llm_config={"config_list": [{"model": "gpt-4", "api_key": OPENAI_API_KEY}]},
|
||||
llm_config={"config_list": [{"model": "gpt-5-mini", "api_key": OPENAI_API_KEY}]},
|
||||
code_execution_config=False,
|
||||
human_input_mode="NEVER",
|
||||
)
|
||||
@@ -99,7 +99,7 @@ For more complex scenarios, you can create multiple agents:
|
||||
manager = ConversableAgent(
|
||||
"manager",
|
||||
system_message="You are a manager who helps in resolving complex customer issues.",
|
||||
llm_config={"config_list": [{"model": "gpt-4", "api_key": OPENAI_API_KEY}]},
|
||||
llm_config={"config_list": [{"model": "gpt-5-mini", "api_key": OPENAI_API_KEY}]},
|
||||
human_input_mode="NEVER"
|
||||
)
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ Add the Mem0 MCP server directly with a single command:
|
||||
npx mcp-add \
|
||||
--name mem0-mcp \
|
||||
--type http \
|
||||
--url "https://mcp.mem0.ai/mcp" \
|
||||
--url "https://mcp.mem0.ai/mcp/" \
|
||||
--clients "claude code"
|
||||
```
|
||||
|
||||
@@ -138,11 +138,13 @@ When installed via the plugin marketplace, Mem0 hooks into Claude Code's lifecyc
|
||||
|
||||
| Hook | Event | What it does |
|
||||
|------|-------|-------------|
|
||||
| **Setup** | `Setup` | Installs the mem0 SDK and dependencies (runs on init and maintenance) |
|
||||
| **Session start** | `SessionStart` | Loads prior memories and displays status banner |
|
||||
| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message; skips short prompts |
|
||||
| **Pre-tool** | `PreToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tool calls |
|
||||
| **Pre-tool (3 handlers)** | `PreToolUse` | Blocks MEMORY.md writes; enforces `user_id`/`app_id` on mem0 tool calls; scans files being read for relevant memory context |
|
||||
| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Pre-compact** | `PreCompact` | Stores a session summary before context compaction |
|
||||
| **Stop** | `Stop` | Stores a session summary when the session ends |
|
||||
| **Pre-compact** | `PreCompact` | Stores a summary before the context is compacted |
|
||||
|
||||
## Example Workflow
|
||||
|
||||
|
||||
+24
-10
@@ -41,7 +41,17 @@ Install the full plugin including MCP server, lifecycle hooks, and SDK skill.
|
||||
codex plugin marketplace add mem0ai/mem0
|
||||
```
|
||||
|
||||
2. Restart Codex, open the Plugin Directory, browse the **Mem0 Plugins** marketplace, and install **Mem0**.
|
||||
2. Install the plugin:
|
||||
|
||||
```bash
|
||||
codex plugin add mem0@mem0-plugins
|
||||
```
|
||||
|
||||
Or, in the app: restart Codex, open the Plugin Directory, browse the **Mem0 Plugins** marketplace, and install **Mem0**.
|
||||
|
||||
<Note>
|
||||
Step 1 is required for the app UI. Mem0 isn't in OpenAI's curated directory yet, so **without `codex plugin marketplace add`, Mem0 won't appear in the Codex app's Plugin Directory** — searching for it returns nothing. Adding the marketplace surfaces it (under **Created by you**) and makes it installable.
|
||||
</Note>
|
||||
|
||||
<Info>
|
||||
Do not combine with Option B. The plugin manifest auto-registers the `mem0` MCP server, so adding both will create a duplicate registration.
|
||||
@@ -49,27 +59,30 @@ Install the full plugin including MCP server, lifecycle hooks, and SDK skill.
|
||||
|
||||
### Option B — Direct MCP
|
||||
|
||||
The fastest way to connect Codex to Mem0 — no plugin, no marketplace. Add to `~/.codex/config.toml`:
|
||||
The fastest way to connect Codex to Mem0 — no plugin, no marketplace. Add the MCP server with a single command:
|
||||
|
||||
```bash
|
||||
codex mcp add mem0 --url https://mcp.mem0.ai/mcp/ --bearer-token-env-var MEM0_API_KEY
|
||||
```
|
||||
|
||||
Or add it manually to `~/.codex/config.toml`:
|
||||
|
||||
```toml
|
||||
[mcp_servers.mem0]
|
||||
url = "https://mcp.mem0.ai/mcp"
|
||||
url = "https://mcp.mem0.ai/mcp/"
|
||||
bearer_token_env_var = "MEM0_API_KEY"
|
||||
```
|
||||
|
||||
Make sure `MEM0_API_KEY` is exported in the shell you launch Codex from, then restart Codex.
|
||||
|
||||
<Info>
|
||||
Codex's `codex mcp add` CLI only supports stdio MCP servers. Because Mem0's MCP is HTTP/streamable, you configure it by editing `config.toml` directly (or via the **Plugins → Connect to a custom MCP → Streamable HTTP** UI in the Codex app).
|
||||
</Info>
|
||||
|
||||
This gives you the MCP tools but not the lifecycle hooks or SDK skill.
|
||||
|
||||
### Managing the Plugin
|
||||
|
||||
```bash
|
||||
codex plugin marketplace upgrade # pull latest plugin versions
|
||||
codex plugin marketplace remove mem0-plugins # unregister the marketplace
|
||||
codex plugin remove mem0@mem0-plugins # uninstall the plugin (keeps the marketplace)
|
||||
codex plugin marketplace remove mem0-plugins # unregister the marketplace entirely
|
||||
```
|
||||
|
||||
To update, run `codex plugin marketplace upgrade` to pull the latest from the Mem0 repo.
|
||||
@@ -110,9 +123,10 @@ When installed via the plugin marketplace, Mem0 hooks into Codex's lifecycle to
|
||||
|------|-------|-------------|
|
||||
| **Session start** | `SessionStart` | Loads prior memories and displays status banner |
|
||||
| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message |
|
||||
| **Pre-tool** | `PreToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tool calls |
|
||||
| **Pre-tool (3 handlers)** | `PreToolUse` | Blocks MEMORY.md writes; enforces `user_id`/`app_id` on mem0 tool calls; scans files being read for relevant memory context |
|
||||
| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Pre-compact** | `PreCompact` | Stores a session summary before context compaction |
|
||||
| **Stop** | `Stop` | Stores a session summary when the session ends |
|
||||
| **Pre-compact** | `PreCompact` | Stores a summary before the context is compacted |
|
||||
|
||||
## Example Workflow
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ The fastest way to get started. Click the link below to install the Mem0 MCP ser
|
||||
npx mcp-add \
|
||||
--name mem0-mcp \
|
||||
--type http \
|
||||
--url "https://mcp.mem0.ai/mcp" \
|
||||
--url "https://mcp.mem0.ai/mcp/" \
|
||||
--clients "cursor"
|
||||
```
|
||||
|
||||
@@ -108,9 +108,10 @@ When installed via the Cursor Marketplace, Mem0 hooks into Cursor's lifecycle:
|
||||
|------|-------|-------------|
|
||||
| **Session start** | `sessionStart` | Loads prior memories and displays status banner |
|
||||
| **User prompt** | `beforeSubmitPrompt` | Searches relevant memories before each message; skips short prompts |
|
||||
| **Pre-tool (2 handlers)** | `preToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tool calls |
|
||||
| **Pre-tool (3 handlers)** | `preToolUse` | Blocks MEMORY.md writes; enforces `user_id`/`app_id` on mem0 tool calls; scans files being read for relevant memory context |
|
||||
| **Post-tool (2 handlers)** | `postToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Pre-compact** | `preCompact` | Stores a session summary before context compaction |
|
||||
| **Stop** | `stop` | Stores a session summary when the session ends |
|
||||
| **Pre-compact** | `preCompact` | Stores a summary before the context is compacted |
|
||||
|
||||
## Example Workflow
|
||||
|
||||
|
||||
@@ -100,12 +100,12 @@ This section:
|
||||
Initialize both the ElevenLabs and Mem0 clients:
|
||||
|
||||
```python
|
||||
# Initialize ElevenLabs client
|
||||
client = ElevenLabs(api_key=API_KEY)
|
||||
# Initialize ElevenLabs client
|
||||
client = ElevenLabs(api_key=API_KEY)
|
||||
|
||||
# Initialize memory client and tools
|
||||
client_tools = ClientTools()
|
||||
mem0_client = AsyncMemoryClient()
|
||||
# Initialize memory client and tools
|
||||
client_tools = ClientTools()
|
||||
mem0_client = AsyncMemoryClient()
|
||||
```
|
||||
|
||||
Here we:
|
||||
@@ -118,36 +118,36 @@ Here we:
|
||||
Define the two key memory functions that will be registered as tools:
|
||||
|
||||
```python
|
||||
# Define memory-related functions for the agent
|
||||
async def add_memories(parameters):
|
||||
"""Add a message to the memory store"""
|
||||
message = parameters.get("message")
|
||||
await mem0_client.add(
|
||||
messages=message,
|
||||
user_id=USER_ID
|
||||
)
|
||||
return "Memory added successfully"
|
||||
# Define memory-related functions for the agent
|
||||
async def add_memories(parameters):
|
||||
"""Add a message to the memory store"""
|
||||
message = parameters.get("message")
|
||||
await mem0_client.add(
|
||||
messages=message,
|
||||
user_id=USER_ID
|
||||
)
|
||||
return "Memory added successfully"
|
||||
|
||||
async def retrieve_memories(parameters):
|
||||
"""Retrieve relevant memories based on the input message"""
|
||||
message = parameters.get("message")
|
||||
async def retrieve_memories(parameters):
|
||||
"""Retrieve relevant memories based on the input message"""
|
||||
message = parameters.get("message")
|
||||
|
||||
# For Platform API, user_id goes in filters
|
||||
filters = {"user_id": USER_ID}
|
||||
# For Platform API, user_id goes in filters
|
||||
filters = {"user_id": USER_ID}
|
||||
|
||||
# Search for relevant memories using the message as a query
|
||||
results = await mem0_client.search(
|
||||
query=message,
|
||||
filters=filters
|
||||
)
|
||||
# Search for relevant memories using the message as a query
|
||||
results = await mem0_client.search(
|
||||
query=message,
|
||||
filters=filters
|
||||
)
|
||||
|
||||
# Extract and join the memory texts
|
||||
memories = ' '.join([result["memory"] for result in results.get('results', [])])
|
||||
print("[ Memories ]", memories)
|
||||
# Extract and join the memory texts
|
||||
memories = ' '.join([result["memory"] for result in results.get('results', [])])
|
||||
print("[ Memories ]", memories)
|
||||
|
||||
if memories:
|
||||
return memories
|
||||
return "No memories found"
|
||||
if memories:
|
||||
return memories
|
||||
return "No memories found"
|
||||
```
|
||||
|
||||
These functions:
|
||||
@@ -171,9 +171,9 @@ These functions:
|
||||
Register the memory functions with the ElevenLabs ClientTools system:
|
||||
|
||||
```python
|
||||
# Register the memory functions as tools for the agent
|
||||
client_tools.register("addMemories", add_memories, is_async=True)
|
||||
client_tools.register("retrieveMemories", retrieve_memories, is_async=True)
|
||||
# Register the memory functions as tools for the agent
|
||||
client_tools.register("addMemories", add_memories, is_async=True)
|
||||
client_tools.register("retrieveMemories", retrieve_memories, is_async=True)
|
||||
```
|
||||
|
||||
This allows the ElevenLabs agent to:
|
||||
@@ -186,19 +186,19 @@ This allows the ElevenLabs agent to:
|
||||
Configure the conversation with ElevenLabs:
|
||||
|
||||
```python
|
||||
# Initialize the conversation
|
||||
conversation = Conversation(
|
||||
client,
|
||||
AGENT_ID,
|
||||
# Assume auth is required when API_KEY is set
|
||||
requires_auth=bool(API_KEY),
|
||||
audio_interface=DefaultAudioInterface(),
|
||||
client_tools=client_tools,
|
||||
callback_agent_response=lambda response: print(f"Agent: {response}"),
|
||||
callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
|
||||
callback_user_transcript=lambda transcript: print(f"User: {transcript}"),
|
||||
# callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),
|
||||
)
|
||||
# Initialize the conversation
|
||||
conversation = Conversation(
|
||||
client,
|
||||
AGENT_ID,
|
||||
# Assume auth is required when API_KEY is set
|
||||
requires_auth=bool(API_KEY),
|
||||
audio_interface=DefaultAudioInterface(),
|
||||
client_tools=client_tools,
|
||||
callback_agent_response=lambda response: print(f"Agent: {response}"),
|
||||
callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
|
||||
callback_user_transcript=lambda transcript: print(f"User: {transcript}"),
|
||||
# callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),
|
||||
)
|
||||
```
|
||||
|
||||
This sets up the conversation with:
|
||||
@@ -217,16 +217,16 @@ This sets up the conversation with:
|
||||
Start and manage the conversation:
|
||||
|
||||
```python
|
||||
# Start the conversation
|
||||
print(f"Starting conversation with user_id: {USER_ID}")
|
||||
conversation.start_session()
|
||||
# Start the conversation
|
||||
print(f"Starting conversation with user_id: {USER_ID}")
|
||||
conversation.start_session()
|
||||
|
||||
# Handle Ctrl+C to gracefully end the session
|
||||
signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session())
|
||||
# Handle Ctrl+C to gracefully end the session
|
||||
signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session())
|
||||
|
||||
# Wait for the conversation to end and get the conversation ID
|
||||
conversation_id = conversation.wait_for_session_end()
|
||||
print(f"Conversation ID: {conversation_id}")
|
||||
# Wait for the conversation to end and get the conversation ID
|
||||
conversation_id = conversation.wait_for_session_end()
|
||||
print(f"Conversation ID: {conversation_id}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -445,4 +445,3 @@ By integrating ElevenLabs Conversational AI with Mem0, you can create voice agen
|
||||
Create voice-first AI applications
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
+164
-37
@@ -1,35 +1,42 @@
|
||||
---
|
||||
title: Hermes Agent
|
||||
description: "Add long-term memory to Hermes agents using Mem0 as a pluggable memory provider with automatic background sync and zero-latency prefetch."
|
||||
description: "Add long-term memory to Hermes agents with Mem0, on managed Mem0 Cloud or fully self-hosted (OSS), with automatic background sync and zero-latency prefetch."
|
||||
---
|
||||
|
||||
Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent) — a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 automatically learns facts from your conversations and surfaces relevant ones before each turn — all without slowing down the chat.
|
||||
Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones before each turn, without slowing down the chat.
|
||||
|
||||
## Overview
|
||||
You can run Mem0 in two ways:
|
||||
|
||||
Hermes runs a built-in memory system (file-based `MEMORY.md` and `USER.md`) alongside one external provider. When Mem0 is active, it works additively with the built-in system at three key moments in every conversation turn:
|
||||
- **Platform mode** (default): managed Mem0 Cloud. Add your API key and you are ready.
|
||||
- **OSS mode**: fully self-hosted with your own LLM, embedder, and vector store. No data leaves your machine.
|
||||
|
||||
### 1. Before the Agent Responds (Prefetch)
|
||||
## How It Works
|
||||
|
||||
When you send a message, Hermes checks if it already has cached Mem0 search results from the previous turn. If so, those memories are injected into the system prompt so the LLM can see them. This is **zero-latency** — no waiting for an API call.
|
||||
Hermes runs a built-in memory system (file-based `MEMORY.md` and `USER.md`) alongside one external provider. When Mem0 is active, it works additively with the built-in system at three points in every conversation turn.
|
||||
|
||||
### 2. After the Agent Responds (Sync)
|
||||
### 1. Before the agent responds (prefetch)
|
||||
|
||||
Once the LLM finishes responding, Hermes sends the `(user message, assistant response)` pair to Mem0's API in a **background thread**. Mem0's server-side LLM automatically extracts facts (e.g., "user prefers Python", "user works at Acme Corp") — you don't have to tell it what to remember.
|
||||
When you send a message, Hermes checks for cached Mem0 search results from the previous turn. If they exist, those memories are injected into the system prompt so the model can see them. This is zero-latency, with no waiting on an API call.
|
||||
|
||||
### 3. Background Prefetch for Next Turn
|
||||
### 2. After the agent responds (sync)
|
||||
|
||||
At the same time as sync, Hermes kicks off a background search on Mem0 to pre-load relevant memories for the next turn. By the time you type your next message, the memories are already cached.
|
||||
Once the model finishes, Hermes sends the `(user message, assistant response)` pair to Mem0 in a background thread. Mem0 extracts facts automatically (for example, "user prefers Python" or "user works at Acme Corp"), so you never have to tell it what to remember. Each write is tagged with the gateway channel it came from.
|
||||
|
||||
### 3. Background prefetch for the next turn
|
||||
|
||||
At the same time, Hermes runs a background search to pre-load relevant memories for your next message. By the time you type, the results are already cached.
|
||||
|
||||
## Agent Tools
|
||||
|
||||
When Mem0 is active, the LLM gets three extra tools it can call during conversations:
|
||||
When Mem0 is active, the model gets five tools it can call during a conversation:
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `mem0_profile` | Fetch all stored memories about the user |
|
||||
| `mem0_search` | Semantic search through memories (supports optional reranking via `rerank` and `top_k` parameters) |
|
||||
| `mem0_conclude` | Store a specific fact verbatim — uses `infer=False` so no server-side LLM extraction happens |
|
||||
| Tool | Description | Parameters |
|
||||
|------|-------------|------------|
|
||||
| `mem0_list` | List all stored memories, for a full overview | `page`, `page_size` (default 100, max 200) |
|
||||
| `mem0_search` | Semantic search by meaning, ranked by relevance | `query` (required), `top_k` (default 10, max 50), `rerank` (default `true`, Platform mode only) |
|
||||
| `mem0_add` | Store a fact verbatim, with no LLM extraction | `content` (required) |
|
||||
| `mem0_update` | Update a memory's text by ID | `memory_id`, `text` (both required) |
|
||||
| `mem0_delete` | Delete a memory by ID | `memory_id` (required) |
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -40,17 +47,19 @@ curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scri
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
The `mem0ai` Python package is automatically installed when you enable the Mem0 provider — no manual pip install needed.
|
||||
The `mem0ai` package is installed automatically when you enable the Mem0 provider, so there is no manual pip step. OSS providers may need extra packages (for example `qdrant-client`, `psycopg2-binary`, or `ollama`), which the setup flow installs for you when you pick them.
|
||||
|
||||
## Setup
|
||||
## Platform Setup
|
||||
|
||||
### Option 1: Interactive Setup Wizard (Recommended)
|
||||
Platform mode uses managed Mem0 Cloud and is the fastest way to start.
|
||||
|
||||
### Option 1: Interactive wizard (recommended)
|
||||
|
||||
```bash
|
||||
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`.
|
||||
Select **mem0**, choose **Platform**, and paste your API key when prompted. The wizard writes the non-secret settings to `~/.hermes/mem0.json` and keeps the key in `~/.hermes/.env`.
|
||||
|
||||
<Note>Get your API key from <a href="https://app.mem0.ai?utm_source=oss&utm_medium=integration-hermes" rel="nofollow">app.mem0.ai</a>.</Note>
|
||||
|
||||
@@ -68,33 +77,151 @@ memory:
|
||||
provider: mem0
|
||||
```
|
||||
|
||||
That's it — Mem0 runs automatically from this point.
|
||||
That's it. Mem0 runs automatically from here.
|
||||
|
||||
## Configuration Options
|
||||
## OSS (Self-Hosted) Setup
|
||||
|
||||
Configuration is stored in `~/.hermes/mem0.json`. Values can also be set via environment variables.
|
||||
OSS mode runs Mem0 entirely on your own infrastructure: your LLM, your embedder, and your vector store. No data is sent to Mem0 Cloud, and no Mem0 API key is required.
|
||||
|
||||
| Key | Env Variable | Default | Description |
|
||||
|-----|-------------|---------|-------------|
|
||||
| `api_key` | `MEM0_API_KEY` | — | **Required.** Mem0 Platform API key |
|
||||
| `user_id` | `MEM0_USER_ID` | `hermes-user` | User identifier for scoping memories |
|
||||
| `agent_id` | `MEM0_AGENT_ID` | `hermes` | Agent identifier |
|
||||
| `rerank` | — | `true` | Enable reranking for memory recall |
|
||||
### Interactive
|
||||
|
||||
```bash
|
||||
hermes memory setup
|
||||
# Select "mem0", then "Open Source (self-hosted)"
|
||||
# Follow the prompts for LLM, embedder, and vector store
|
||||
```
|
||||
|
||||
### With flags
|
||||
|
||||
```bash
|
||||
hermes memory setup mem0 --mode oss \
|
||||
--oss-llm openai --oss-llm-key sk-... \
|
||||
--oss-vector qdrant
|
||||
```
|
||||
|
||||
### Supported providers
|
||||
|
||||
| Component | Providers |
|
||||
|-----------|-----------|
|
||||
| LLM | `openai` (default model `gpt-5-mini`), `ollama` (local, default `llama3.1:8b`) |
|
||||
| Embedder | `openai` (default `text-embedding-3-small`), `ollama` (local, default `nomic-embed-text`) |
|
||||
| Vector store | `qdrant` (local path or server), `pgvector` |
|
||||
|
||||
### Flag reference
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--mode` | `platform` or `oss` |
|
||||
| `--oss-llm` | LLM provider (`openai` or `ollama`, default `openai`) |
|
||||
| `--oss-llm-key` | LLM API key (for `openai`) |
|
||||
| `--oss-llm-model` | Override the LLM model |
|
||||
| `--oss-llm-url` | LLM base URL (for `ollama` or a custom endpoint) |
|
||||
| `--oss-embedder` | Embedder provider (default `openai`) |
|
||||
| `--oss-embedder-key` | Embedder API key |
|
||||
| `--oss-vector` | Vector store (`qdrant` or `pgvector`, default `qdrant`) |
|
||||
| `--oss-vector-path` | Local Qdrant storage path |
|
||||
| `--oss-vector-host`, `--oss-vector-port` | PGVector or remote Qdrant host and port |
|
||||
| `--oss-vector-user`, `--oss-vector-password`, `--oss-vector-dbname` | PGVector connection details |
|
||||
| `--user-id` | Canonical user identifier |
|
||||
| `--dry-run` | Preview the resolved config without writing it |
|
||||
|
||||
## Switching Modes
|
||||
|
||||
You can move between Platform and OSS at any time. Run the setup command again, or edit `~/.hermes/mem0.json` directly.
|
||||
|
||||
```bash
|
||||
# Platform to OSS
|
||||
hermes memory setup mem0 --mode oss --oss-llm-key sk-...
|
||||
|
||||
# OSS to Platform
|
||||
hermes memory setup mem0 --mode platform --api-key sk-...
|
||||
|
||||
# Preview without writing anything
|
||||
hermes memory setup mem0 --mode oss --oss-llm-key sk-... --dry-run
|
||||
```
|
||||
|
||||
A self-hosted `~/.hermes/mem0.json` looks like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"mode": "oss",
|
||||
"oss": {
|
||||
"llm": {"provider": "openai", "config": {"model": "gpt-5-mini"}},
|
||||
"embedder": {"provider": "openai", "config": {"model": "text-embedding-3-small"}},
|
||||
"vector_store": {"provider": "qdrant", "config": {"path": "~/.hermes/mem0_qdrant"}}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Behavioral settings live in `~/.hermes/mem0.json` and are written for you by `hermes memory setup`. Only the secret `MEM0_API_KEY` belongs in `~/.hermes/.env`.
|
||||
|
||||
| Key | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `mode` | `platform` | `platform` (Mem0 Cloud) or `oss` (self-hosted) |
|
||||
| `api_key` | none | Mem0 Platform API key, required in Platform mode. Stored in `.env` as `MEM0_API_KEY` |
|
||||
| `user_id` | `hermes-user` | Identifier that scopes memories. See cross-channel behavior below |
|
||||
| `agent_id` | `hermes` | Agent identifier attached to writes |
|
||||
| `rerank` | `true` | Rerank search results for relevance (Platform mode only) |
|
||||
|
||||
### Cross-channel memories
|
||||
|
||||
Hermes can run from the CLI and from gateways like Telegram, Slack, and Discord. The `user_id` setting controls how memories are scoped across them:
|
||||
|
||||
- **Set a `user_id`** and it applies to every gateway, so one person gets a single merged memory store no matter where they talk to the agent.
|
||||
- **Leave it unset** (or at the default `hermes-user`) and each gateway uses its own native id, keeping per-platform memories separate.
|
||||
|
||||
Either way, every write is tagged with `metadata.channel` (for example `telegram` or `cli`), so per-channel views are still possible at query time.
|
||||
|
||||
|
||||
## Reliability
|
||||
|
||||
- **Circuit Breaker** — If Mem0's API fails 5 times in a row, Hermes stops calling it for 2 minutes, then retries. The agent keeps working fine without memory during that time.
|
||||
- **Non-blocking** — All Mem0 API calls happen in background daemon threads. A slow or failed API call never blocks your conversation.
|
||||
- **Thread-safe** — The Mem0 client uses lazy initialization with locking, safe for concurrent access.
|
||||
- **Circuit breaker**: if Mem0 fails five times in a row, Hermes pauses calls for two minutes, then retries. The agent keeps working without memory during that window. Expected client errors, like a 404 on a missing memory id, do not count toward tripping the breaker.
|
||||
- **Non-blocking**: every Mem0 call runs in a background daemon thread, so a slow or failed call never blocks your conversation.
|
||||
- **Thread-safe**: the client uses lazy initialization with locking, and the background sync and prefetch threads are guarded so concurrent gateway messages cannot produce duplicate memories.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Mem0 temporarily unavailable"
|
||||
|
||||
The circuit breaker tripped after five consecutive failures and resets after two minutes.
|
||||
|
||||
- **Platform mode**: check your API key and internet connection.
|
||||
- **OSS mode**: make sure your vector store (Qdrant or PGVector) is running and reachable.
|
||||
|
||||
### OSS: vector store connection refused
|
||||
|
||||
```bash
|
||||
# Local Qdrant: confirm the storage path is writable
|
||||
ls -la ~/.hermes/mem0_qdrant
|
||||
|
||||
# Qdrant server: confirm it is reachable
|
||||
curl http://localhost:6333/healthz
|
||||
|
||||
# PGVector: confirm PostgreSQL is accepting connections
|
||||
pg_isready -h localhost -p 5432
|
||||
```
|
||||
|
||||
### OSS: Ollama not reachable
|
||||
|
||||
```bash
|
||||
curl http://localhost:11434/api/tags
|
||||
```
|
||||
|
||||
### Memories not appearing
|
||||
|
||||
- `mem0_add` stores text verbatim with no extraction. Ordinary conversation turns are extracted automatically by the background sync.
|
||||
- Search is semantic, so try a broader query.
|
||||
- Confirm `user_id` is the same across sessions (check `~/.hermes/mem0.json`).
|
||||
|
||||
## Key Features
|
||||
|
||||
1. **Zero-Latency Recall** — Memories are prefetched in the background and cached, ready before you type
|
||||
2. **Server-side Extraction** — Mem0's API automatically extracts and deduplicates facts from each exchange
|
||||
3. **Non-blocking** — All API calls run in background daemon threads
|
||||
4. **Fault Tolerant** — Circuit breaker ensures the agent works even if Mem0 is temporarily unreachable
|
||||
5. **Additive Memory** — Works alongside Hermes' built-in file-based memory system (MEMORY.md, USER.md)
|
||||
1. **Two ways to run**: managed Platform or fully self-hosted OSS, switchable at any time.
|
||||
2. **Zero-latency recall**: memories are prefetched in the background and cached before you type.
|
||||
3. **Automatic extraction**: Mem0 extracts and deduplicates facts from each exchange for you.
|
||||
4. **Non-blocking and fault tolerant**: background threads plus a circuit breaker keep the agent responsive even when Mem0 is unreachable.
|
||||
5. **Additive memory**: works alongside Hermes' built-in file memory (`MEMORY.md`, `USER.md`).
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="OpenClaw Integration" icon={<svg width="24" height="24" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="m153.5 173.5q24.62 1.46 46 13.5 12.11 8.1 17.5 21.5 0.74 2.45 0.5 5 0.09 0.81 1 1 1.48-4.9 1-10 5.04 10.48 1.5 22-9.81 27.86-35.5 42.5-26.17 14.97-56 19.5-2.77-0.4-2 1 2.86 1.27 6 1 25.64 1.53 48.5-10 0.34 10.08 2 20 1.08 5.76 5 10 1 1.5 0 3-31.11 20.84-68.5 17.5-23.7-5.7-32.5-28.5-4.39-9.18-3.5-19 15.41 6.23 32 4.5-20.68-6.39-39-18-34.81-27.22-12.5-65.5 11.84-14.83 29-23 4.21 7.66 11.5 12.5 3 1 6 0-26.04-34.62-29-78-0.13-8.46 2-16.5 1 6.5 2 13 3.43 39.53 24.5 73 2.03 2.28 4.5 4 0.5-1.25 1-2.5-1.27-6.54-5-12 0.5-0.75 1-1.5 9.72-3.43 20-4 0.55 10.34 8 17.5 1.94 0.74 4 0.5-17.8-64.6 16.5-122 0.98-1.79 1.5 0-28.21 56.64-13.5 118 1.08 1.43 2.5 0.5 2.21-4.98 2-10.5z" fill="currentColor"/><path fill-rule="evenodd" d="m454.5 97.5q-1.33 11.18-8.5 20-21.81 26.28-55.5 32-1.11-0.2-2 0.5 2.31 2.82 5.5 4.5 1 2 0 4-9.56 11.3-19.5 20 19.71-8.72 31-27 2.68-0.43 5 1-14.24 30.97-48 36.5-9.93 1.71-20 1.5-6.8-0.48-13 1 5.81 6.92 14 11-10.78 16.03-27 26.5 27.16-7.4 38-33.5 4.34 1.35 9 1-9.08 23.84-33 33.5-18.45 6.41-38 7 22.59 8.92 45-1 12.05-5.52 24-11 9.01-1.79 17 2.5 5.28-4.38 11-8 12.8-6.07 27-5 0 0.5 0 1-19.34 2.69-34 15.5 0.5 0.25 1 0.5 17.79-8.09 36-15 2.71-0.79 5-2 2.5-1 5-2 5.53-4.04 11-8 11.7-4.18 24-6.5 7.78-1.36 15 1.5-2.97 18.45-13.5 34-34.92 49.37-94.5 62.5-59.27 12.45-108-23-15.53-12.52-21.5-31.5-2.47-14.26 4-27-3.15 24.41 14 42-4.92-10.28-7-22-1.97-17.63 7-33 47.28-69.5 125.5-100 15.86-3.42 32-5.5 18.63-1.47 37 1.5z" fill="currentColor"/><path fill-rule="evenodd" d="m231.5 238.5q1.31-0.2 2 1-3.13 28.62 15 51-16.25 6.75-27-7.5-1-1-2 0 14.73 29.34 46 18.5 1.79 0.52 0 1.5-37.63 16.82-50.5-22.5-5.1-26.48 16.5-42z" fill="currentColor"/><path fill-rule="evenodd" d="m203.5 266.5q1.31-0.2 2 1-2.48 22.08 12 39-6.99 1.35-14 0.5 4.59 4.08 10 7-8.71 0.28-14.5-6.5-16.98-22.76 4.5-41z" fill="currentColor"/><path fill-rule="evenodd" d="m58.5 284.5q9.6-2.17 14.5 6 5.15 14.18-1 28-11.05-13.14-27.5-17.5 5.15-9.9 14-16.5z" fill="currentColor"/><path fill-rule="evenodd" d="m56.5 313.5q3.43 5.43 8 10-4.88 0.44-8 4-1.11-0.2-2 0.5 28.91 1.65 38 28.5 0.45 3.16-1 6-11.02-7.01-23-12.5-4.75-3.75-9.5-7.5 1.47 7.42 7 13 8.34 27.18 32 43 0.99 2.41-1.5 3.5-40.25 5.58-66.5-25.5-15.67-22.01-8-48 10.46-23.87 34.5-15z" fill="currentColor"/><path fill-rule="evenodd" d="m198.5 319.5q1.44 0.68 2.5 2 2.41 8.23 6 16 1.2 2.64-0.5 5-30.65 21.41-68 18.5-25.16-6.17-32.5-30.5 6.96 4.99 15.5 6.5 8.99 0.75 18 0.5 16.25 2.38 32-2.5 15.9-3.94 27-15.5z" fill="currentColor"/><path fill-rule="evenodd" d="m239.5 342.5q7.02-0.25 14 0.5 4.46 1.06 8 3.5-5.2 2.35-10 5.5-3.88 4.65-9 7.5-9.89-3.09-9.5-13 2.36-3.63 6.5-4z" fill="currentColor"/><path fill-rule="evenodd" d="m214.5 349.5q5.96 7.2 13.5 13 1 1 0 2-28.58 23.34-65.5 20.5-18.15-4.24-27.5-19.5 1.13 0.94 2.5 1.5 14.7 1.42 29-1.5 26.57-0.52 48-16z" fill="currentColor"/><path fill-rule="evenodd" d="m302.5 373.5q0.21 2.44-2 3.5-28.69 7.6-50.5-12.5-0.06-6.71 6.5-9 4.45-0.75 9-1 22.26 2.27 37 19z" fill="currentColor"/><path fill-rule="evenodd" d="m232.5 365.5q17.6 6.19 10.5 23-10.6 10.42-25.5 11.5-25.94 3.21-49-9 36.75-1.65 64-25.5z" fill="currentColor"/><path fill-rule="evenodd" d="m113.5 367.5q7.7-0.01 9.5 7-9.69 7.19-18.5 15.5-7.23 5.76-5.5-3.5 3.12-12.84 14.5-19z" fill="currentColor"/><path fill-rule="evenodd" d="m126.5 380.5q7.88-0.4 12 6.5-8.5 7.25-17 14.5-5.62-12.55 5-21z" fill="currentColor"/><path fill-rule="evenodd" d="m283.5 385.5q3.22 2.95 7 5.5 2.8 4.03 6 7.5 0.42 2.77-2 4-15.5-9.75-31-19.5-1.79-0.98 0-1.5 9.96 2.49 20 4z" fill="currentColor"/></svg>} href="/integrations/openclaw">
|
||||
|
||||
@@ -98,20 +98,9 @@ add_result = add_tool.invoke(add_input)
|
||||
|
||||
```json Output
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"memory": "Name is Alex",
|
||||
"event": "ADD"
|
||||
},
|
||||
{
|
||||
"memory": "Is a vegetarian",
|
||||
"event": "ADD"
|
||||
},
|
||||
{
|
||||
"memory": "Is allergic to nuts",
|
||||
"event": "ADD"
|
||||
}
|
||||
]
|
||||
"message": "Memory processing has been queued for background execution",
|
||||
"status": "PENDING",
|
||||
"event_id": "3a1b2c3d-4e5f-6789-abcd-ef0123456789"
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
@@ -173,23 +162,25 @@ result = search_tool.invoke(search_input)
|
||||
```
|
||||
|
||||
```json Output
|
||||
[
|
||||
{
|
||||
"id": "1a75e827-7eca-45ea-8c5c-cfd43299f061",
|
||||
"memory": "Name is Alex",
|
||||
"user_id": "alex",
|
||||
"hash": "d0fccc8fa47f7a149ee95750c37bb0ca",
|
||||
"metadata": {
|
||||
"food": "vegan"
|
||||
},
|
||||
"categories": [
|
||||
"personal_details"
|
||||
],
|
||||
"created_at": "2024-11-27T16:53:43.276872-08:00",
|
||||
"updated_at": "2024-11-27T16:53:43.276885-08:00",
|
||||
"score": 0.3810526501504994
|
||||
}
|
||||
]
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"id": "1a75e827-7eca-45ea-8c5c-cfd43299f061",
|
||||
"memory": "Name is Alex",
|
||||
"user_id": "alex",
|
||||
"hash": "d0fccc8fa47f7a149ee95750c37bb0ca",
|
||||
"metadata": {
|
||||
"food": "vegan"
|
||||
},
|
||||
"categories": [
|
||||
"personal_details"
|
||||
],
|
||||
"created_at": "2024-11-27T16:53:43.276872-08:00",
|
||||
"updated_at": "2024-11-27T16:53:43.276885-08:00",
|
||||
"score": 0.3810526501504994
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ load_dotenv()
|
||||
# MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key
|
||||
|
||||
# Initialize LangChain and Mem0
|
||||
llm = ChatOpenAI(model="gpt-4")
|
||||
llm = ChatOpenAI(model="gpt-5-mini")
|
||||
mem0 = MemoryClient()
|
||||
```
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ async def websocket_endpoint(websocket: WebSocket):
|
||||
# LLM for response generation
|
||||
llm = OpenAILLMService(
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
model="gpt-3.5-turbo",
|
||||
model="gpt-5-mini",
|
||||
system_prompt="You are a helpful assistant that remembers past conversations."
|
||||
)
|
||||
|
||||
|
||||
@@ -26,12 +26,12 @@ Install the SDK provider and AI SDK:
|
||||
npm install @mem0/vercel-ai-provider ai@^6
|
||||
```
|
||||
|
||||
### Peer Dependencies
|
||||
### Dependencies
|
||||
|
||||
`@mem0/vercel-ai-provider` v3.0.0 requires:
|
||||
- `ai` v6+ (`^6.0.199`)
|
||||
- `@ai-sdk/provider` v3+ (`^3.0.10`)
|
||||
- Provider packages at v3+: `@ai-sdk/openai@^3`, `@ai-sdk/anthropic@^3`, `@ai-sdk/google@^3`, `@ai-sdk/groq@^3`, `@ai-sdk/cohere@^3`
|
||||
`@mem0/vercel-ai-provider` bundles `ai`, all `@ai-sdk/*` provider packages, and `@ai-sdk/provider` as regular dependencies — you do **not** need to install them separately. The install command above (`npm install @mem0/vercel-ai-provider ai@^6`) is sufficient.
|
||||
|
||||
The only true peer dependency is `zod` (optional):
|
||||
- `zod` v3+ (`^3.0.0`) — required only if you use Zod schemas in tool definitions
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -305,6 +305,8 @@ These options can be passed per-request when creating a model instance:
|
||||
| `rerank` | `boolean` | Enable reranking of results |
|
||||
| `page` | `number` | Page number for pagination |
|
||||
| `page_size` | `number` | Results per page |
|
||||
| `mem0ApiKey` | `string` | Mem0 API key; overrides the `MEM0_API_KEY` env var |
|
||||
| `host` | `string` | Custom Mem0 API base URL for self-hosted deployments |
|
||||
|
||||
## Key Features
|
||||
|
||||
@@ -312,6 +314,7 @@ These options can be passed per-request when creating a model instance:
|
||||
- `retrieveMemories()`: Retrieves memory context for prompts as a formatted system prompt string.
|
||||
- `getMemories()`: Get memories from your profile in array format.
|
||||
- `addMemories()`: Adds user memories to enhance contextual responses.
|
||||
- `searchMemories()`: Searches memories and returns the raw results array (semantic search rather than the full retrieval pipeline).
|
||||
|
||||
## Migrating from v2.x
|
||||
|
||||
|
||||
+7
-3
@@ -367,6 +367,8 @@ All API Reference docs describe Mem0 Platform REST endpoints (requires API key).
|
||||
- [Get Organization](https://docs.mem0.ai/api-reference/organization/get-org) [Platform]: Use when fetching one org.
|
||||
- [Get Organization Members](https://docs.mem0.ai/api-reference/organization/get-org-members) [Platform]: Use when listing org members.
|
||||
- [Add Organization Member](https://docs.mem0.ai/api-reference/organization/add-org-member) [Platform]: Use when inviting a member to an org.
|
||||
- [Update Organization Member](https://docs.mem0.ai/api-reference/organization/update-org-member) [Platform]: Use when updating an org member's role.
|
||||
- [Remove Organization Member](https://docs.mem0.ai/api-reference/organization/remove-org-member) [Platform]: Use when removing a member from an organization.
|
||||
- [Delete Organization](https://docs.mem0.ai/api-reference/organization/delete-org) [Platform]: Use when removing an org.
|
||||
|
||||
### Projects
|
||||
@@ -375,6 +377,9 @@ All API Reference docs describe Mem0 Platform REST endpoints (requires API key).
|
||||
- [Get Project](https://docs.mem0.ai/api-reference/project/get-project) [Platform]: Use when fetching one project.
|
||||
- [Get Project Members](https://docs.mem0.ai/api-reference/project/get-project-members) [Platform]: Use when listing project members.
|
||||
- [Add Project Member](https://docs.mem0.ai/api-reference/project/add-project-member) [Platform]: Use when inviting a member to a project.
|
||||
- [Update Project](https://docs.mem0.ai/api-reference/project/update-project) [Platform]: Use when updating project settings.
|
||||
- [Update Project Member](https://docs.mem0.ai/api-reference/project/update-project-member) [Platform]: Use when updating a project member's role.
|
||||
- [Remove Project Member](https://docs.mem0.ai/api-reference/project/remove-project-member) [Platform]: Use when removing a member from a project.
|
||||
- [Delete Project](https://docs.mem0.ai/api-reference/project/delete-project) [Platform]: Use when removing a project.
|
||||
|
||||
### Webhooks
|
||||
@@ -460,6 +465,7 @@ Everything below is OSS-only provider configuration. Skip this entire section wh
|
||||
- [LM Studio Embeddings](https://docs.mem0.ai/components/embedders/models/lmstudio) [OSS]: Use when embeddings run through LM Studio.
|
||||
- [Together Embeddings](https://docs.mem0.ai/components/embedders/models/together) [OSS]: Use when embeddings run on Together.
|
||||
- [LangChain Embeddings](https://docs.mem0.ai/components/embedders/models/langchain) [OSS]: Use when embeddings are wrapped behind a LangChain adapter.
|
||||
- [FastEmbed](https://docs.mem0.ai/components/embedders/models/fastembed) [OSS]: Use when embeddings run locally via FastEmbed (ONNX).
|
||||
|
||||
### Vector Databases [OSS]
|
||||
- [Vector Database Overview](https://docs.mem0.ai/components/vectordbs/overview) [OSS]: Use when choosing a vector store.
|
||||
@@ -498,7 +504,5 @@ Everything below is OSS-only provider configuration. Skip this entire section wh
|
||||
- [Custom Reranker Prompts](https://docs.mem0.ai/components/rerankers/custom-prompts) [OSS]: Use when rewriting reranker prompts.
|
||||
- [Cohere Reranker](https://docs.mem0.ai/components/rerankers/models/cohere) [OSS]: Use for Cohere Rerank.
|
||||
- [Sentence Transformer Reranker](https://docs.mem0.ai/components/rerankers/models/sentence_transformer) [OSS]: Use for local cross-encoder rerankers.
|
||||
- [Hugging Face Reranker](https://docs.mem0.ai/components/rerankers/models/huggingface) [OSS]: Use for HF-hosted reranker models.
|
||||
- [LLM Reranker (prompt)](https://docs.mem0.ai/components/rerankers/models/llm) [OSS]: Use when the reranker is a prompted LLM (config guide).
|
||||
- [LLM Reranker](https://docs.mem0.ai/components/rerankers/models/llm_reranker) [OSS]: Use when the reranker is a prompted LLM (implementation reference).
|
||||
- [Hugging Face Reranker](https://docs.mem0.ai/components/rerankers/models/huggingface) [OSS]: Use for HF-hosted reranker models.- [LLM Reranker](https://docs.mem0.ai/components/rerankers/models/llm_reranker) [OSS]: Use when the reranker is a prompted LLM (implementation reference).
|
||||
- [Zero Entropy Reranker](https://docs.mem0.ai/components/rerankers/models/zero_entropy) [OSS]: Use for the Zero Entropy reranker.
|
||||
|
||||
@@ -62,7 +62,8 @@ def add(
|
||||
filters: dict = None,
|
||||
output_format: str = None, # ❌ REMOVED
|
||||
version: str = None # ❌ REMOVED
|
||||
) -> Union[List[dict], dict]
|
||||
) -> Union[List[dict], dict]:
|
||||
...
|
||||
```
|
||||
|
||||
#### v1.0.0 Signature
|
||||
@@ -76,7 +77,8 @@ def add(
|
||||
metadata: dict = None,
|
||||
filters: dict = None,
|
||||
infer: bool = True # ✅ NEW: Control memory inference
|
||||
) -> dict # Always returns dict with "results" key
|
||||
) -> dict: # Always returns dict with "results" key
|
||||
...
|
||||
```
|
||||
|
||||
#### Changes Summary
|
||||
@@ -147,7 +149,8 @@ def search(
|
||||
filters: dict = None, # Basic key-value only
|
||||
output_format: str = None, # ❌ REMOVED
|
||||
version: str = None # ❌ REMOVED
|
||||
) -> Union[List[dict], dict]
|
||||
) -> Union[List[dict], dict]:
|
||||
...
|
||||
```
|
||||
|
||||
#### v1.0.0 Signature
|
||||
@@ -161,7 +164,8 @@ def search(
|
||||
limit: int = 100,
|
||||
filters: dict = None, # ✅ ENHANCED: Advanced operators
|
||||
rerank: bool = True # ✅ NEW: Reranking support
|
||||
) -> dict # Always returns dict with "results" key
|
||||
) -> dict: # Always returns dict with "results" key
|
||||
...
|
||||
```
|
||||
|
||||
#### Enhanced Filtering
|
||||
@@ -216,7 +220,8 @@ def get_all(
|
||||
filters: dict = None,
|
||||
output_format: str = None, # ❌ REMOVED
|
||||
version: str = None # ❌ REMOVED
|
||||
) -> Union[List[dict], dict]
|
||||
) -> Union[List[dict], dict]:
|
||||
...
|
||||
```
|
||||
|
||||
#### v1.0.0 Signature
|
||||
@@ -227,7 +232,8 @@ def get_all(
|
||||
agent_id: str = None,
|
||||
run_id: str = None,
|
||||
filters: dict = None # ✅ ENHANCED: Advanced operators
|
||||
) -> dict # Always returns dict with "results" key
|
||||
) -> dict: # Always returns dict with "results" key
|
||||
...
|
||||
```
|
||||
|
||||
### update() Method
|
||||
@@ -239,7 +245,8 @@ def update(
|
||||
self,
|
||||
memory_id: str,
|
||||
data: str
|
||||
) -> dict
|
||||
) -> dict:
|
||||
...
|
||||
```
|
||||
|
||||
### delete() Method
|
||||
@@ -250,7 +257,8 @@ def update(
|
||||
def delete(
|
||||
self,
|
||||
memory_id: str
|
||||
) -> dict
|
||||
) -> dict:
|
||||
...
|
||||
```
|
||||
|
||||
### delete_all() Method
|
||||
@@ -344,7 +352,7 @@ config = {
|
||||
### New Configuration Options
|
||||
|
||||
#### Reranker Configuration
|
||||
```python
|
||||
```text
|
||||
# Cohere reranker
|
||||
"reranker": {
|
||||
"provider": "cohere",
|
||||
@@ -563,4 +571,4 @@ results = m.search(
|
||||
|
||||
<Info>
|
||||
Use this reference to systematically update your codebase. Test each change thoroughly before deploying to production.
|
||||
</Info>
|
||||
</Info>
|
||||
|
||||
@@ -62,7 +62,7 @@ These changes produce a **+20 point improvement on LoCoMo** (71.4 → 91.6) and
|
||||
|---|---|---|---|
|
||||
| Constructor | `MemoryClient(api_key, org_id, project_id)` | `MemoryClient(api_key)` | Remove `org_id`, `project_id` from constructor |
|
||||
| Method options | `client.add(messages, **kwargs)` | `client.add(messages, options=AddMemoryOptions(...))` | Use typed option classes (or `**kwargs` still works) |
|
||||
| Removed params | `api_version`, `output_format`, `async_mode`, `filter_memories`, `expiration_date`, `keyword_search`, `force_add_only`, `batch_size`, `immutable`, `includes`, `excludes`, `enable_graph`, `org_name`, `project_name` | — | Remove from all calls |
|
||||
| Removed params | `api_version`, `output_format`, `async_mode`, `filter_memories`, `keyword_search`, `force_add_only`, `batch_size`, `immutable`, `includes`, `excludes`, `enable_graph`, `org_name`, `project_name` | — | Remove from all calls |
|
||||
|
||||
### TypeScript Client SDK
|
||||
|
||||
@@ -70,7 +70,7 @@ These changes produce a **+20 point improvement on LoCoMo** (71.4 → 91.6) and
|
||||
|---|---|---|---|
|
||||
| Constructor | `new MemoryClient({ apiKey, organizationId, projectId })` | `new MemoryClient({ apiKey })` | Remove `organizationId`, `projectId`, `organizationName`, `projectName` |
|
||||
| All params | snake_case: `user_id`, `agent_id`, `top_k` | camelCase: `userId`, `agentId`, `topK` | Rename all params to camelCase |
|
||||
| Removed params | `api_version`, `output_format`, `async_mode`, `enable_graph`, `org_id`, `project_id`, `org_name`, `project_name`, `filter_memories`, `batch_size`, `force_add_only`, `immutable`, `expiration_date`, `includes`, `excludes`, `keyword_search` | — | Remove from all calls |
|
||||
| Removed params | `api_version`, `output_format`, `async_mode`, `enable_graph`, `org_id`, `project_id`, `org_name`, `project_name`, `filter_memories`, `batch_size`, `force_add_only`, `immutable`, `includes`, `excludes`, `keyword_search` | — | Remove from all calls |
|
||||
| Output format enum | `OutputFormat.V1`, `OutputFormat.V1_1` | Removed | v1.1 is now always used |
|
||||
| API version enum | `API_VERSION.V1`, `API_VERSION.V2` | Removed | Handled internally |
|
||||
|
||||
@@ -423,7 +423,7 @@ These parameters have been removed across all SDKs. Remove them from your code:
|
||||
|
||||
**All methods:** `api_version`, `output_format`, `async_mode`, `org_name`, `project_name`, `org_id`, `project_id`
|
||||
|
||||
**add():** `enable_graph`, `immutable`, `expiration_date`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search`
|
||||
**add():** `enable_graph`, `immutable`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search`
|
||||
|
||||
**search():** `enable_graph`
|
||||
|
||||
@@ -437,7 +437,7 @@ These parameters have been removed across all SDKs. Remove them from your code:
|
||||
|
||||
**All methods:** `OutputFormat` enum, `API_VERSION` enum
|
||||
|
||||
**add():** `enable_graph` / `enableGraph`, `async_mode` / `asyncMode`, `output_format` / `outputFormat`, `immutable`, `expiration_date` / `expirationDate`, `filter_memories` / `filterMemories`, `batch_size` / `batchSize`, `force_add_only` / `forceAddOnly`, `includes`, `excludes`, `keyword_search` / `keywordSearch`
|
||||
**add():** `enable_graph` / `enableGraph`, `async_mode` / `asyncMode`, `output_format` / `outputFormat`, `immutable`, `filter_memories` / `filterMemories`, `batch_size` / `batchSize`, `force_add_only` / `forceAddOnly`, `includes`, `excludes`, `keyword_search` / `keywordSearch`
|
||||
|
||||
**search():** `enable_graph` / `enableGraph`
|
||||
|
||||
|
||||
@@ -215,7 +215,7 @@ client.add(messages, user_id="alice")
|
||||
# async_mode and output_format removed (async by default, v1.1 always)
|
||||
```
|
||||
|
||||
**Removed parameters:** `org_id`, `project_id`, `api_version`, `output_format`, `async_mode`, `enable_graph`, `immutable`, `expiration_date`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search`, `org_name`, `project_name`
|
||||
**Removed parameters:** `org_id`, `project_id`, `api_version`, `output_format`, `async_mode`, `enable_graph`, `immutable`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search`, `org_name`, `project_name`
|
||||
|
||||
### TypeScript Client SDK
|
||||
|
||||
@@ -242,7 +242,7 @@ await client.search("query", {
|
||||
});
|
||||
```
|
||||
|
||||
**Removed:** `OutputFormat` enum, `API_VERSION` enum, `organizationId`, `projectId`, `organizationName`, `projectName`, `enableGraph`, `asyncMode`, `outputFormat`, `immutable`, `expirationDate`, `filterMemories`, `batchSize`, `forceAddOnly`, `includes`, `excludes`, `keywordSearch`
|
||||
**Removed:** `OutputFormat` enum, `API_VERSION` enum, `organizationId`, `projectId`, `organizationName`, `projectName`, `enableGraph`, `asyncMode`, `outputFormat`, `immutable`, `filterMemories`, `batchSize`, `forceAddOnly`, `includes`, `excludes`, `keywordSearch`
|
||||
|
||||
<Info>
|
||||
For the full list of parameter changes across all SDKs, see the [OSS migration guide](/migration/oss-v2-to-v3#removed-parameters-reference).
|
||||
|
||||
@@ -130,7 +130,7 @@ memory = Memory.from_config_file("config.yaml")
|
||||
</Tabs>
|
||||
|
||||
<Info icon="check">
|
||||
Run `memory.add(["Remember my favorite cafe in Tokyo."], user_id="alex")` and then `memory.search("favorite cafe", filters={"user_id": "alex"})`. You should see the Qdrant collection populate and the reranker mark the memory as a top hit.
|
||||
Run `memory.add("Remember my favorite cafe in Tokyo.", user_id="alex")` and then `memory.search("favorite cafe", filters={"user_id": "alex"})`. You should see the Qdrant collection populate and the reranker mark the memory as a top hit.
|
||||
</Info>
|
||||
|
||||
## Tune component settings
|
||||
|
||||
@@ -18,7 +18,7 @@ icon: "bolt"
|
||||
</Warning>
|
||||
|
||||
<Note>
|
||||
Working in TypeScript? The Node SDK still uses synchronous calls—use `Memory` there and rely on Python’s `AsyncMemory` when you need awaited operations.
|
||||
Working in TypeScript? The OSS `Memory` class in the Node SDK (`mem0ai/oss`) is also fully async — every method returns a `Promise` and must be `await`ed. Python’s `AsyncMemory` serves the same purpose within Python async frameworks like FastAPI. Both runtimes support awaited memory operations; choose the SDK that matches your language.
|
||||
</Note>
|
||||
|
||||
## Feature anatomy
|
||||
|
||||
@@ -165,8 +165,7 @@ await memory.add("Yesterday, I ordered a laptop, the order id is 12345", { userI
|
||||
{"memory": "Ordered a laptop", "event": "ADD"},
|
||||
{"memory": "Order ID: 12345", "event": "ADD"},
|
||||
{"memory": "Order placed yesterday", "event": "ADD"}
|
||||
],
|
||||
"relations": []
|
||||
]
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
@@ -188,8 +187,7 @@ await memory.add("I like going to hikes", { userId: "user123" });
|
||||
|
||||
```json Output
|
||||
{
|
||||
"results": [],
|
||||
"relations": []
|
||||
"results": []
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
@@ -41,6 +41,14 @@ Multimodal support lets Mem0 extract facts from images alongside regular text. A
|
||||
|
||||
## Configure it
|
||||
|
||||
<Warning>
|
||||
You must set `enable_vision: True` in your LLM config for image content to be processed. Without it, image turns are silently dropped and no vision memories are created. Example:
|
||||
```python
|
||||
config = {"llm": {"provider": "openai", "config": {"enable_vision": True, "vision_details": "auto"}}}
|
||||
client = Memory.from_config(config)
|
||||
```
|
||||
</Warning>
|
||||
|
||||
### Add image messages from URLs
|
||||
|
||||
<CodeGroup>
|
||||
@@ -66,7 +74,7 @@ client.add(messages, user_id="alice")
|
||||
```
|
||||
|
||||
```ts TypeScript
|
||||
import { Memory } from "mem0ai";
|
||||
import { Memory } from "mem0ai/oss";
|
||||
|
||||
const client = new Memory();
|
||||
|
||||
@@ -123,7 +131,7 @@ client.add(messages, user_id="alice")
|
||||
|
||||
```ts TypeScript
|
||||
import fs from "fs";
|
||||
import { Memory } from "mem0ai";
|
||||
import { Memory } from "mem0ai/oss";
|
||||
|
||||
function encodeImage(imagePath: string) {
|
||||
const buffer = fs.readFileSync(imagePath);
|
||||
@@ -226,7 +234,7 @@ client.add(messages, user_id="user123")
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
from mem0 import Memory
|
||||
from mem0.exceptions import InvalidImageError, FileSizeError
|
||||
from mem0.exceptions import ValidationError
|
||||
|
||||
client = Memory()
|
||||
|
||||
@@ -242,16 +250,14 @@ try:
|
||||
client.add(messages, user_id="user123")
|
||||
print("Image processed successfully")
|
||||
|
||||
except InvalidImageError:
|
||||
print("Invalid image format or corrupted file")
|
||||
except FileSizeError:
|
||||
print("Image file too large")
|
||||
except ValidationError as exc:
|
||||
print(f"Image validation error: {exc}")
|
||||
except Exception as exc:
|
||||
print(f"Unexpected error: {exc}")
|
||||
```
|
||||
|
||||
```ts TypeScript
|
||||
import { Memory } from "mem0ai";
|
||||
import { Memory } from "mem0ai/oss";
|
||||
|
||||
const client = new Memory();
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ config = {
|
||||
"provider": "llm_reranker",
|
||||
"config": {
|
||||
"provider": "openai",
|
||||
"model": "gpt-4o-mini",
|
||||
"model": "gpt-5-mini",
|
||||
"api_key": "your-openai-api-key",
|
||||
"top_k": 5
|
||||
}
|
||||
@@ -150,7 +150,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4",
|
||||
"model": "gpt-5-mini",
|
||||
"api_key": "your-openai-api-key"
|
||||
}
|
||||
},
|
||||
|
||||
+23
-1
@@ -1779,6 +1779,11 @@
|
||||
"type": "object",
|
||||
"description": "Entity and metadata filters. Must include at least one entity ID (`user_id`, `agent_id`, `app_id`, or `run_id`).",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"show_expired": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "When true, include memories whose `expiration_date` has passed. Expired memories are hidden by default."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1977,6 +1982,12 @@
|
||||
"additionalProperties": true,
|
||||
"description": "User-supplied metadata to attach to each extracted memory."
|
||||
},
|
||||
"expiration_date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"nullable": true,
|
||||
"description": "Optional expiration date in YYYY-MM-DD format. After this date, memories are hidden from search and get-all unless `show_expired` is true."
|
||||
},
|
||||
"custom_instructions": {
|
||||
"type": "string",
|
||||
"description": "Project-level instructions that guide extraction for this call."
|
||||
@@ -2094,6 +2105,11 @@
|
||||
"description": "Entity and metadata filters. Must include at least one entity ID (`user_id`, `agent_id`, `app_id`, or `run_id`). Supports `AND`, `OR`, `NOT`, and comparison operators (`in`, `gte`, `lte`, `gt`, `lt`, `contains`, `icontains`, `ne`).",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"show_expired": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "When true, include memories whose `expiration_date` has passed. Expired memories are hidden by default."
|
||||
},
|
||||
"top_k": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
@@ -2432,6 +2448,12 @@
|
||||
"metadata": {
|
||||
"type": "object",
|
||||
"description": "Additional metadata associated with the memory"
|
||||
},
|
||||
"expiration_date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"nullable": true,
|
||||
"description": "Expiration date in YYYY-MM-DD format, or null to clear the expiration date."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6256,4 +6278,4 @@
|
||||
}
|
||||
},
|
||||
"x-original-swagger-version": "2.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ results_without_criteria = client.search(
|
||||
### Compare Results
|
||||
|
||||
### Search Results (with Criteria)
|
||||
```python
|
||||
```text
|
||||
[
|
||||
{"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.666, ...},
|
||||
{"memory": "User finally has time to draw something after a long time", "score": 0.616, ...},
|
||||
@@ -128,7 +128,7 @@ results_without_criteria = client.search(
|
||||
```
|
||||
|
||||
### Search Results (without Criteria)
|
||||
```python
|
||||
```text
|
||||
[
|
||||
{"memory": "User is happy today", "score": 0.607, ...},
|
||||
{"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.512, ...},
|
||||
|
||||
@@ -190,7 +190,7 @@ messages = [
|
||||
client.add(messages, user_id='alice')
|
||||
```
|
||||
|
||||
```python Memories with categories
|
||||
```text Memories with categories
|
||||
# Following categories will be created for the memories added
|
||||
Sometimes draws and sketches in free time (hobbies)
|
||||
Is quite athletic (sports)
|
||||
|
||||
@@ -108,10 +108,10 @@ print(response)
|
||||
|
||||
```javascript JavaScript
|
||||
// Basic Export request
|
||||
const filters = {"user_id": "alice"};
|
||||
const basicFilters = {"user_id": "alice"};
|
||||
const response = await client.createMemoryExport({
|
||||
schema: json_schema,
|
||||
filters: filters
|
||||
filters: basicFilters
|
||||
});
|
||||
|
||||
// Export with custom instructions and additional filters
|
||||
@@ -124,16 +124,16 @@ const export_instructions = `
|
||||
`;
|
||||
|
||||
// For create operation, using only user_id filter as requested
|
||||
const filters = {
|
||||
const exportFilters = {
|
||||
"AND": [
|
||||
{"user_id": "alex"},
|
||||
{"created_at": {"gte": "2024-01-01"}}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
const responseWithInstructions = await client.createMemoryExport({
|
||||
schema: json_schema,
|
||||
filters: filters,
|
||||
filters: exportFilters,
|
||||
exportInstructions: export_instructions
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0",
|
||||
"version": "0.2.10",
|
||||
"version": "0.2.11",
|
||||
"description": "Persistent memory for Claude Code. Remembers decisions, patterns, and preferences across sessions.",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0",
|
||||
"version": "0.2.10",
|
||||
"version": "0.2.11",
|
||||
"description": "Persistent memory for Codex. Remembers decisions, patterns, and preferences across sessions.",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0",
|
||||
"version": "0.2.10",
|
||||
"version": "0.2.11",
|
||||
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search using the Mem0 Platform MCP server.",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
All notable changes to the Mem0 plugin will be documented in this file.
|
||||
|
||||
## 0.2.11 — Session-summary metadata fix + rerank auto-injected context by default
|
||||
|
||||
> Versions: Claude Code / Cursor / Codex `0.2.11`; Antigravity `0.1.3`. All four editors share `scripts/`, so the fix below applies to every editor.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`files_touched` was double-JSON-encoded in session summaries (`scripts/capture_session_summary.py`):** the Stop-hook summary set `metadata["files_touched"] = json.dumps(files[:20])` — a pre-serialized JSON string — and then serialized the whole request body again with `json.dumps(body)`. The stored memory therefore carried an escaped string blob (`"[\"mem0/memory/main.py\", \"src/client/index.ts\"]"`) instead of a real array, so file paths surfaced as backslash- and slash-heavy escaped text when those memories were returned by `search_memories`/`get_memories` and shown in Claude Code, Cursor, Codex, and Antigravity. The fix stores the list directly (`metadata["files_touched"] = files[:20]`) so the body is encoded exactly once. New `tests/test_capture_session_summary.py` asserts the posted body contains a JSON array and no escaped-string artifact.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Auto-injected memory context is now reranked by default (`scripts/_search.py`, `scripts/file_context.py`, `scripts/on_bash_output.sh`, `scripts/on_user_prompt.sh`):** the REST search endpoint does not rerank when `rerank` is omitted, so hook-injected context (file-context, bash-error lookup, session-resume prefetch) was ordered by raw vector similarity and the single most relevant memory could fall outside the injected `top_k` window. A new `should_rerank()` helper turns reranking on for every auto-injection path; the extra ~150–200 ms stays within the hook's curl budget. Opt out with `MEM0_RERANK=0` (also accepts `false`/`no`/`off`). (#5690)
|
||||
|
||||
## 0.2.10 — Accurate per-editor telemetry attribution
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "mem0",
|
||||
"name": "mem0",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"description": "Persistent semantic memory for Antigravity agents. Cross-session, user-level recall via the Mem0 Platform MCP server. 16 slash commands, lifecycle hooks for auto-capture and metadata enforcement.",
|
||||
"author": { "name": "Mem0", "email": "support@mem0.ai" },
|
||||
"publisher": "mem0ai",
|
||||
|
||||
@@ -173,7 +173,7 @@ def store_summary(
|
||||
if branch:
|
||||
metadata["branch"] = branch
|
||||
if files:
|
||||
metadata["files_touched"] = json.dumps(files[:20])
|
||||
metadata["files_touched"] = files[:20]
|
||||
|
||||
body = {
|
||||
"messages": [{"role": "user", "content": summary_prompt}],
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Regression tests for capture_session_summary.py request body construction.
|
||||
|
||||
Guards against the double-JSON-encoding bug where ``files_touched`` was stored
|
||||
as a pre-serialized JSON string and then encoded a second time with the rest of
|
||||
the request body — surfacing as escaped, slash-heavy blobs in the memories shown
|
||||
inside Claude Code / Cursor / Codex / Antigravity (all four editors share this
|
||||
script).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
|
||||
class _FakeResp:
|
||||
status = 200
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
return False
|
||||
|
||||
|
||||
def _capture_request_body(monkeypatch):
|
||||
"""Patch urlopen so store_summary posts nowhere; capture the request body."""
|
||||
import capture_session_summary as css
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
def fake_urlopen(req, timeout=0):
|
||||
captured["raw"] = req.data.decode("utf-8")
|
||||
captured["body"] = json.loads(captured["raw"])
|
||||
return _FakeResp()
|
||||
|
||||
monkeypatch.setattr(css.urllib.request, "urlopen", fake_urlopen)
|
||||
return captured, css
|
||||
|
||||
|
||||
def test_files_touched_is_json_array_not_double_encoded(monkeypatch):
|
||||
"""files_touched must be a real JSON array, encoded exactly once."""
|
||||
captured, css = _capture_request_body(monkeypatch)
|
||||
files = ["mem0/memory/main.py", "src/client/index.ts"]
|
||||
|
||||
css.store_summary(
|
||||
api_key="test-key",
|
||||
summary_prompt="did some work",
|
||||
user_id="u1",
|
||||
session_id="s1",
|
||||
project_id="p1",
|
||||
branch="main",
|
||||
files=files,
|
||||
)
|
||||
|
||||
files_touched = captured["body"]["metadata"]["files_touched"]
|
||||
assert isinstance(files_touched, list), (
|
||||
"files_touched must be a JSON array, not a double-encoded string; "
|
||||
f"got {type(files_touched).__name__}: {files_touched!r}"
|
||||
)
|
||||
assert files_touched == files
|
||||
# The file paths must not appear as an escaped JSON string inside the body.
|
||||
assert '\\"' not in captured["raw"]
|
||||
|
||||
|
||||
def test_files_touched_omitted_when_no_files(monkeypatch):
|
||||
"""No files touched -> no files_touched key (unchanged behaviour)."""
|
||||
captured, css = _capture_request_body(monkeypatch)
|
||||
|
||||
css.store_summary(
|
||||
api_key="test-key",
|
||||
summary_prompt="did some work",
|
||||
user_id="u1",
|
||||
session_id="s1",
|
||||
project_id="p1",
|
||||
branch="main",
|
||||
files=[],
|
||||
)
|
||||
|
||||
assert "files_touched" not in captured["body"]["metadata"]
|
||||
@@ -71,7 +71,8 @@
|
||||
"picomatch@<2.3.2": "^2.3.2",
|
||||
"@qdrant/js-client-rest": "^1.18.0",
|
||||
"uuid@<11.1.1": ">=11.1.1",
|
||||
"esbuild": ">=0.28.1"
|
||||
"esbuild": ">=0.28.1",
|
||||
"undici@<6.27.0": ">=6.27.0 <8.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+6
-5
@@ -13,6 +13,7 @@ overrides:
|
||||
'@qdrant/js-client-rest': ^1.18.0
|
||||
uuid@<11.1.1: '>=11.1.1'
|
||||
esbuild: '>=0.28.1'
|
||||
undici@<6.27.0: '>=6.27.0 <8.0.0'
|
||||
|
||||
importers:
|
||||
|
||||
@@ -1996,9 +1997,9 @@ packages:
|
||||
undici-types@6.21.0:
|
||||
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
|
||||
|
||||
undici@6.26.0:
|
||||
resolution: {integrity: sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A==}
|
||||
engines: {node: '>=18.17'}
|
||||
undici@7.28.0:
|
||||
resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}
|
||||
engines: {node: '>=20.18.1'}
|
||||
|
||||
util-deprecate@1.0.2:
|
||||
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
|
||||
@@ -2509,7 +2510,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@qdrant/openapi-typescript-fetch': 1.2.6
|
||||
typescript: 5.9.3
|
||||
undici: 6.26.0
|
||||
undici: 7.28.0
|
||||
|
||||
'@qdrant/openapi-typescript-fetch@1.2.6': {}
|
||||
|
||||
@@ -4063,7 +4064,7 @@ snapshots:
|
||||
|
||||
undici-types@6.21.0: {}
|
||||
|
||||
undici@6.26.0: {}
|
||||
undici@7.28.0: {}
|
||||
|
||||
util-deprecate@1.0.2: {}
|
||||
|
||||
|
||||
@@ -21,3 +21,4 @@ overrides:
|
||||
"@qdrant/js-client-rest": "^1.18.0"
|
||||
"uuid@<11.1.1": ">=11.1.1"
|
||||
"esbuild": ">=0.28.1"
|
||||
"undici@<6.27.0": ">=6.27.0 <8.0.0"
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
safePath,
|
||||
normalizeModuleUrlToPath,
|
||||
loadSkill,
|
||||
loadTriagePrompt,
|
||||
loadCompactTriagePrompt,
|
||||
} from "./skill-loader.ts";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// safePath — path containment
|
||||
@@ -74,6 +76,31 @@ describe("loadSkill path traversal", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeModuleUrlToPath", () => {
|
||||
it("normalizes raw Windows paths before fileURLToPath conversion", () => {
|
||||
const rawWindowsMetaUrl = "C:\\Users\\example\\openclaw\\index.ts";
|
||||
const result = normalizeModuleUrlToPath(rawWindowsMetaUrl);
|
||||
// Assert the decoded property directly rather than reconstructing via the function body
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result).not.toContain("%5C");
|
||||
});
|
||||
|
||||
it("leaves already-correct file URLs unchanged", () => {
|
||||
const fileMetaUrl = "file:///C:/Users/example/openclaw/index.ts";
|
||||
const expected = fileURLToPath(fileMetaUrl);
|
||||
|
||||
expect(normalizeModuleUrlToPath(fileMetaUrl)).toBe(expected);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"passes POSIX absolute paths through unchanged",
|
||||
() => {
|
||||
const posixPath = "/home/user/openclaw/index.ts";
|
||||
expect(normalizeModuleUrlToPath(posixPath)).toBe(posixPath);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("loadCompactTriagePrompt", () => {
|
||||
it("keeps the core triage instructions without inlining the full skill body", () => {
|
||||
const prompt = loadCompactTriagePrompt();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import * as path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import type { SkillsConfig, CategoryConfig } from "./types.ts";
|
||||
import { readText, exists } from "./fs-safe.ts";
|
||||
|
||||
@@ -84,6 +84,14 @@ function parseSkillFile(content: string): ParsedSkill {
|
||||
};
|
||||
}
|
||||
|
||||
/** @internal — exported for testing only */
|
||||
export function normalizeModuleUrlToPath(moduleUrl: string): string {
|
||||
const normalizedUrl = moduleUrl.startsWith("file:")
|
||||
? moduleUrl
|
||||
: pathToFileURL(moduleUrl).toString();
|
||||
return fileURLToPath(normalizedUrl);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Skill Loader
|
||||
// ============================================================================
|
||||
@@ -96,7 +104,7 @@ function resolveSkillsDir(): string {
|
||||
|
||||
// Strategy 1: import.meta.url (works in native ESM)
|
||||
try {
|
||||
const metaDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const metaDir = path.dirname(normalizeModuleUrlToPath(import.meta.url));
|
||||
candidates.push(path.join(metaDir, "skills"));
|
||||
candidates.push(path.join(metaDir, "..", "skills"));
|
||||
} catch {
|
||||
|
||||
@@ -74,6 +74,7 @@
|
||||
"form-data@<4.0.6": ">=4.0.6",
|
||||
"uuid@<11.1.1": ">=11.1.1",
|
||||
"esbuild": ">=0.28.1",
|
||||
"undici@<6.27.0": ">=6.27.0 <8.0.0",
|
||||
"undici@>=8.0.0 <8.5.0": ">=8.5.0"
|
||||
}
|
||||
}
|
||||
|
||||
+6
-5
@@ -8,6 +8,7 @@ overrides:
|
||||
form-data@<4.0.6: '>=4.0.6'
|
||||
uuid@<11.1.1: '>=11.1.1'
|
||||
esbuild: '>=0.28.1'
|
||||
undici@<6.27.0: '>=6.27.0 <8.0.0'
|
||||
undici@>=8.0.0 <8.5.0: '>=8.5.0'
|
||||
|
||||
importers:
|
||||
@@ -2351,9 +2352,9 @@ packages:
|
||||
undici-types@7.24.6:
|
||||
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
|
||||
|
||||
undici@6.26.0:
|
||||
resolution: {integrity: sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A==}
|
||||
engines: {node: '>=18.17'}
|
||||
undici@7.28.0:
|
||||
resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}
|
||||
engines: {node: '>=20.18.1'}
|
||||
|
||||
undici@8.5.0:
|
||||
resolution: {integrity: sha512-xamtWoB1EshgjpmlXd7GGm2VfdDtw1+rD8uhry8pSNW3If6S8E0m2T2+orSKeZXEn/aPJMviCpDBA65WJt8zhg==}
|
||||
@@ -3202,7 +3203,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@qdrant/openapi-typescript-fetch': 1.2.6
|
||||
typescript: 6.0.3
|
||||
undici: 6.26.0
|
||||
undici: 7.28.0
|
||||
|
||||
'@qdrant/openapi-typescript-fetch@1.2.6': {}
|
||||
|
||||
@@ -4894,7 +4895,7 @@ snapshots:
|
||||
|
||||
undici-types@7.24.6: {}
|
||||
|
||||
undici@6.26.0: {}
|
||||
undici@7.28.0: {}
|
||||
|
||||
undici@8.5.0: {}
|
||||
|
||||
|
||||
@@ -5,4 +5,5 @@ overrides:
|
||||
"form-data@<4.0.6": ">=4.0.6"
|
||||
"uuid@<11.1.1": ">=11.1.1"
|
||||
"esbuild": ">=0.28.1"
|
||||
"undici@<6.27.0": ">=6.27.0 <8.0.0"
|
||||
"undici@>=8.0.0 <8.5.0": ">=8.5.0"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0ai",
|
||||
"version": "3.0.9",
|
||||
"version": "3.0.11",
|
||||
"description": "The Memory Layer For Your AI Apps",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
@@ -156,7 +156,8 @@
|
||||
"tar-fs@>=2.0.0 <2.1.4": "^2.1.4",
|
||||
"glob@>=10.2.0 <10.5.0": "^10.5.0",
|
||||
"@modelcontextprotocol/sdk": "^1.25.4",
|
||||
"esbuild": ">=0.28.1"
|
||||
"esbuild": ">=0.28.1",
|
||||
"undici@<6.27.0": ">=6.27.0 <8.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+6
-5
@@ -23,6 +23,7 @@ overrides:
|
||||
glob@>=10.2.0 <10.5.0: ^10.5.0
|
||||
'@modelcontextprotocol/sdk': ^1.25.4
|
||||
esbuild: '>=0.28.1'
|
||||
undici@<6.27.0: '>=6.27.0 <8.0.0'
|
||||
|
||||
importers:
|
||||
|
||||
@@ -2925,9 +2926,9 @@ packages:
|
||||
undici-types@6.21.0:
|
||||
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
|
||||
|
||||
undici@6.26.0:
|
||||
resolution: {integrity: sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A==}
|
||||
engines: {node: '>=18.17'}
|
||||
undici@7.28.0:
|
||||
resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}
|
||||
engines: {node: '>=20.18.1'}
|
||||
|
||||
update-browserslist-db@1.2.3:
|
||||
resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
|
||||
@@ -3747,7 +3748,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@qdrant/openapi-typescript-fetch': 1.2.6
|
||||
typescript: 5.5.4
|
||||
undici: 6.26.0
|
||||
undici: 7.28.0
|
||||
|
||||
'@qdrant/openapi-typescript-fetch@1.2.6': {}
|
||||
|
||||
@@ -6113,7 +6114,7 @@ snapshots:
|
||||
|
||||
undici-types@6.21.0: {}
|
||||
|
||||
undici@6.26.0: {}
|
||||
undici@7.28.0: {}
|
||||
|
||||
update-browserslist-db@1.2.3(browserslist@4.28.2):
|
||||
dependencies:
|
||||
|
||||
@@ -24,3 +24,4 @@ overrides:
|
||||
"glob@>=10.2.0 <10.5.0": "^10.5.0"
|
||||
"@modelcontextprotocol/sdk": "^1.25.4"
|
||||
"esbuild": ">=0.28.1"
|
||||
"undici@<6.27.0": ">=6.27.0 <8.0.0"
|
||||
|
||||
@@ -281,19 +281,22 @@ export default class MemoryClient {
|
||||
text,
|
||||
metadata,
|
||||
timestamp,
|
||||
expirationDate,
|
||||
}: {
|
||||
text?: string;
|
||||
metadata?: Record<string, any>;
|
||||
timestamp?: number | string;
|
||||
expirationDate?: string | null;
|
||||
},
|
||||
): Promise<Array<Memory>> {
|
||||
if (
|
||||
text === undefined &&
|
||||
metadata === undefined &&
|
||||
timestamp === undefined
|
||||
timestamp === undefined &&
|
||||
expirationDate === undefined
|
||||
) {
|
||||
throw new Error(
|
||||
"At least one of text, metadata, or timestamp must be provided for update.",
|
||||
"At least one of text, metadata, timestamp, or expirationDate must be provided for update.",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -302,6 +305,7 @@ export default class MemoryClient {
|
||||
if (text !== undefined) payload.text = text;
|
||||
if (metadata !== undefined) payload.metadata = metadata;
|
||||
if (timestamp !== undefined) payload.timestamp = timestamp;
|
||||
if (expirationDate !== undefined) payload.expiration_date = expirationDate;
|
||||
|
||||
const payloadKeys = Object.keys(payload);
|
||||
this._captureEvent("update", [payloadKeys]);
|
||||
|
||||
@@ -13,6 +13,7 @@ export interface AddMemoryOptions extends EntityOptions {
|
||||
customCategories?: custom_categories[];
|
||||
customInstructions?: string;
|
||||
timestamp?: number;
|
||||
expirationDate?: string;
|
||||
structuredDataSchema?: Record<string, any>;
|
||||
}
|
||||
|
||||
@@ -25,6 +26,7 @@ export interface SearchMemoryOptions {
|
||||
latestOnly?: boolean;
|
||||
fields?: string[];
|
||||
categories?: string[];
|
||||
showExpired?: boolean;
|
||||
}
|
||||
|
||||
export interface GetAllMemoryOptions {
|
||||
@@ -35,6 +37,7 @@ export interface GetAllMemoryOptions {
|
||||
endDate?: string;
|
||||
latestOnly?: boolean;
|
||||
categories?: string[];
|
||||
showExpired?: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteAllMemoryOptions extends EntityOptions {}
|
||||
@@ -119,6 +122,7 @@ export interface Memory {
|
||||
memoryType?: string;
|
||||
score?: number;
|
||||
metadata?: any | null;
|
||||
expirationDate?: string | null;
|
||||
owner?: string | null;
|
||||
agentId?: string | null;
|
||||
appId?: string | null;
|
||||
@@ -169,7 +173,9 @@ export interface PaginatedMemories {
|
||||
|
||||
export interface ProjectResponse {
|
||||
customInstructions?: string;
|
||||
customCategories?: string[];
|
||||
// The API returns category objects (`[{ "<name>": "<description>" }]`),
|
||||
// not bare strings (see issue #5738).
|
||||
customCategories?: custom_categories[];
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,21 @@ describe("MemoryClient - add()", () => {
|
||||
expect(getFetchBody(call!).user_id).toBe("user_1");
|
||||
});
|
||||
|
||||
test("serializes expirationDate as expiration_date", async () => {
|
||||
const extra = new Map<string, { status: number; body: unknown }>();
|
||||
extra.set("/v3/memories/add/", { status: 200, body: [createMockMemory()] });
|
||||
const mock = setupMockFetch(extra);
|
||||
|
||||
const client = new MemoryClient({ apiKey: TEST_API_KEY });
|
||||
await client.add([{ role: "user", content: "test" }], {
|
||||
userId: "u1",
|
||||
expirationDate: "2030-01-31",
|
||||
});
|
||||
|
||||
const call = findFetchCall(mock, "/v3/memories/add/", "POST");
|
||||
expect(getFetchBody(call!).expiration_date).toBe("2030-01-31");
|
||||
});
|
||||
|
||||
test("throws an error when given an empty messages array", async () => {
|
||||
setupMockFetch();
|
||||
|
||||
@@ -176,11 +191,26 @@ describe("MemoryClient - update()", () => {
|
||||
expect(body.timestamp).toBe(1710600000);
|
||||
});
|
||||
|
||||
test("sends expirationDate as expiration_date, including null", async () => {
|
||||
const extra = new Map<string, { status: number; body: unknown }>();
|
||||
extra.set("/v1/memories/mem_123/", {
|
||||
status: 200,
|
||||
body: createMockMemory(),
|
||||
});
|
||||
const mock = setupMockFetch(extra);
|
||||
|
||||
const client = new MemoryClient({ apiKey: TEST_API_KEY });
|
||||
await client.update("mem_123", { expirationDate: null });
|
||||
|
||||
const call = findFetchCall(mock, "/v1/memories/mem_123/", "PUT");
|
||||
expect(getFetchBody(call!).expiration_date).toBeNull();
|
||||
});
|
||||
|
||||
test("throws when no fields provided", async () => {
|
||||
setupMockFetch();
|
||||
const client = new MemoryClient({ apiKey: TEST_API_KEY });
|
||||
await expect(client.update("mem_123", {})).rejects.toThrow(
|
||||
"At least one of text, metadata, or timestamp must be provided",
|
||||
"At least one of text, metadata, timestamp, or expirationDate must be provided",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -81,6 +81,24 @@ describe("MemoryClient - search()", () => {
|
||||
expect(getFetchBody(call!).latest_only).toBe(true);
|
||||
});
|
||||
|
||||
test("serializes showExpired as show_expired", async () => {
|
||||
const extra = new Map<string, { status: number; body: unknown }>();
|
||||
extra.set("/v3/memories/search/", {
|
||||
status: 200,
|
||||
body: { results: [] },
|
||||
});
|
||||
const mock = setupMockFetch(extra);
|
||||
|
||||
const client = new MemoryClient({ apiKey: TEST_API_KEY });
|
||||
await client.search("test", {
|
||||
filters: { user_id: "u1" },
|
||||
showExpired: true,
|
||||
});
|
||||
|
||||
const call = findFetchCall(mock, "/v3/memories/search/", "POST");
|
||||
expect(getFetchBody(call!).show_expired).toBe(true);
|
||||
});
|
||||
|
||||
test("passes complex OR filters through to the API body", async () => {
|
||||
const extra = new Map<string, { status: number; body: unknown }>();
|
||||
extra.set("/v3/memories/search/", {
|
||||
@@ -300,4 +318,22 @@ describe("MemoryClient - getAll() entity param rejection", () => {
|
||||
const call = findFetchCall(mock, "/v3/memories/", "POST");
|
||||
expect(getFetchBody(call!).latest_only).toBe(true);
|
||||
});
|
||||
|
||||
test("serializes showExpired as show_expired", async () => {
|
||||
const extra = new Map<string, { status: number; body: unknown }>();
|
||||
extra.set("/v3/memories/", {
|
||||
status: 200,
|
||||
body: { results: [] },
|
||||
});
|
||||
const mock = setupMockFetch(extra);
|
||||
|
||||
const client = new MemoryClient({ apiKey: TEST_API_KEY });
|
||||
await client.getAll({
|
||||
filters: { user_id: "u1" },
|
||||
showExpired: true,
|
||||
});
|
||||
|
||||
const call = findFetchCall(mock, "/v3/memories/", "POST");
|
||||
expect(getFetchBody(call!).show_expired).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -99,4 +99,50 @@ describe("camelToSnakeKeys / snakeToCamelKeys", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("user-controlled customCategories names (issue #5738)", () => {
|
||||
it("converts the outer key but leaves multi-word category names on write", () => {
|
||||
expect(
|
||||
camelToSnakeKeys({
|
||||
customCategories: [
|
||||
{ work_life_balance: "desc" },
|
||||
{ AIResearch: "desc" },
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
// outer SDK key is snake_cased, user-defined category names are not
|
||||
custom_categories: [
|
||||
{ work_life_balance: "desc" },
|
||||
{ AIResearch: "desc" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("converts the outer key but leaves category names verbatim on read", () => {
|
||||
expect(
|
||||
snakeToCamelKeys({
|
||||
custom_categories: [
|
||||
{ work_life_balance: "desc" },
|
||||
{ AIResearch: "desc" },
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
customCategories: [
|
||||
{ work_life_balance: "desc" },
|
||||
{ AIResearch: "desc" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips category names losslessly (write then read)", () => {
|
||||
const customCategories = [
|
||||
{ work_life_balance: "balance between work and life" },
|
||||
{ AIResearch: "artificial intelligence research" },
|
||||
];
|
||||
const roundTripped = snakeToCamelKeys(
|
||||
camelToSnakeKeys({ customCategories }),
|
||||
);
|
||||
expect(roundTripped.customCategories).toEqual(customCategories);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,6 +29,11 @@ const OPAQUE_VALUE_KEYS = new Set([
|
||||
"metadata",
|
||||
"structuredDataSchema",
|
||||
"structured_data_schema",
|
||||
// Custom-category names are user-controlled keys (`[{ "<name>": "<desc>" }]`).
|
||||
// Listed in both casings so they round-trip verbatim in both directions
|
||||
// (see issue #5738; same class as `metadata`/`structuredDataSchema`).
|
||||
"customCategories",
|
||||
"custom_categories",
|
||||
]);
|
||||
|
||||
/**
|
||||
|
||||
@@ -18,6 +18,7 @@ export * from "./llms/ollama";
|
||||
export * from "./llms/lmstudio";
|
||||
export * from "./llms/mistral";
|
||||
export * from "./llms/langchain";
|
||||
export * from "./llms/litellm";
|
||||
export * from "./vector_stores/base";
|
||||
export * from "./vector_stores/memory";
|
||||
export * from "./vector_stores/qdrant";
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { OpenAILLM } from "./openai";
|
||||
import { LLMConfig, Message } from "../types";
|
||||
import { LLMResponse } from "./base";
|
||||
|
||||
export class LiteLLM extends OpenAILLM {
|
||||
constructor(config: LLMConfig) {
|
||||
super({
|
||||
...config,
|
||||
apiKey: config.apiKey || process.env.LITELLM_API_KEY || "sk-anything",
|
||||
baseURL:
|
||||
config.baseURL ||
|
||||
process.env.LITELLM_API_BASE ||
|
||||
"http://localhost:4000",
|
||||
model: config.model || "gpt-5-mini",
|
||||
});
|
||||
}
|
||||
|
||||
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(`LiteLLM 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(`LiteLLM failed: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,20 +2,20 @@ import { OpenAILLM } from "./openai";
|
||||
import { LLMConfig, Message } from "../types";
|
||||
import { LLMResponse } from "./base";
|
||||
|
||||
export class TogetherLLM extends OpenAILLM {
|
||||
export class MiniMaxLLM extends OpenAILLM {
|
||||
constructor(config: LLMConfig) {
|
||||
const apiKey = config.apiKey || process.env.TOGETHER_API_KEY;
|
||||
const apiKey = config.apiKey || process.env.MINIMAX_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error("Together API key is required");
|
||||
throw new Error("MiniMax API key is required");
|
||||
}
|
||||
super({
|
||||
...config,
|
||||
apiKey,
|
||||
baseURL:
|
||||
config.baseURL ||
|
||||
process.env.TOGETHER_API_BASE ||
|
||||
"https://api.together.xyz/v1",
|
||||
model: config.model || "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
process.env.MINIMAX_API_BASE ||
|
||||
"https://api.minimax.io/v1",
|
||||
model: config.model || "MiniMax-M2.7",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export class TogetherLLM extends OpenAILLM {
|
||||
return await super.generateResponse(messages, responseFormat, tools);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`Together LLM failed: ${message}`);
|
||||
throw new Error(`MiniMax LLM failed: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ export class TogetherLLM extends OpenAILLM {
|
||||
return await super.generateChat(messages);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`Together LLM failed: ${message}`);
|
||||
throw new Error(`MiniMax LLM failed: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -296,6 +296,44 @@ export class Memory {
|
||||
return filters;
|
||||
}
|
||||
|
||||
private _normalizeEntityText(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
private async _existingEntitiesByText(
|
||||
entityStore: VectorStore,
|
||||
filters: Record<string, any>,
|
||||
): Promise<Map<string, { id: string; payload: Record<string, any> }>> {
|
||||
const rowsByText = new Map<
|
||||
string,
|
||||
{ id: string; payload: Record<string, any> }
|
||||
>();
|
||||
let rows: Array<{ id: string; payload: Record<string, any> }> = [];
|
||||
try {
|
||||
const listed = await entityStore.list(filters, 10000);
|
||||
rows = (
|
||||
Array.isArray(listed) && Array.isArray(listed[0])
|
||||
? listed[0]
|
||||
: (listed as any)
|
||||
) as Array<{ id: string; payload: Record<string, any> }>;
|
||||
} catch (e) {
|
||||
console.debug(
|
||||
`Exact entity lookup failed, falling back to semantic dedup: ${e}`,
|
||||
);
|
||||
return rowsByText;
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
const text = row.payload?.data;
|
||||
if (typeof text !== "string") continue;
|
||||
const key = this._normalizeEntityText(text);
|
||||
if (key && !rowsByText.has(key)) {
|
||||
rowsByText.set(key, row);
|
||||
}
|
||||
}
|
||||
return rowsByText;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove `memoryId` from every entity record scoped to `filters`.
|
||||
* If an entity's `linkedMemoryIds` becomes empty after removal, the
|
||||
@@ -393,6 +431,10 @@ export class Memory {
|
||||
if (entities.length === 0) return;
|
||||
|
||||
const entityStore = await this.getEntityStore();
|
||||
const exactMatches = await this._existingEntitiesByText(
|
||||
entityStore,
|
||||
filters,
|
||||
);
|
||||
|
||||
for (const entity of entities) {
|
||||
try {
|
||||
@@ -409,12 +451,21 @@ export class Memory {
|
||||
score?: number;
|
||||
payload: Record<string, any>;
|
||||
}> = [];
|
||||
try {
|
||||
matches = await entityStore.search(entityVec, 1, filters);
|
||||
} catch {}
|
||||
const exactMatch = exactMatches.get(
|
||||
this._normalizeEntityText(entity.text),
|
||||
);
|
||||
if (!exactMatch) {
|
||||
try {
|
||||
matches = await entityStore.search(entityVec, 1, filters);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (matches.length > 0 && (matches[0].score ?? 0) >= 0.95) {
|
||||
const match = matches[0];
|
||||
const semanticMatch =
|
||||
matches.length > 0 && (matches[0].score ?? 0) >= 0.95
|
||||
? matches[0]
|
||||
: undefined;
|
||||
const match = exactMatch ?? semanticMatch;
|
||||
if (match) {
|
||||
const payload = match.payload || {};
|
||||
const linked = new Set<string>(
|
||||
Array.isArray(payload.linkedMemoryIds)
|
||||
@@ -1062,6 +1113,10 @@ export class Memory {
|
||||
|
||||
if (valid.length > 0) {
|
||||
const entityStore = await this.getEntityStore();
|
||||
const exactMatches = await this._existingEntitiesByText(
|
||||
entityStore,
|
||||
filters,
|
||||
);
|
||||
|
||||
// 7c: Search for existing entities one by one (no batch search)
|
||||
const toInsertVectors: number[][] = [];
|
||||
@@ -1077,13 +1132,20 @@ export class Memory {
|
||||
score?: number;
|
||||
payload: Record<string, any>;
|
||||
}> = [];
|
||||
try {
|
||||
matches = await entityStore.search(entityVec, 1, filters);
|
||||
} catch {}
|
||||
const exactMatch = exactMatches.get(key);
|
||||
if (!exactMatch) {
|
||||
try {
|
||||
matches = await entityStore.search(entityVec, 1, filters);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (matches.length > 0 && (matches[0].score ?? 0) >= 0.95) {
|
||||
const semanticMatch =
|
||||
matches.length > 0 && (matches[0].score ?? 0) >= 0.95
|
||||
? matches[0]
|
||||
: undefined;
|
||||
const match = exactMatch ?? semanticMatch;
|
||||
if (match) {
|
||||
// Update existing entity
|
||||
const match = matches[0];
|
||||
const payload = match.payload || {};
|
||||
const linked = new Set<string>(payload.linkedMemoryIds ?? []);
|
||||
for (const mid of memoryIds) linked.add(mid);
|
||||
@@ -1539,7 +1601,9 @@ export class Memory {
|
||||
has_agent_id: !!config.agentId,
|
||||
has_run_id: !!config.runId,
|
||||
});
|
||||
const { userId, agentId, runId } = config;
|
||||
const userId = validateAndTrimEntityId(config.userId, "userId");
|
||||
const agentId = validateAndTrimEntityId(config.agentId, "agentId");
|
||||
const runId = validateAndTrimEntityId(config.runId, "runId");
|
||||
|
||||
// Convert camelCase entity params to snake_case for filters (matches storage and search/getAll)
|
||||
const filters: SearchFilters = {};
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
* Extracts four types of entities from text:
|
||||
* - PROPER: Capitalized multi-word sequences (person names, places, brands)
|
||||
* - QUOTED: Text in single or double quotes (titles, specific terms)
|
||||
* - COMPOUND: Multi-word noun phrases with specific modifiers (e.g., "machine learning")
|
||||
* - NOUN: Single nouns from circumstantial compound patterns
|
||||
* - TOPIC: Multi-word noun/topic phrases with specific modifiers
|
||||
* - IDENTIFIER: Dotted technical identifiers such as person.properties.email
|
||||
*
|
||||
* Uses the `compromise` npm package for NLP-based extraction when available.
|
||||
* Falls back to regex-only extraction if `compromise` is not installed.
|
||||
@@ -196,6 +196,25 @@ const NON_SPECIFIC_ADJ: Set<string> = new Set([
|
||||
"final",
|
||||
"initial",
|
||||
"side",
|
||||
"top",
|
||||
]);
|
||||
|
||||
/** Leading words that frame a topic but are not part of the topic itself. */
|
||||
const TOPIC_PREFIX_WORDS: Set<string> = new Set([
|
||||
"a",
|
||||
"an",
|
||||
"the",
|
||||
"my",
|
||||
"your",
|
||||
"our",
|
||||
"their",
|
||||
"his",
|
||||
"her",
|
||||
"its",
|
||||
"this",
|
||||
"that",
|
||||
"these",
|
||||
"those",
|
||||
]);
|
||||
|
||||
/** Generic tail words to strip from compound entities. */
|
||||
@@ -267,6 +286,25 @@ const GENERIC_CAPS: Set<string> = new Set([
|
||||
"disadvantages",
|
||||
]);
|
||||
|
||||
/** Generic role/title words that should not become single-token entities. */
|
||||
const GENERIC_SINGLE_ENTITY_TERMS: Set<string> = new Set([
|
||||
"user",
|
||||
"assistant",
|
||||
"agent",
|
||||
"customer",
|
||||
"client",
|
||||
"person",
|
||||
"people",
|
||||
"human",
|
||||
"memory",
|
||||
"message",
|
||||
"conversation",
|
||||
"chat",
|
||||
"session",
|
||||
"system",
|
||||
"top",
|
||||
]);
|
||||
|
||||
/** Markdown/formatting markers to skip during extraction. */
|
||||
const FORMATTING_MARKERS: Set<string> = new Set([
|
||||
"*",
|
||||
@@ -287,7 +325,7 @@ const FORMATTING_MARKERS: Set<string> = new Set([
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ExtractedEntity {
|
||||
type: "PROPER" | "QUOTED" | "COMPOUND" | "NOUN";
|
||||
type: "PROPER" | "QUOTED" | "TOPIC" | "IDENTIFIER";
|
||||
text: string;
|
||||
}
|
||||
|
||||
@@ -338,32 +376,96 @@ function stripGenericEnding(words: string[]): string[] {
|
||||
return words;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a token position is at the start of a sentence.
|
||||
* Simple heuristic: index 0, or preceded by sentence-ending punctuation
|
||||
* or formatting markers.
|
||||
*/
|
||||
function isSentenceStart(
|
||||
tokens: string[],
|
||||
idx: number,
|
||||
rawText: string,
|
||||
): boolean {
|
||||
if (idx === 0) {
|
||||
return true;
|
||||
function stripTopicPrefix(words: string[]): string[] {
|
||||
let start = 0;
|
||||
while (
|
||||
start < words.length &&
|
||||
TOPIC_PREFIX_WORDS.has(words[start].toLowerCase())
|
||||
) {
|
||||
start++;
|
||||
}
|
||||
const prev = tokens[idx - 1];
|
||||
if (/[.!?:]$/.test(prev)) {
|
||||
return words.slice(start);
|
||||
}
|
||||
|
||||
function cleanToken(token: string): string {
|
||||
return token.replace(/^[^\w.]+|[^\w.]+$/g, "");
|
||||
}
|
||||
|
||||
function tokenize(text: string): string[] {
|
||||
return (
|
||||
text.match(
|
||||
/[A-Za-z_][\w-]*(?:\.[A-Za-z_][\w-]*)*|\d[\d,]*(?:\.\d+)?|[,:;.!?&]/g,
|
||||
) ?? []
|
||||
);
|
||||
}
|
||||
|
||||
function isCapitalized(token: string): boolean {
|
||||
return /^[A-Z]/.test(token) && /[A-Za-z]/.test(token);
|
||||
}
|
||||
|
||||
function hasInternalCapOrDigit(token: string): boolean {
|
||||
return (
|
||||
/\d/.test(token) ||
|
||||
/[A-Z]/.test(token.slice(1)) ||
|
||||
/^[A-Z]{2,}$/.test(token)
|
||||
);
|
||||
}
|
||||
|
||||
function isBadSingleNameToken(token: string): boolean {
|
||||
const lower = token.toLowerCase();
|
||||
return GENERIC_SINGLE_ENTITY_TERMS.has(lower) || GENERIC_CAPS.has(lower);
|
||||
}
|
||||
|
||||
function looksLikeMetricCount(token: string): boolean {
|
||||
return /^\d[\d,]*(?:\.\d+)?$/.test(token);
|
||||
}
|
||||
|
||||
function isMetricListContext(tokens: string[], idx: number): boolean {
|
||||
const prev = idx > 0 ? tokens[idx - 1] : "";
|
||||
const next = idx + 1 < tokens.length ? tokens[idx + 1] : "";
|
||||
return [":", ",", ";"].includes(prev) || [",", ";"].includes(next);
|
||||
}
|
||||
|
||||
function isSentenceStart(tokens: string[], idx: number): boolean {
|
||||
if (idx === 0) return true;
|
||||
return (
|
||||
[".", "!", "?", ":"].includes(tokens[idx - 1]) ||
|
||||
FORMATTING_MARKERS.has(tokens[idx - 1])
|
||||
);
|
||||
}
|
||||
|
||||
function isListItemNameToken(tokens: string[], idx: number): boolean {
|
||||
const token = cleanToken(tokens[idx]);
|
||||
if (!isCapitalized(token) || isBadSingleNameToken(token)) return false;
|
||||
const next = idx + 1 < tokens.length ? cleanToken(tokens[idx + 1]) : "";
|
||||
if (!looksLikeMetricCount(next)) return false;
|
||||
return (
|
||||
isMetricListContext(tokens, idx) || isMetricListContext(tokens, idx + 1)
|
||||
);
|
||||
}
|
||||
|
||||
function isNameToken(tokens: string[], idx: number): boolean {
|
||||
const token = cleanToken(tokens[idx]);
|
||||
if (!token || !isCapitalized(token) || isBadSingleNameToken(token))
|
||||
return false;
|
||||
if (hasInternalCapOrDigit(token) || isListItemNameToken(tokens, idx))
|
||||
return true;
|
||||
}
|
||||
if (FORMATTING_MARKERS.has(prev)) {
|
||||
return true;
|
||||
}
|
||||
// Check for newline before this token in the raw text
|
||||
const tokenStart = rawText.indexOf(tokens[idx]);
|
||||
if (tokenStart > 0 && rawText.charAt(tokenStart - 1) === "\n") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return !isSentenceStart(tokens, idx);
|
||||
}
|
||||
|
||||
function cleanEntityText(text: string): string {
|
||||
return text
|
||||
.replace(/^\*+\s*|\s*\*+$/g, "")
|
||||
.replace(/\s*:+$/g, "")
|
||||
.replace(/^\d+\s*\.\s*/, "")
|
||||
.replace(/\s+\d[\d,]*(?:\.\d+)?$/g, "")
|
||||
.replace(/[.,;!?]+$/, "")
|
||||
.trim()
|
||||
.replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
function isCoordinatedNameTopic(text: string): boolean {
|
||||
return /\b[A-Z][\w-]+\s+and\s+[A-Z][\w-]+\b/.test(text);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -397,86 +499,79 @@ function extractQuoted(text: string): ExtractedEntity[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract proper noun sequences using capitalization heuristics.
|
||||
* Finds sequences of capitalized words that are not at sentence starts.
|
||||
* Extract dotted technical identifiers such as person.properties.email.
|
||||
*/
|
||||
function extractIdentifiers(text: string): ExtractedEntity[] {
|
||||
const entities: ExtractedEntity[] = [];
|
||||
const identifierRe = /\b[A-Za-z_][\w-]*(?:\.[A-Za-z_][\w-]*)+\b/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = identifierRe.exec(text)) !== null) {
|
||||
entities.push({ type: "IDENTIFIER", text: match[0] });
|
||||
}
|
||||
return entities;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract proper names using capitalization and list-context heuristics.
|
||||
*/
|
||||
function extractProper(text: string): ExtractedEntity[] {
|
||||
const entities: ExtractedEntity[] = [];
|
||||
// Tokenize on whitespace, preserving order
|
||||
const tokens = text.split(/\s+/).filter(Boolean);
|
||||
const functionWords = new Set([
|
||||
"'s",
|
||||
"of",
|
||||
"the",
|
||||
"in",
|
||||
"and",
|
||||
"for",
|
||||
"at",
|
||||
"is",
|
||||
]);
|
||||
const tokens = tokenize(text);
|
||||
const innerConnectors = new Set(["of", "the", "in", "for", "at"]);
|
||||
|
||||
let i = 0;
|
||||
while (i < tokens.length) {
|
||||
const tok = tokens[i];
|
||||
// Skip formatting markers
|
||||
if (FORMATTING_MARKERS.has(tok)) {
|
||||
const token = cleanToken(tokens[i]);
|
||||
const next = i + 1 < tokens.length ? tokens[i + 1] : "";
|
||||
const afterNext = i + 2 < tokens.length ? cleanToken(tokens[i + 2]) : "";
|
||||
if (
|
||||
token &&
|
||||
next === "&" &&
|
||||
afterNext &&
|
||||
isCapitalized(token) &&
|
||||
isCapitalized(afterNext) &&
|
||||
!isBadSingleNameToken(token) &&
|
||||
!isBadSingleNameToken(afterNext)
|
||||
) {
|
||||
entities.push({
|
||||
type: "PROPER",
|
||||
text: cleanEntityText(`${token} & ${afterNext}`),
|
||||
});
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isNameToken(tokens, i)) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const isLabel = i + 1 < tokens.length && tokens[i + 1] === ":";
|
||||
const isCap =
|
||||
tok.length > 0 &&
|
||||
tok.charAt(0) === tok.charAt(0).toUpperCase() &&
|
||||
/[A-Z]/.test(tok.charAt(0));
|
||||
|
||||
if (isCap && !isLabel) {
|
||||
const seq: Array<{ token: string; idx: number }> = [
|
||||
{ token: tok, idx: i },
|
||||
];
|
||||
let j = i + 1;
|
||||
while (j < tokens.length) {
|
||||
const t = tokens[j];
|
||||
const tIsCap =
|
||||
t.length > 0 &&
|
||||
t.charAt(0) === t.charAt(0).toUpperCase() &&
|
||||
/[A-Z]/.test(t.charAt(0));
|
||||
if (tIsCap || functionWords.has(t.toLowerCase())) {
|
||||
seq.push({ token: t, idx: j });
|
||||
j++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
const span = [cleanToken(tokens[i])];
|
||||
let j = i + 1;
|
||||
while (j < tokens.length) {
|
||||
const current = cleanToken(tokens[j]);
|
||||
if (isNameToken(tokens, j)) {
|
||||
span.push(current);
|
||||
j++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Strip trailing function words
|
||||
while (
|
||||
seq.length > 0 &&
|
||||
functionWords.has(seq[seq.length - 1].token.toLowerCase())
|
||||
if (
|
||||
innerConnectors.has(current.toLowerCase()) &&
|
||||
j + 1 < tokens.length &&
|
||||
isNameToken(tokens, j + 1)
|
||||
) {
|
||||
seq.pop();
|
||||
span.push(current, cleanToken(tokens[j + 1]));
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seq.length > 0) {
|
||||
// Check for at least one mid-sentence capitalized word
|
||||
const hasMidCap = seq.some(({ token, idx: tokenIdx }) => {
|
||||
const isCapWord =
|
||||
/[A-Z]/.test(token.charAt(0)) &&
|
||||
!functionWords.has(token.toLowerCase());
|
||||
return isCapWord && !isSentenceStart(tokens, tokenIdx, text);
|
||||
});
|
||||
|
||||
if (hasMidCap) {
|
||||
const phrase = seq.map((s) => s.token).join(" ");
|
||||
if (phrase.length > 2) {
|
||||
entities.push({ type: "PROPER", text: phrase });
|
||||
}
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
} else {
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
|
||||
const phrase = cleanEntityText(span.join(" "));
|
||||
if (phrase.length > 2) {
|
||||
entities.push({ type: "PROPER", text: phrase });
|
||||
}
|
||||
i = Math.max(j, i + 1);
|
||||
}
|
||||
|
||||
return entities;
|
||||
@@ -484,7 +579,7 @@ function extractProper(text: string): ExtractedEntity[] {
|
||||
|
||||
/**
|
||||
* Extract compound noun phrases using the `compromise` NLP library.
|
||||
* Returns COMPOUND and NOUN entities derived from noun chunks.
|
||||
* Returns TOPIC entities derived from noun chunks.
|
||||
*/
|
||||
function extractCompoundsWithNlp(text: string): ExtractedEntity[] {
|
||||
if (!nlp) {
|
||||
@@ -524,12 +619,12 @@ function extractCompoundsWithNlp(text: string): ExtractedEntity[] {
|
||||
const filtered = words.filter(
|
||||
(w) => !NON_SPECIFIC_ADJ.has(w.toLowerCase()),
|
||||
);
|
||||
const cleaned = stripGenericEnding(filtered);
|
||||
const cleaned = stripGenericEnding(stripTopicPrefix(filtered));
|
||||
|
||||
if (cleaned.length >= 2) {
|
||||
const phrase = cleaned.join(" ");
|
||||
const phrase = cleanEntityText(cleaned.join(" "));
|
||||
if (phrase.length > 3) {
|
||||
entities.push({ type: "COMPOUND", text: phrase });
|
||||
entities.push({ type: "TOPIC", text: phrase });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -547,7 +642,7 @@ function extractCompoundsRegex(text: string): ExtractedEntity[] {
|
||||
// Multi-word sequences with at least one non-trivial word
|
||||
// Match sequences like "machine learning", "New York", "data science"
|
||||
const compoundRe =
|
||||
/\b([A-Z][a-z]+(?:\s+(?:of|and|the|for|in)\s+)?[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b/g;
|
||||
/\b([A-Z][a-z]+(?:\s+(?:of|the|for|in)\s+)?[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = compoundRe.exec(text)) !== null) {
|
||||
const phrase = match[1].trim();
|
||||
@@ -558,9 +653,12 @@ function extractCompoundsRegex(text: string): ExtractedEntity[] {
|
||||
const filtered = words.filter(
|
||||
(w) => !NON_SPECIFIC_ADJ.has(w.toLowerCase()),
|
||||
);
|
||||
const cleaned = stripGenericEnding(filtered);
|
||||
const cleaned = stripGenericEnding(stripTopicPrefix(filtered));
|
||||
if (cleaned.length >= 2) {
|
||||
entities.push({ type: "COMPOUND", text: cleaned.join(" ") });
|
||||
entities.push({
|
||||
type: "TOPIC",
|
||||
text: cleanEntityText(cleaned.join(" ")),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -590,9 +688,12 @@ function extractCompoundsRegex(text: string): ExtractedEntity[] {
|
||||
const filtered = words.filter(
|
||||
(w) => !NON_SPECIFIC_ADJ.has(w.toLowerCase()),
|
||||
);
|
||||
const cleaned = stripGenericEnding(filtered);
|
||||
const cleaned = stripGenericEnding(stripTopicPrefix(filtered));
|
||||
if (cleaned.length >= 2) {
|
||||
entities.push({ type: "COMPOUND", text: cleaned.join(" ") });
|
||||
entities.push({
|
||||
type: "TOPIC",
|
||||
text: cleanEntityText(cleaned.join(" ")),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -614,9 +715,9 @@ function extractCompoundsRegex(text: string): ExtractedEntity[] {
|
||||
*
|
||||
* Entity types (in priority order for deduplication):
|
||||
* PROPER - Capitalized multi-word sequences not at sentence start
|
||||
* COMPOUND - Multi-word noun phrases with specific modifiers
|
||||
* IDENTIFIER - Dotted technical identifiers
|
||||
* QUOTED - Text in single or double quotes (min 3 chars)
|
||||
* NOUN - Single nouns from circumstantial patterns
|
||||
* TOPIC - Multi-word noun/topic phrases with specific modifiers
|
||||
*
|
||||
* @param text - Input text to extract entities from.
|
||||
* @returns Deduplicated list of extracted entities.
|
||||
@@ -630,7 +731,10 @@ export function extractEntities(text: string): ExtractedEntity[] {
|
||||
// 2. PROPER entities (capitalization heuristics)
|
||||
raw.push(...extractProper(text));
|
||||
|
||||
// 3. COMPOUND entities (NLP or regex fallback)
|
||||
// 3. IDENTIFIER entities
|
||||
raw.push(...extractIdentifiers(text));
|
||||
|
||||
// 4. TOPIC entities (NLP or regex fallback)
|
||||
if (nlp) {
|
||||
raw.push(...extractCompoundsWithNlp(text));
|
||||
} else {
|
||||
@@ -654,19 +758,17 @@ export function extractEntities(text: string): ExtractedEntity[] {
|
||||
const cleaned: ExtractedEntity[] = [];
|
||||
for (const entity of deduped) {
|
||||
let txt = entity.text.trim();
|
||||
// Strip leading/trailing asterisks
|
||||
txt = txt.replace(/^\*+\s*|\s*\*+$/g, "");
|
||||
// Strip trailing colons
|
||||
txt = txt.replace(/\s*:+$/, "");
|
||||
// Strip leading numbered list markers
|
||||
txt = txt.replace(/^\d+\s*\.\s*/, "");
|
||||
// Strip trailing sentence punctuation (".", ",", ";", "!", "?") — otherwise
|
||||
// "Paris." and "Paris" produce different embeddings and break entity dedup.
|
||||
txt = txt.replace(/[.,;!?]+$/, "").trim();
|
||||
txt = cleanEntityText(txt);
|
||||
|
||||
if (!txt || txt.length <= 2 || hasArtifacts(txt)) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
entity.type === "TOPIC" &&
|
||||
(/^\d/.test(txt) || isCoordinatedNameTopic(txt))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Filter generic single-word PROPER nouns
|
||||
if (
|
||||
@@ -680,12 +782,12 @@ export function extractEntities(text: string): ExtractedEntity[] {
|
||||
cleaned.push({ type: entity.type, text: txt });
|
||||
}
|
||||
|
||||
// Keep best type per entity (PROPER > COMPOUND > QUOTED > NOUN)
|
||||
// Keep best type per entity (PROPER > IDENTIFIER > QUOTED > TOPIC)
|
||||
const typePriority: Record<string, number> = {
|
||||
PROPER: 0,
|
||||
COMPOUND: 1,
|
||||
IDENTIFIER: 1,
|
||||
QUOTED: 2,
|
||||
NOUN: 3,
|
||||
TOPIC: 3,
|
||||
};
|
||||
const best = new Map<string, ExtractedEntity>();
|
||||
for (const entity of cleaned) {
|
||||
@@ -700,14 +802,17 @@ export function extractEntities(text: string): ExtractedEntity[] {
|
||||
}
|
||||
const bestEntities = Array.from(best.values());
|
||||
|
||||
// Remove entities that are substrings of longer entities
|
||||
const allLower = bestEntities.map((e) => e.text.toLowerCase());
|
||||
// Remove entities that are token substrings of longer entities.
|
||||
return bestEntities.filter(
|
||||
(entity) =>
|
||||
!allLower.some(
|
||||
!bestEntities.some(
|
||||
(other) =>
|
||||
entity.text.toLowerCase() !== other &&
|
||||
other.includes(entity.text.toLowerCase()),
|
||||
entity.text.toLowerCase() !== other.text.toLowerCase() &&
|
||||
(typePriority[entity.type] ?? 99) >=
|
||||
(typePriority[other.type] ?? 99) &&
|
||||
new RegExp(
|
||||
`(^|\\s)${entity.text.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\s|$)`,
|
||||
).test(other.text.toLowerCase()),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,8 @@ import { RedisDB } from "../vector_stores/redis";
|
||||
import { OllamaLLM } from "../llms/ollama";
|
||||
import { LMStudioLLM } from "../llms/lmstudio";
|
||||
import { DeepSeekLLM } from "../llms/deepseek";
|
||||
import { TogetherLLM } from "../llms/together";
|
||||
import { LiteLLM } from "../llms/litellm";
|
||||
import { MiniMaxLLM } from "../llms/minimax";
|
||||
import { SupabaseDB } from "../vector_stores/supabase";
|
||||
import { SQLiteManager } from "../storage/SQLiteManager";
|
||||
import { MemoryHistoryManager } from "../storage/MemoryHistoryManager";
|
||||
@@ -86,8 +87,10 @@ export class LLMFactory {
|
||||
return new LangchainLLM(config);
|
||||
case "deepseek":
|
||||
return new DeepSeekLLM(config);
|
||||
case "together":
|
||||
return new TogetherLLM(config);
|
||||
case "litellm":
|
||||
return new LiteLLM(config);
|
||||
case "minimax":
|
||||
return new MiniMaxLLM(config);
|
||||
default:
|
||||
throw new Error(`Unsupported LLM provider: ${provider}`);
|
||||
}
|
||||
|
||||
@@ -31,9 +31,11 @@ const parse_vision_messages = async (messages: Message[]) => {
|
||||
typeof message.content === "object" &&
|
||||
message.content.type === "image_url"
|
||||
) {
|
||||
const description = await get_image_description(
|
||||
message.content.image_url.url,
|
||||
);
|
||||
const imageUrl = message.content.image_url?.url;
|
||||
if (!imageUrl) {
|
||||
throw new Error("image_url content part is missing image_url.url");
|
||||
}
|
||||
const description = await get_image_description(imageUrl);
|
||||
new_message.content =
|
||||
typeof description === "string"
|
||||
? description
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Client as ClientType } from "pg";
|
||||
import type { Client as ClientType, ClientConfig } from "pg";
|
||||
import pkg from "pg";
|
||||
const { Client, escapeIdentifier } = pkg;
|
||||
import { VectorStore } from "./base";
|
||||
@@ -157,41 +157,90 @@ export function buildFilterConditions(
|
||||
|
||||
interface PGVectorConfig extends VectorStoreConfig {
|
||||
dbname?: string;
|
||||
user: string;
|
||||
password: string;
|
||||
host: string;
|
||||
port: number;
|
||||
user?: string;
|
||||
password?: string;
|
||||
host?: string;
|
||||
port?: number;
|
||||
connectionString?: string;
|
||||
ssl?: ClientConfig["ssl"];
|
||||
embeddingModelDims: number;
|
||||
diskann?: boolean;
|
||||
hnsw?: boolean;
|
||||
}
|
||||
|
||||
function getConnectionString(config: PGVectorConfig): string | undefined {
|
||||
return config.connectionString?.trim() || undefined;
|
||||
}
|
||||
|
||||
function validateConnectionConfig(config: PGVectorConfig): void {
|
||||
if (getConnectionString(config)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const missingFields = ["user", "password", "host", "port"].filter((field) => {
|
||||
const v = config[field as keyof PGVectorConfig];
|
||||
return v === undefined || v === null || v === "";
|
||||
});
|
||||
|
||||
if (missingFields.length > 0) {
|
||||
throw new Error(
|
||||
`PGVector requires either connectionString or ${missingFields.join(", ")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function buildClientConfig(
|
||||
config: PGVectorConfig,
|
||||
database?: string,
|
||||
): ClientConfig {
|
||||
const connectionString = getConnectionString(config);
|
||||
if (connectionString) {
|
||||
return {
|
||||
connectionString,
|
||||
...(config.ssl !== undefined ? { ssl: config.ssl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
database,
|
||||
user: config.user,
|
||||
password: config.password,
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
...(config.ssl !== undefined ? { ssl: config.ssl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export class PGVector implements VectorStore {
|
||||
private client: ClientType;
|
||||
private collectionName: string;
|
||||
private useDiskann: boolean;
|
||||
private useHnsw: boolean;
|
||||
private readonly dbName: string;
|
||||
private readonly useDirectConnection: boolean;
|
||||
private config: PGVectorConfig;
|
||||
private _initPromise?: Promise<void>;
|
||||
|
||||
constructor(config: PGVectorConfig) {
|
||||
validateConnectionConfig(config);
|
||||
this.collectionName = validateIdentifier(
|
||||
config.collectionName || "memories",
|
||||
"collectionName",
|
||||
);
|
||||
this.useDiskann = config.diskann || false;
|
||||
this.useHnsw = config.hnsw || false;
|
||||
this.dbName = validateIdentifier(config.dbname || "vector_store", "dbname");
|
||||
this.useDirectConnection = !!getConnectionString(config);
|
||||
this.dbName = this.useDirectConnection
|
||||
? ""
|
||||
: validateIdentifier(config.dbname || "vector_store", "dbname");
|
||||
this.config = config;
|
||||
|
||||
this.client = new Client({
|
||||
database: "postgres", // Initially connect to default postgres database
|
||||
user: config.user,
|
||||
password: config.password,
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
});
|
||||
this.client = new Client(
|
||||
buildClientConfig(
|
||||
config,
|
||||
this.useDirectConnection ? undefined : "postgres",
|
||||
),
|
||||
);
|
||||
this.initialize().catch(console.error);
|
||||
}
|
||||
|
||||
@@ -210,29 +259,20 @@ export class PGVector implements VectorStore {
|
||||
try {
|
||||
await this.client.connect();
|
||||
|
||||
// Check if database exists
|
||||
const dbExists = await this.checkDatabaseExists(this.dbName);
|
||||
if (!dbExists) {
|
||||
await this.createDatabase(this.dbName);
|
||||
if (!this.useDirectConnection) {
|
||||
const dbExists = await this.checkDatabaseExists(this.dbName);
|
||||
if (!dbExists) {
|
||||
await this.createDatabase(this.dbName);
|
||||
}
|
||||
|
||||
await this.client.end();
|
||||
|
||||
this.client = new Client(buildClientConfig(this.config, this.dbName));
|
||||
await this.client.connect();
|
||||
}
|
||||
|
||||
// Disconnect from postgres database
|
||||
await this.client.end();
|
||||
|
||||
// Connect to the target database
|
||||
this.client = new Client({
|
||||
database: this.dbName,
|
||||
user: this.config.user,
|
||||
password: this.config.password,
|
||||
host: this.config.host,
|
||||
port: this.config.port,
|
||||
});
|
||||
await this.client.connect();
|
||||
|
||||
// Create vector extension
|
||||
await this.client.query("CREATE EXTENSION IF NOT EXISTS vector");
|
||||
|
||||
// Create memory_migrations table
|
||||
await this.client.query(`
|
||||
CREATE TABLE IF NOT EXISTS memory_migrations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -240,7 +280,6 @@ export class PGVector implements VectorStore {
|
||||
)
|
||||
`);
|
||||
|
||||
// Check if the collection exists
|
||||
const collections = await this.listCols();
|
||||
if (!collections.includes(this.collectionName)) {
|
||||
await this.createCol(this.config.embeddingModelDims);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { extractEntities } from "../src/utils/entity_extraction";
|
||||
|
||||
describe("extractEntities", () => {
|
||||
it("handles product lists, coordinated names, and identifiers", () => {
|
||||
const text =
|
||||
"User reported top inbound integration pages: OpenClaw 25,443, " +
|
||||
"Claude Code 8,916, Codex 2,573, Dify 656. " +
|
||||
"User compared Cartesia and Deepgram. " +
|
||||
"The email field for Mem0 lives at person.properties.email. " +
|
||||
"The qwen endpoint uses person.properties.email. " +
|
||||
"Johnson & Johnson was mentioned. " +
|
||||
"Glasses around my window. " +
|
||||
"On 2026-05-27 there were 90 days of stats.";
|
||||
|
||||
const entityTexts = new Set(
|
||||
extractEntities(text).map((entity) => entity.text),
|
||||
);
|
||||
const normalized = new Set(
|
||||
[...entityTexts].map((entityText) => entityText.toLowerCase()),
|
||||
);
|
||||
|
||||
for (const expected of [
|
||||
"OpenClaw",
|
||||
"Claude Code",
|
||||
"Codex",
|
||||
"Dify",
|
||||
"Cartesia",
|
||||
"Deepgram",
|
||||
"Mem0",
|
||||
]) {
|
||||
expect(entityTexts.has(expected)).toBe(true);
|
||||
}
|
||||
expect(entityTexts.has("person.properties.email")).toBe(true);
|
||||
expect(entityTexts.has("qwen endpoint")).toBe(true);
|
||||
expect(entityTexts.has("Johnson & Johnson")).toBe(true);
|
||||
expect(entityTexts.has("Johnson")).toBe(false);
|
||||
expect(normalized.has("top")).toBe(false);
|
||||
expect(normalized.has("glasses")).toBe(false);
|
||||
expect(entityTexts.has("Cartesia and Deepgram")).toBe(false);
|
||||
expect(entityTexts.has("Claude Code 8,916")).toBe(false);
|
||||
for (const rejected of ["8,916", "2,573", "656", "2026-05-27", "90"]) {
|
||||
expect(entityTexts.has(rejected)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -92,6 +92,16 @@ jest.mock("../src/llms/deepseek", () => ({
|
||||
.fn()
|
||||
.mockImplementation((config) => ({ type: "deepseek-llm", config })),
|
||||
}));
|
||||
jest.mock("../src/llms/litellm", () => ({
|
||||
LiteLLM: jest
|
||||
.fn()
|
||||
.mockImplementation((config) => ({ type: "litellm-llm", config })),
|
||||
}));
|
||||
jest.mock("../src/llms/minimax", () => ({
|
||||
MiniMaxLLM: jest
|
||||
.fn()
|
||||
.mockImplementation((config) => ({ type: "minimax-llm", config })),
|
||||
}));
|
||||
|
||||
jest.mock("../src/vector_stores/qdrant", () => ({
|
||||
Qdrant: jest
|
||||
@@ -206,6 +216,8 @@ describe("LLMFactory", () => {
|
||||
["langchain"],
|
||||
["lmstudio"],
|
||||
["deepseek"],
|
||||
["litellm"],
|
||||
["minimax"],
|
||||
])("creates LLM for provider '%s'", (provider) => {
|
||||
expect(() => LLMFactory.create(provider, dummyLLMConfig)).not.toThrow();
|
||||
});
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/// <reference types="jest" />
|
||||
/**
|
||||
* Together LLM — unit tests (mocked OpenAI).
|
||||
* LiteLLM — unit tests (mocked OpenAI).
|
||||
*/
|
||||
|
||||
import { TogetherLLM } from "../src/llms/together";
|
||||
import { LiteLLM } from "../src/llms/litellm";
|
||||
|
||||
const mockCreate = jest.fn();
|
||||
|
||||
@@ -13,17 +13,12 @@ jest.mock("openai", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
describe("TogetherLLM (unit)", () => {
|
||||
describe("LiteLLM (unit)", () => {
|
||||
beforeEach(() => mockCreate.mockClear());
|
||||
|
||||
it("throws when no API key is provided", () => {
|
||||
const original = process.env.TOGETHER_API_KEY;
|
||||
delete process.env.TOGETHER_API_KEY;
|
||||
try {
|
||||
expect(() => new TogetherLLM({})).toThrow("Together API key is required");
|
||||
} finally {
|
||||
if (original !== undefined) process.env.TOGETHER_API_KEY = original;
|
||||
}
|
||||
it("uses default baseURL when none is provided", () => {
|
||||
const llm = new LiteLLM({});
|
||||
expect(llm).toBeDefined();
|
||||
});
|
||||
|
||||
it("generateResponse() returns a text response", async () => {
|
||||
@@ -39,7 +34,7 @@ describe("TogetherLLM (unit)", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const llm = new TogetherLLM({ apiKey: "test-key" });
|
||||
const llm = new LiteLLM({ baseURL: "http://localhost:4000" });
|
||||
const result = await llm.generateResponse([
|
||||
{ role: "user", content: "Hi" },
|
||||
]);
|
||||
@@ -68,7 +63,7 @@ describe("TogetherLLM (unit)", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const llm = new TogetherLLM({ apiKey: "test-key" });
|
||||
const llm = new LiteLLM({});
|
||||
const result = await llm.generateResponse(
|
||||
[{ role: "user", content: "What is the weather?" }],
|
||||
undefined,
|
||||
@@ -85,11 +80,11 @@ describe("TogetherLLM (unit)", () => {
|
||||
it("generateResponse() wraps API errors with a clear message", async () => {
|
||||
mockCreate.mockRejectedValueOnce(new Error("Connection refused"));
|
||||
|
||||
const llm = new TogetherLLM({ apiKey: "test-key" });
|
||||
const llm = new LiteLLM({});
|
||||
|
||||
await expect(
|
||||
llm.generateResponse([{ role: "user", content: "Hi" }]),
|
||||
).rejects.toThrow("Together LLM failed: Connection refused");
|
||||
).rejects.toThrow("LiteLLM failed: Connection refused");
|
||||
});
|
||||
|
||||
it("generateChat() returns LLMResponse shape", async () => {
|
||||
@@ -101,7 +96,7 @@ describe("TogetherLLM (unit)", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const llm = new TogetherLLM({ apiKey: "test-key" });
|
||||
const llm = new LiteLLM({});
|
||||
const result = await llm.generateChat([
|
||||
{ role: "user", content: "Help me" },
|
||||
]);
|
||||
@@ -115,10 +110,22 @@ describe("TogetherLLM (unit)", () => {
|
||||
it("generateChat() wraps API errors with a clear message", async () => {
|
||||
mockCreate.mockRejectedValueOnce(new Error("Timeout"));
|
||||
|
||||
const llm = new TogetherLLM({ apiKey: "test-key" });
|
||||
const llm = new LiteLLM({});
|
||||
|
||||
await expect(
|
||||
llm.generateChat([{ role: "user", content: "Hi" }]),
|
||||
).rejects.toThrow("Together LLM failed: Timeout");
|
||||
).rejects.toThrow("LiteLLM failed: Timeout");
|
||||
});
|
||||
|
||||
it("respects LITELLM_API_BASE env var", () => {
|
||||
const original = process.env.LITELLM_API_BASE;
|
||||
process.env.LITELLM_API_BASE = "http://custom-proxy:8080";
|
||||
try {
|
||||
const llm = new LiteLLM({});
|
||||
expect(llm).toBeDefined();
|
||||
} finally {
|
||||
if (original !== undefined) process.env.LITELLM_API_BASE = original;
|
||||
else delete process.env.LITELLM_API_BASE;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -314,4 +314,27 @@ describe("Memory Input Validation", () => {
|
||||
expect(result.results).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteAll() entity ID validation", () => {
|
||||
it("should throw error when userId is whitespace-only", async () => {
|
||||
await expect(memory.deleteAll({ userId: " " })).rejects.toThrow(
|
||||
"Invalid userId",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when userId contains internal whitespace", async () => {
|
||||
await expect(memory.deleteAll({ userId: "user 123" })).rejects.toThrow(
|
||||
"Invalid userId: cannot contain whitespace",
|
||||
);
|
||||
});
|
||||
|
||||
it("should trim userId before listing memories", async () => {
|
||||
const listSpy = jest.spyOn(memory["vectorStore"], "list");
|
||||
listSpy.mockResolvedValue([[], null]);
|
||||
|
||||
await memory.deleteAll({ userId: " alice " });
|
||||
|
||||
expect(listSpy).toHaveBeenCalledWith({ user_id: "alice" });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
/// <reference types="jest" />
|
||||
/**
|
||||
* MiniMax LLM - unit tests (mocked OpenAI).
|
||||
*/
|
||||
|
||||
let capturedConstructorArgs: any;
|
||||
const mockCreate = jest.fn();
|
||||
|
||||
jest.mock("openai", () => {
|
||||
return jest.fn().mockImplementation((args: any) => {
|
||||
capturedConstructorArgs = args;
|
||||
return {
|
||||
chat: { completions: { create: mockCreate } },
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
import { MiniMaxLLM } from "../src/llms/minimax";
|
||||
|
||||
describe("MiniMaxLLM (unit)", () => {
|
||||
beforeEach(() => {
|
||||
capturedConstructorArgs = undefined;
|
||||
mockCreate.mockClear();
|
||||
delete process.env.MINIMAX_API_KEY;
|
||||
delete process.env.MINIMAX_API_BASE;
|
||||
});
|
||||
|
||||
it("throws when no API key is provided", () => {
|
||||
expect(() => new MiniMaxLLM({})).toThrow("MiniMax API key is required");
|
||||
});
|
||||
|
||||
it("uses MiniMax defaults with an explicit API key", () => {
|
||||
new MiniMaxLLM({ apiKey: "test-key" });
|
||||
|
||||
expect(capturedConstructorArgs).toMatchObject({
|
||||
apiKey: "test-key",
|
||||
baseURL: "https://api.minimax.io/v1",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses environment variables when config does not provide credentials", () => {
|
||||
process.env.MINIMAX_API_KEY = "env-key";
|
||||
process.env.MINIMAX_API_BASE = "https://example.minimax.test/v1";
|
||||
|
||||
new MiniMaxLLM({});
|
||||
|
||||
expect(capturedConstructorArgs).toMatchObject({
|
||||
apiKey: "env-key",
|
||||
baseURL: "https://example.minimax.test/v1",
|
||||
});
|
||||
});
|
||||
|
||||
it("config values take precedence over environment variables", () => {
|
||||
process.env.MINIMAX_API_KEY = "env-key";
|
||||
process.env.MINIMAX_API_BASE = "https://env.minimax.test/v1";
|
||||
|
||||
new MiniMaxLLM({
|
||||
apiKey: "config-key",
|
||||
baseURL: "https://config.minimax.test/v1",
|
||||
model: "MiniMax-M1",
|
||||
});
|
||||
|
||||
expect(capturedConstructorArgs).toMatchObject({
|
||||
apiKey: "config-key",
|
||||
baseURL: "https://config.minimax.test/v1",
|
||||
});
|
||||
});
|
||||
|
||||
it("generateResponse() returns a text response", async () => {
|
||||
mockCreate.mockResolvedValueOnce({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: "Hello from MiniMax",
|
||||
role: "assistant",
|
||||
tool_calls: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const llm = new MiniMaxLLM({ apiKey: "test-key" });
|
||||
const result = await llm.generateResponse([
|
||||
{ role: "user", content: "Hi" },
|
||||
]);
|
||||
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ model: "MiniMax-M2.7" }),
|
||||
);
|
||||
expect(result).toBe("Hello from MiniMax");
|
||||
});
|
||||
|
||||
it("generateResponse() handles tool calls", async () => {
|
||||
mockCreate.mockResolvedValueOnce({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: "",
|
||||
role: "assistant",
|
||||
tool_calls: [
|
||||
{
|
||||
function: {
|
||||
name: "search_memory",
|
||||
arguments: '{"query": "alice"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const llm = new MiniMaxLLM({ apiKey: "test-key" });
|
||||
const result = await llm.generateResponse(
|
||||
[{ role: "user", content: "Find Alice" }],
|
||||
undefined,
|
||||
[{ type: "function", function: { name: "search_memory" } }],
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
content: "",
|
||||
role: "assistant",
|
||||
toolCalls: [{ name: "search_memory", arguments: '{"query": "alice"}' }],
|
||||
});
|
||||
});
|
||||
|
||||
it("generateResponse() wraps API errors with a clear message", async () => {
|
||||
mockCreate.mockRejectedValueOnce(new Error("Connection refused"));
|
||||
|
||||
const llm = new MiniMaxLLM({ apiKey: "test-key" });
|
||||
|
||||
await expect(
|
||||
llm.generateResponse([{ role: "user", content: "Hi" }]),
|
||||
).rejects.toThrow("MiniMax 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 MiniMaxLLM({ 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 MiniMaxLLM({ apiKey: "test-key" });
|
||||
|
||||
await expect(
|
||||
llm.generateChat([{ role: "user", content: "Hi" }]),
|
||||
).rejects.toThrow("MiniMax LLM failed: Timeout");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
/// <reference types="jest" />
|
||||
|
||||
jest.mock("pg", () => {
|
||||
const Client = jest.fn().mockImplementation(() => ({
|
||||
connect: jest.fn().mockResolvedValue(undefined),
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
/// <reference types="jest" />
|
||||
|
||||
const searchRows = [
|
||||
{
|
||||
id: "a",
|
||||
@@ -23,9 +21,13 @@ const searchRows = [
|
||||
},
|
||||
];
|
||||
|
||||
const mockState = {
|
||||
databaseExists: true,
|
||||
};
|
||||
|
||||
function mockPgQuery(sql: string) {
|
||||
if (sql.includes("SELECT 1 FROM pg_database")) {
|
||||
return { rows: [{ "?column?": 1 }] };
|
||||
return { rows: mockState.databaseExists ? [{ "?column?": 1 }] : [] };
|
||||
}
|
||||
|
||||
if (sql.includes("FROM information_schema.tables")) {
|
||||
@@ -69,13 +71,129 @@ jest.mock("pg", () => {
|
||||
|
||||
import { PGVector } from "../src/vector_stores/pgvector";
|
||||
|
||||
describe("PGVector - search()", () => {
|
||||
function getClientQueries(client: { query: jest.Mock }) {
|
||||
return client.query.mock.calls.map(([sql]) => sql as string);
|
||||
}
|
||||
|
||||
describe("PGVector", () => {
|
||||
beforeEach(() => {
|
||||
const pg = require("pg");
|
||||
mockState.databaseExists = true;
|
||||
pg.__mock.Client.mockClear();
|
||||
pg.__mock.clients.length = 0;
|
||||
});
|
||||
|
||||
test("uses one direct client for connectionString mode and skips bootstrap database creation", async () => {
|
||||
mockState.databaseExists = false;
|
||||
|
||||
const ssl = { rejectUnauthorized: false };
|
||||
const store = new PGVector({
|
||||
collectionName: "memories",
|
||||
connectionString:
|
||||
"postgresql://postgres:postgres@db.example.com:5432/neondb",
|
||||
ssl,
|
||||
embeddingModelDims: 3,
|
||||
dimension: 3,
|
||||
} as any);
|
||||
|
||||
await store.initialize();
|
||||
|
||||
const pg = require("pg");
|
||||
expect(pg.__mock.Client).toHaveBeenCalledTimes(1);
|
||||
expect(pg.__mock.Client).toHaveBeenCalledWith({
|
||||
connectionString:
|
||||
"postgresql://postgres:postgres@db.example.com:5432/neondb",
|
||||
ssl,
|
||||
});
|
||||
|
||||
const directClient = pg.__mock.clients[0];
|
||||
const queries = getClientQueries(directClient);
|
||||
|
||||
expect(queries).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("SELECT 1 FROM pg_database"),
|
||||
]),
|
||||
);
|
||||
expect(queries).not.toEqual(
|
||||
expect.arrayContaining([expect.stringContaining("CREATE DATABASE")]),
|
||||
);
|
||||
expect(queries).toEqual(
|
||||
expect.arrayContaining([
|
||||
"CREATE EXTENSION IF NOT EXISTS vector",
|
||||
expect.stringContaining("FROM information_schema.tables"),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps the split-field bootstrap flow when connectionString is absent", async () => {
|
||||
mockState.databaseExists = false;
|
||||
const ssl = { rejectUnauthorized: false };
|
||||
|
||||
const store = new PGVector({
|
||||
collectionName: "memories",
|
||||
user: "postgres",
|
||||
password: "postgres",
|
||||
host: "localhost",
|
||||
port: 5432,
|
||||
dbname: "vector_store",
|
||||
ssl,
|
||||
embeddingModelDims: 3,
|
||||
dimension: 3,
|
||||
} as any);
|
||||
|
||||
await store.initialize();
|
||||
|
||||
const pg = require("pg");
|
||||
expect(pg.__mock.Client).toHaveBeenCalledTimes(2);
|
||||
expect(pg.__mock.Client).toHaveBeenNthCalledWith(1, {
|
||||
database: "postgres",
|
||||
user: "postgres",
|
||||
password: "postgres",
|
||||
host: "localhost",
|
||||
port: 5432,
|
||||
ssl,
|
||||
});
|
||||
expect(pg.__mock.Client).toHaveBeenNthCalledWith(2, {
|
||||
database: "vector_store",
|
||||
user: "postgres",
|
||||
password: "postgres",
|
||||
host: "localhost",
|
||||
port: 5432,
|
||||
ssl,
|
||||
});
|
||||
|
||||
const bootstrapClient = pg.__mock.clients[0];
|
||||
const activeClient = pg.__mock.clients[1];
|
||||
const bootstrapQueries = getClientQueries(bootstrapClient);
|
||||
|
||||
expect(bootstrapQueries).toEqual(
|
||||
expect.arrayContaining([
|
||||
"SELECT 1 FROM pg_database WHERE datname = $1",
|
||||
'CREATE DATABASE "vector_store"',
|
||||
]),
|
||||
);
|
||||
expect(bootstrapClient.end).toHaveBeenCalledTimes(1);
|
||||
expect(getClientQueries(activeClient)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"CREATE EXTENSION IF NOT EXISTS vector",
|
||||
expect.stringContaining("FROM information_schema.tables"),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test("throws when connectionString is absent and split-field params are missing", () => {
|
||||
expect(
|
||||
() =>
|
||||
new PGVector({
|
||||
collectionName: "memories",
|
||||
embeddingModelDims: 3,
|
||||
dimension: 3,
|
||||
} as any),
|
||||
).toThrow(
|
||||
"PGVector requires either connectionString or user, password, host, port",
|
||||
);
|
||||
});
|
||||
|
||||
test("returns similarity score (1 - distance) clamped to [0, 1]", async () => {
|
||||
const store = new PGVector({
|
||||
collectionName: "memories",
|
||||
|
||||
+14
-10
@@ -344,24 +344,26 @@ class MemoryClient:
|
||||
Args:
|
||||
memory_id: The ID of the memory to update.
|
||||
options: Typed options (UpdateMemoryOptions) with text, metadata,
|
||||
and/or timestamp fields.
|
||||
**kwargs: Alternatively pass text, metadata, timestamp as keyword args.
|
||||
timestamp, and/or expiration_date fields.
|
||||
**kwargs: Alternatively pass text, metadata, timestamp, or
|
||||
expiration_date as keyword args.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: The response from the server.
|
||||
|
||||
Raises:
|
||||
ValueError: If none of text, metadata, or timestamp are provided.
|
||||
ValueError: If none of text, metadata, timestamp, or expiration_date are provided.
|
||||
|
||||
Example:
|
||||
>>> client.update("mem_123", UpdateMemoryOptions(text="Updated text"))
|
||||
>>> client.update("mem_123", text="Updated text")
|
||||
>>> client.update("mem_123", expiration_date=None)
|
||||
"""
|
||||
payload = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs}
|
||||
payload = {k: v for k, v in payload.items() if v is not None}
|
||||
payload = {k: v for k, v in payload.items() if v is not None or k == "expiration_date"}
|
||||
|
||||
if not payload:
|
||||
raise ValueError("At least one of text, metadata, or timestamp must be provided for update.")
|
||||
raise ValueError("At least one of text, metadata, timestamp, or expiration_date must be provided for update.")
|
||||
|
||||
capture_client_event("client.update", self, {"memory_id": memory_id, "sync_type": "sync"})
|
||||
params = self._prepare_params()
|
||||
@@ -1260,24 +1262,26 @@ class AsyncMemoryClient:
|
||||
Args:
|
||||
memory_id: The ID of the memory to update.
|
||||
options: Typed options (UpdateMemoryOptions) with text, metadata,
|
||||
and/or timestamp fields.
|
||||
**kwargs: Alternatively pass text, metadata, timestamp as keyword args.
|
||||
timestamp, and/or expiration_date fields.
|
||||
**kwargs: Alternatively pass text, metadata, timestamp, or
|
||||
expiration_date as keyword args.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: The response from the server.
|
||||
|
||||
Raises:
|
||||
ValueError: If none of text, metadata, or timestamp are provided.
|
||||
ValueError: If none of text, metadata, timestamp, or expiration_date are provided.
|
||||
|
||||
Example:
|
||||
>>> await client.update("mem_123", UpdateMemoryOptions(text="Updated text"))
|
||||
>>> await client.update("mem_123", text="Updated text")
|
||||
>>> await client.update("mem_123", expiration_date=None)
|
||||
"""
|
||||
payload = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs}
|
||||
payload = {k: v for k, v in payload.items() if v is not None}
|
||||
payload = {k: v for k, v in payload.items() if v is not None or k == "expiration_date"}
|
||||
|
||||
if not payload:
|
||||
raise ValueError("At least one of text, metadata, or timestamp must be provided for update.")
|
||||
raise ValueError("At least one of text, metadata, timestamp, or expiration_date must be provided for update.")
|
||||
|
||||
capture_client_event("client.update", self, {"memory_id": memory_id, "sync_type": "async"})
|
||||
params = self._prepare_params()
|
||||
|
||||
@@ -29,6 +29,7 @@ class AddMemoryOptions(BaseModel):
|
||||
)
|
||||
custom_instructions: Optional[str] = Field(default=None, description="Custom instructions for fact extraction")
|
||||
timestamp: Optional[int] = Field(default=None, description="Unix timestamp for the memory")
|
||||
expiration_date: Optional[str] = Field(default=None, description="Expiration date in YYYY-MM-DD format")
|
||||
structured_data_schema: Optional[Dict[str, Any]] = Field(
|
||||
default=None, description="Schema for structured data extraction"
|
||||
)
|
||||
@@ -50,6 +51,7 @@ class SearchMemoryOptions(BaseModel):
|
||||
threshold: Optional[float] = Field(default=None, description="Minimum similarity score threshold")
|
||||
fields: Optional[List[str]] = Field(default=None, description="Fields to include in the response")
|
||||
categories: Optional[List[str]] = Field(default=None, description="Categories to filter by")
|
||||
show_expired: Optional[bool] = Field(default=None, description="Whether to include expired memories")
|
||||
|
||||
|
||||
class GetAllMemoryOptions(BaseModel):
|
||||
@@ -71,6 +73,7 @@ class GetAllMemoryOptions(BaseModel):
|
||||
default=None, description="Filter memories created on or before this date (ISO 8601)"
|
||||
)
|
||||
categories: Optional[List[str]] = Field(default=None, description="Categories to filter by")
|
||||
show_expired: Optional[bool] = Field(default=None, description="Whether to include expired memories")
|
||||
|
||||
|
||||
class DeleteAllMemoryOptions(BaseModel):
|
||||
@@ -91,6 +94,7 @@ class UpdateMemoryOptions(BaseModel):
|
||||
text: Optional[str] = Field(default=None, description="New text content for the memory")
|
||||
metadata: Optional[Dict[str, Any]] = Field(default=None, description="Updated metadata")
|
||||
timestamp: Optional[Union[int, float, str]] = Field(default=None, description="Updated timestamp")
|
||||
expiration_date: Optional[str] = Field(default=None, description="Expiration date in YYYY-MM-DD format, or None to clear")
|
||||
|
||||
|
||||
class ProjectUpdateOptions(BaseModel):
|
||||
|
||||
@@ -18,6 +18,12 @@ class OpenSearchConfig(BaseModel):
|
||||
"RequestsHttpConnection", description="Connection class for OpenSearch"
|
||||
)
|
||||
pool_maxsize: int = Field(20, description="Maximum number of connections in the pool")
|
||||
auto_refresh: bool = Field(
|
||||
False,
|
||||
description="Automatically refresh index after insert operations to make documents "
|
||||
"immediately searchable. Disabled by default for OpenSearch Serverless compatibility. "
|
||||
"OpenSearch automatically refreshes indices every ~1 second, so most users don't need this.",
|
||||
)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
|
||||
+33
-2
@@ -1,6 +1,7 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Dict, List, Optional
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
try:
|
||||
from groq import Groq
|
||||
@@ -11,6 +12,8 @@ from mem0.configs.llms.base import BaseLlmConfig
|
||||
from mem0.llms.base import LLMBase
|
||||
from mem0.memory.utils import extract_json
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class GroqLLM(LLMBase):
|
||||
def __init__(self, config: Optional[BaseLlmConfig] = None):
|
||||
@@ -22,6 +25,24 @@ class GroqLLM(LLMBase):
|
||||
api_key = self.config.api_key or os.getenv("GROQ_API_KEY")
|
||||
self.client = Groq(api_key=api_key)
|
||||
|
||||
@staticmethod
|
||||
def _supports_json_mode(model: Optional[Union[str, Dict]]) -> bool:
|
||||
"""
|
||||
Groq's compound agentic systems (e.g. ``groq/compound``, ``groq/compound-mini``)
|
||||
do not support the JSON ``response_format`` and return empty or non-JSON content
|
||||
when it is requested. See https://console.groq.com/docs/structured-outputs.
|
||||
|
||||
Non-string models (the config allows a dict) are assumed to support JSON mode,
|
||||
preserving prior behavior.
|
||||
"""
|
||||
if not isinstance(model, str):
|
||||
return True
|
||||
# Strip provider prefixes (e.g. "groq/compound-mini" -> "compound-mini"),
|
||||
# mirroring the _is_reasoning_model heuristic in LLMBase, so the match
|
||||
# targets the compound family rather than any name containing the substring.
|
||||
base_model = model.lower().rsplit("/", 1)[-1]
|
||||
return not base_model.startswith("compound")
|
||||
|
||||
def _parse_response(self, response, tools):
|
||||
"""
|
||||
Process the response based on whether tools are used or not.
|
||||
@@ -79,7 +100,17 @@ class GroqLLM(LLMBase):
|
||||
"top_p": self.config.top_p,
|
||||
}
|
||||
if response_format:
|
||||
params["response_format"] = response_format
|
||||
requests_json = isinstance(response_format, dict) and response_format.get("type") in (
|
||||
"json_object",
|
||||
"json_schema",
|
||||
)
|
||||
if requests_json and not self._supports_json_mode(self.config.model):
|
||||
logger.debug(
|
||||
f"Model '{self.config.model}' does not support JSON response_format; "
|
||||
"sending the request without it."
|
||||
)
|
||||
else:
|
||||
params["response_format"] = response_format
|
||||
if tools:
|
||||
params["tools"] = tools
|
||||
params["tool_choice"] = tool_choice
|
||||
|
||||
+250
-52
@@ -9,7 +9,7 @@ import time
|
||||
import uuid
|
||||
import warnings
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from pydantic import ValidationError
|
||||
@@ -81,6 +81,14 @@ warnings.filterwarnings("ignore", category=DeprecationWarning, message=".*swigva
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _vector_store_list_rows(listed):
|
||||
if isinstance(listed, (list, tuple)) and listed and isinstance(listed[0], list):
|
||||
return listed[0]
|
||||
if isinstance(listed, (list, tuple)):
|
||||
return listed
|
||||
return []
|
||||
|
||||
|
||||
# Fields that hold runtime auth/connection objects and must be preserved.
|
||||
# These are non-serializable objects (e.g. AWSV4SignerAuth, RequestsHttpConnection)
|
||||
# needed by clients like OpenSearch — not sensitive strings to redact.
|
||||
@@ -370,9 +378,37 @@ def _entity_collection_name(provider: str, collection_name: str) -> str:
|
||||
return f"{collection_name}{separator}entities"
|
||||
|
||||
|
||||
def _normalize_expiration_date(value: Any) -> Optional[str]:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date().isoformat()
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return date.fromisoformat(value).isoformat()
|
||||
except ValueError as exc:
|
||||
raise ValueError("expiration_date must be a valid date in YYYY-MM-DD format.") from exc
|
||||
raise ValueError("expiration_date must be a date string in YYYY-MM-DD format.")
|
||||
|
||||
|
||||
def _payload_is_expired(payload: Optional[Dict[str, Any]]) -> bool:
|
||||
if not payload:
|
||||
return False
|
||||
expiration_date = payload.get("expiration_date")
|
||||
if not expiration_date:
|
||||
return False
|
||||
try:
|
||||
return date.fromisoformat(str(expiration_date)) < datetime.now(timezone.utc).date()
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
setup_config()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_UNSET = object()
|
||||
_PROJECT_UPDATE_UNSUPPORTED_ERROR = "Project updates are not supported by the OSS Memory SDK."
|
||||
|
||||
|
||||
@@ -499,22 +535,49 @@ class Memory(MemoryBase):
|
||||
)
|
||||
return self._entity_store
|
||||
|
||||
@staticmethod
|
||||
def _normalize_entity_text(value: str) -> str:
|
||||
return " ".join(value.strip().lower().split())
|
||||
|
||||
def _existing_entities_by_text(self, filters):
|
||||
"""Return existing entity rows keyed by normalized payload data."""
|
||||
try:
|
||||
listed = self.entity_store.list(filters=filters, top_k=10000)
|
||||
except Exception as e:
|
||||
logger.debug(f"Exact entity lookup failed, falling back to semantic dedup: {e}")
|
||||
return {}
|
||||
|
||||
rows_by_text = {}
|
||||
for row in _vector_store_list_rows(listed):
|
||||
payload = getattr(row, "payload", None) or {}
|
||||
text = payload.get("data")
|
||||
if not isinstance(text, str):
|
||||
continue
|
||||
normalized = self._normalize_entity_text(text)
|
||||
if normalized and normalized not in rows_by_text:
|
||||
rows_by_text[normalized] = row
|
||||
return rows_by_text
|
||||
|
||||
def _upsert_entity(self, entity_text, entity_type, memory_id, filters):
|
||||
"""Upsert an entity into the entity store, linking it to a memory."""
|
||||
try:
|
||||
entity_embedding = self.embedding_model.embed(entity_text, "add")
|
||||
search_filters = {k: v for k, v in filters.items() if k in ("user_id", "agent_id", "run_id") and v}
|
||||
exact_match = self._existing_entities_by_text(search_filters).get(self._normalize_entity_text(entity_text))
|
||||
|
||||
existing = self.entity_store.search(
|
||||
query=entity_text,
|
||||
vectors=entity_embedding,
|
||||
top_k=1,
|
||||
filters=search_filters,
|
||||
)
|
||||
existing = []
|
||||
if exact_match is None:
|
||||
existing = self.entity_store.search(
|
||||
query=entity_text,
|
||||
vectors=entity_embedding,
|
||||
top_k=1,
|
||||
filters=search_filters,
|
||||
)
|
||||
|
||||
if existing and existing[0].score >= 0.95:
|
||||
semantic_match = existing[0] if existing and existing[0].score >= 0.95 else None
|
||||
match = exact_match or semantic_match
|
||||
if match:
|
||||
# Update existing entity's linked_memory_ids
|
||||
match = existing[0]
|
||||
payload = match.payload or {}
|
||||
linked_ids = payload.get("linked_memory_ids", [])
|
||||
if memory_id not in linked_ids:
|
||||
@@ -609,7 +672,7 @@ class Memory(MemoryBase):
|
||||
return
|
||||
seen = set()
|
||||
for entity_type, entity_text in entities:
|
||||
key = entity_text.strip().lower()
|
||||
key = self._normalize_entity_text(entity_text)
|
||||
if not key or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
@@ -659,6 +722,7 @@ class Memory(MemoryBase):
|
||||
run_id: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
timestamp: Optional[Any] = None,
|
||||
expiration_date: Optional[Any] = None,
|
||||
infer: bool = True,
|
||||
memory_type: Optional[str] = None,
|
||||
prompt: Optional[str] = None,
|
||||
@@ -677,6 +741,8 @@ class Memory(MemoryBase):
|
||||
run_id (str, optional): ID of the run creating the memory. Defaults to None.
|
||||
metadata (dict, optional): Metadata to store with the memory. Defaults to None.
|
||||
timestamp (Any, optional): Platform-only temporal parameter. Not supported in OSS.
|
||||
expiration_date (Any, optional): Date in YYYY-MM-DD format. Expired memories are hidden
|
||||
from search and get_all unless show_expired is True.
|
||||
infer (bool, optional): If True (default), an LLM is used to extract key facts from
|
||||
'messages' and decide whether to add, update, or delete related memories.
|
||||
If False, 'messages' are added as raw memories directly.
|
||||
@@ -702,6 +768,7 @@ class Memory(MemoryBase):
|
||||
if timestamp is not None:
|
||||
raise ValueError(get_temporal_feature_error_message("sync", "add", "timestamp"))
|
||||
|
||||
normalized_expiration_date = _normalize_expiration_date(expiration_date)
|
||||
temporal_usage_notice = detect_temporal_usage_from_metadata(metadata)
|
||||
processed_metadata, effective_filters = _build_filters_and_metadata(
|
||||
user_id=user_id,
|
||||
@@ -709,6 +776,8 @@ class Memory(MemoryBase):
|
||||
run_id=run_id,
|
||||
input_metadata=metadata,
|
||||
)
|
||||
if normalized_expiration_date is not None:
|
||||
processed_metadata["expiration_date"] = normalized_expiration_date
|
||||
|
||||
if memory_type is not None and memory_type != MemoryType.PROCEDURAL.value:
|
||||
raise Mem0ValidationError(
|
||||
@@ -971,7 +1040,7 @@ class Memory(MemoryBase):
|
||||
for idx, (memory_id, text, embedding, payload) in enumerate(records):
|
||||
entities = all_entities[idx] if idx < len(all_entities) else []
|
||||
for entity_type, entity_text in entities:
|
||||
key = entity_text.strip().lower()
|
||||
key = self._normalize_entity_text(entity_text)
|
||||
if key in global_entities:
|
||||
global_entities[key][2].add(memory_id)
|
||||
else:
|
||||
@@ -1009,6 +1078,7 @@ class Memory(MemoryBase):
|
||||
if valid:
|
||||
valid_indices, valid_keys = zip(*valid)
|
||||
valid_vectors = [entity_embeddings[i] for i in valid_indices]
|
||||
exact_matches = self._existing_entities_by_text(search_filters)
|
||||
|
||||
# 7c: Batch search for existing entities
|
||||
valid_texts = [global_entities[k][1] for k in valid_keys]
|
||||
@@ -1024,10 +1094,12 @@ class Memory(MemoryBase):
|
||||
for j, key in enumerate(valid_keys):
|
||||
entity_type, entity_text, memory_ids = global_entities[key]
|
||||
matches = existing_matches[j] if j < len(existing_matches) else []
|
||||
exact_match = exact_matches.get(key)
|
||||
|
||||
if matches and matches[0].score >= 0.95:
|
||||
semantic_match = matches[0] if matches and matches[0].score >= 0.95 else None
|
||||
match = exact_match or semantic_match
|
||||
if match:
|
||||
# Update existing entity
|
||||
match = matches[0]
|
||||
payload = match.payload or {}
|
||||
linked = set(payload.get("linked_memory_ids", []))
|
||||
linked |= memory_ids
|
||||
@@ -1103,6 +1175,7 @@ class Memory(MemoryBase):
|
||||
"actor_id",
|
||||
"role",
|
||||
"attributed_to",
|
||||
"expiration_date",
|
||||
]
|
||||
|
||||
core_and_promoted_keys = {"data", "hash", "created_at", "updated_at", "id", "text_lemmatized", "attributed_to", *promoted_payload_keys}
|
||||
@@ -1131,6 +1204,7 @@ class Memory(MemoryBase):
|
||||
*,
|
||||
filters: Optional[Dict[str, Any]] = None,
|
||||
top_k: int = 20,
|
||||
show_expired: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
@@ -1141,6 +1215,7 @@ class Memory(MemoryBase):
|
||||
Must contain at least one of: user_id, agent_id, run_id.
|
||||
Example: filters={"user_id": "u1", "agent_id": "a1"}
|
||||
top_k (int, optional): The maximum number of memories to return. Defaults to 20.
|
||||
show_expired (bool, optional): Include expired memories. Defaults to False.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing a list of memories under the "results" key.
|
||||
@@ -1179,6 +1254,7 @@ class Memory(MemoryBase):
|
||||
)
|
||||
|
||||
limit = top_k
|
||||
fetch_limit = limit if show_expired else max(limit * 4, 60)
|
||||
scale_threshold_notice = detect_scale_threshold_from_top_k(top_k)
|
||||
|
||||
keys, encoded_ids = process_telemetry_filters(effective_filters)
|
||||
@@ -1186,7 +1262,7 @@ class Memory(MemoryBase):
|
||||
"mem0.get_all", self, {"limit": limit, "keys": keys, "encoded_ids": encoded_ids, "sync_type": "sync"}
|
||||
)
|
||||
|
||||
all_memories_result = self._get_all_from_vector_store(effective_filters, limit)
|
||||
all_memories_result = self._get_all_from_vector_store(effective_filters, fetch_limit, show_expired, limit)
|
||||
|
||||
if scale_threshold_notice:
|
||||
display_scale_threshold_notice(self, "sync", "get_all", *scale_threshold_notice)
|
||||
@@ -1194,7 +1270,7 @@ class Memory(MemoryBase):
|
||||
display_first_run_notice(self, "sync", "get_all")
|
||||
return {"results": all_memories_result}
|
||||
|
||||
def _get_all_from_vector_store(self, filters, limit):
|
||||
def _get_all_from_vector_store(self, filters, limit, show_expired=False, output_limit=None):
|
||||
memories_result = self.vector_store.list(filters=filters, top_k=limit)
|
||||
|
||||
# Handle different vector store return formats by inspecting first element
|
||||
@@ -1217,11 +1293,14 @@ class Memory(MemoryBase):
|
||||
"actor_id",
|
||||
"role",
|
||||
"attributed_to",
|
||||
"expiration_date",
|
||||
]
|
||||
core_and_promoted_keys = {"data", "hash", "created_at", "updated_at", "id", "text_lemmatized", "attributed_to", *promoted_payload_keys}
|
||||
|
||||
formatted_memories = []
|
||||
for mem in actual_memories:
|
||||
if not show_expired and _payload_is_expired(mem.payload):
|
||||
continue
|
||||
memory_item_dict = MemoryItem(
|
||||
id=mem.id,
|
||||
memory=mem.payload.get("data", ""),
|
||||
@@ -1239,6 +1318,8 @@ class Memory(MemoryBase):
|
||||
memory_item_dict["metadata"] = additional_metadata
|
||||
|
||||
formatted_memories.append(memory_item_dict)
|
||||
if output_limit is not None and len(formatted_memories) >= output_limit:
|
||||
break
|
||||
|
||||
return formatted_memories
|
||||
|
||||
@@ -1252,6 +1333,7 @@ class Memory(MemoryBase):
|
||||
rerank: bool = False,
|
||||
explain: bool = False,
|
||||
reference_date: Optional[Any] = None,
|
||||
show_expired: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
@@ -1284,6 +1366,7 @@ class Memory(MemoryBase):
|
||||
rerank (bool, optional): Whether to rerank results. Defaults to False.
|
||||
explain (bool, optional): Whether to include score_details for each result. Defaults to False.
|
||||
reference_date (Any, optional): Platform-only temporal parameter. Not supported in OSS.
|
||||
show_expired (bool, optional): Include expired memories. Defaults to False.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the search results under a "results" key.
|
||||
@@ -1355,7 +1438,9 @@ class Memory(MemoryBase):
|
||||
)
|
||||
|
||||
search_start = time.perf_counter()
|
||||
original_memories = self._search_vector_store(query, effective_filters, limit, threshold, explain=explain)
|
||||
original_memories = self._search_vector_store(
|
||||
query, effective_filters, limit, threshold, explain=explain, show_expired=show_expired
|
||||
)
|
||||
search_elapsed_seconds = time.perf_counter() - search_start
|
||||
|
||||
# Apply reranking if enabled and reranker is available
|
||||
@@ -1487,7 +1572,7 @@ class Memory(MemoryBase):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _search_vector_store(self, query, filters, limit, threshold=0.1, explain=False):
|
||||
def _search_vector_store(self, query, filters, limit, threshold=0.1, explain=False, show_expired=False):
|
||||
# Guard against None threshold (backward compat)
|
||||
if threshold is None:
|
||||
threshold = 0.1
|
||||
@@ -1528,11 +1613,14 @@ class Memory(MemoryBase):
|
||||
# Step 7: Build candidate set from semantic results
|
||||
candidates = []
|
||||
for mem in semantic_results:
|
||||
payload = mem.payload if hasattr(mem, 'payload') else {}
|
||||
if not show_expired and _payload_is_expired(payload):
|
||||
continue
|
||||
mem_id = str(mem.id)
|
||||
candidates.append({
|
||||
"id": mem_id,
|
||||
"score": mem.score,
|
||||
"payload": mem.payload if hasattr(mem, 'payload') else {},
|
||||
"payload": payload,
|
||||
})
|
||||
|
||||
# Step 8: Score and rank
|
||||
@@ -1553,6 +1641,7 @@ class Memory(MemoryBase):
|
||||
"actor_id",
|
||||
"role",
|
||||
"attributed_to",
|
||||
"expiration_date",
|
||||
]
|
||||
core_and_promoted_keys = {"data", "hash", "created_at", "updated_at", "id", "text_lemmatized", "attributed_to", *promoted_payload_keys}
|
||||
|
||||
@@ -1603,7 +1692,7 @@ class Memory(MemoryBase):
|
||||
seen = set()
|
||||
deduped = []
|
||||
for entity_type, entity_text in query_entities[:8]:
|
||||
key = entity_text.strip().lower()
|
||||
key = self._normalize_entity_text(entity_text)
|
||||
if key and key not in seen:
|
||||
seen.add(key)
|
||||
deduped.append((entity_type, entity_text))
|
||||
@@ -1670,14 +1759,21 @@ class Memory(MemoryBase):
|
||||
|
||||
return memory_boosts
|
||||
|
||||
def update(self, memory_id, data, metadata: Optional[Dict[str, Any]] = None):
|
||||
def update(
|
||||
self,
|
||||
memory_id,
|
||||
data: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
expiration_date: Any = _UNSET,
|
||||
):
|
||||
"""
|
||||
Update a memory by ID.
|
||||
|
||||
Args:
|
||||
memory_id (str): ID of the memory to update.
|
||||
data (str): New content to update the memory with.
|
||||
data (str, optional): New content to update the memory with.
|
||||
metadata (dict, optional): Metadata to update with the memory. Defaults to None.
|
||||
expiration_date (Any, optional): Date in YYYY-MM-DD format, or None to clear it.
|
||||
|
||||
Returns:
|
||||
dict: Success message indicating the memory was updated.
|
||||
@@ -1688,9 +1784,19 @@ class Memory(MemoryBase):
|
||||
"""
|
||||
capture_event("mem0.update", self, {"memory_id": memory_id, "sync_type": "sync"})
|
||||
|
||||
existing_embeddings = {data: self.embedding_model.embed(data, "update")}
|
||||
if data is None and metadata is None and expiration_date is _UNSET:
|
||||
raise ValueError("At least one of data, metadata, or expiration_date must be provided.")
|
||||
|
||||
self._update_memory(memory_id, data, existing_embeddings, metadata)
|
||||
update_metadata = deepcopy(metadata) if metadata is not None else None
|
||||
if expiration_date is not _UNSET:
|
||||
update_metadata = update_metadata or {}
|
||||
update_metadata["expiration_date"] = _normalize_expiration_date(expiration_date)
|
||||
|
||||
existing_embeddings = {}
|
||||
if data is not None:
|
||||
existing_embeddings[data] = self.embedding_model.embed(data, "update")
|
||||
|
||||
self._update_memory(memory_id, data, existing_embeddings, update_metadata)
|
||||
display_first_run_notice(self, "sync", "update")
|
||||
return {"message": "Memory updated successfully!"}
|
||||
|
||||
@@ -1724,6 +1830,10 @@ class Memory(MemoryBase):
|
||||
agent_id (str, optional): ID of the agent to delete memories for. Defaults to None.
|
||||
run_id (str, optional): ID of the run to delete memories for. Defaults to None.
|
||||
"""
|
||||
user_id = _validate_and_trim_entity_id(user_id, "user_id")
|
||||
agent_id = _validate_and_trim_entity_id(agent_id, "agent_id")
|
||||
run_id = _validate_and_trim_entity_id(run_id, "run_id")
|
||||
|
||||
filters: Dict[str, Any] = {}
|
||||
if user_id:
|
||||
filters["user_id"] = user_id
|
||||
@@ -1853,6 +1963,11 @@ class Memory(MemoryBase):
|
||||
raise ValueError(f"Memory with id {memory_id} not found. Please provide a valid 'memory_id'")
|
||||
|
||||
prev_value = existing_memory.payload.get("data")
|
||||
if data is None:
|
||||
data = prev_value
|
||||
if not isinstance(data, str):
|
||||
raise ValueError(f"Memory with id {memory_id} does not have text content to update")
|
||||
text_changed = data != prev_value
|
||||
|
||||
new_metadata = deepcopy(existing_memory.payload)
|
||||
if metadata is not None:
|
||||
@@ -1894,8 +2009,9 @@ class Memory(MemoryBase):
|
||||
# Entity-store cleanup: strip this memory's id from old-text entities,
|
||||
# then re-extract entities from the new text and link them back.
|
||||
session_filters = {k: new_metadata[k] for k in ("user_id", "agent_id", "run_id") if new_metadata.get(k)}
|
||||
self._remove_memory_from_entity_store(memory_id, session_filters)
|
||||
self._link_entities_for_memory(memory_id, data, session_filters)
|
||||
if text_changed:
|
||||
self._remove_memory_from_entity_store(memory_id, session_filters)
|
||||
self._link_entities_for_memory(memory_id, data, session_filters)
|
||||
|
||||
return memory_id
|
||||
|
||||
@@ -2045,22 +2161,51 @@ class AsyncMemory(MemoryBase):
|
||||
)
|
||||
return self._entity_store
|
||||
|
||||
@staticmethod
|
||||
def _normalize_entity_text(value: str) -> str:
|
||||
return " ".join(value.strip().lower().split())
|
||||
|
||||
def _existing_entities_by_text(self, filters):
|
||||
"""Return existing entity rows keyed by normalized payload data."""
|
||||
try:
|
||||
listed = self.entity_store.list(filters=filters, top_k=10000)
|
||||
except Exception as e:
|
||||
logger.debug(f"Exact entity lookup failed, falling back to semantic dedup: {e}")
|
||||
return {}
|
||||
|
||||
rows_by_text = {}
|
||||
for row in _vector_store_list_rows(listed):
|
||||
payload = getattr(row, "payload", None) or {}
|
||||
text = payload.get("data")
|
||||
if not isinstance(text, str):
|
||||
continue
|
||||
normalized = self._normalize_entity_text(text)
|
||||
if normalized and normalized not in rows_by_text:
|
||||
rows_by_text[normalized] = row
|
||||
return rows_by_text
|
||||
|
||||
async def _upsert_entity_async(self, entity_text, entity_type, memory_id, filters):
|
||||
"""Async variant of `_upsert_entity` — per-entity search-then-update-or-insert."""
|
||||
try:
|
||||
entity_embedding = await asyncio.to_thread(self.embedding_model.embed, entity_text, "add")
|
||||
search_filters = {k: v for k, v in filters.items() if k in ("user_id", "agent_id", "run_id") and v}
|
||||
exact_match = (
|
||||
await asyncio.to_thread(self._existing_entities_by_text, search_filters)
|
||||
).get(self._normalize_entity_text(entity_text))
|
||||
|
||||
existing = await asyncio.to_thread(
|
||||
self.entity_store.search,
|
||||
query=entity_text,
|
||||
vectors=entity_embedding,
|
||||
top_k=1,
|
||||
filters=search_filters,
|
||||
)
|
||||
existing = []
|
||||
if exact_match is None:
|
||||
existing = await asyncio.to_thread(
|
||||
self.entity_store.search,
|
||||
query=entity_text,
|
||||
vectors=entity_embedding,
|
||||
top_k=1,
|
||||
filters=search_filters,
|
||||
)
|
||||
|
||||
if existing and existing[0].score >= 0.95:
|
||||
match = existing[0]
|
||||
semantic_match = existing[0] if existing and existing[0].score >= 0.95 else None
|
||||
match = exact_match or semantic_match
|
||||
if match:
|
||||
payload = match.payload or {}
|
||||
linked_ids = payload.get("linked_memory_ids", [])
|
||||
if memory_id not in linked_ids:
|
||||
@@ -2163,7 +2308,7 @@ class AsyncMemory(MemoryBase):
|
||||
return
|
||||
seen = set()
|
||||
for entity_type, entity_text in entities:
|
||||
key = entity_text.strip().lower()
|
||||
key = self._normalize_entity_text(entity_text)
|
||||
if not key or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
@@ -2213,6 +2358,7 @@ class AsyncMemory(MemoryBase):
|
||||
run_id: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
timestamp: Optional[Any] = None,
|
||||
expiration_date: Optional[Any] = None,
|
||||
infer: bool = True,
|
||||
memory_type: Optional[str] = None,
|
||||
prompt: Optional[str] = None,
|
||||
@@ -2228,6 +2374,8 @@ class AsyncMemory(MemoryBase):
|
||||
run_id (str, optional): ID of the run creating the memory. Defaults to None.
|
||||
metadata (dict, optional): Metadata to store with the memory. Defaults to None.
|
||||
timestamp (Any, optional): Platform-only temporal parameter. Not supported in OSS.
|
||||
expiration_date (Any, optional): Date in YYYY-MM-DD format. Expired memories are hidden
|
||||
from search and get_all unless show_expired is True.
|
||||
infer (bool, optional): Whether to infer the memories. Defaults to True.
|
||||
memory_type (str, optional): Type of memory to create. Defaults to None.
|
||||
Pass "procedural_memory" to create procedural memories.
|
||||
@@ -2239,10 +2387,13 @@ class AsyncMemory(MemoryBase):
|
||||
if timestamp is not None:
|
||||
raise ValueError(await get_temporal_feature_error_message_async("async", "add", "timestamp"))
|
||||
|
||||
normalized_expiration_date = _normalize_expiration_date(expiration_date)
|
||||
temporal_usage_notice = detect_temporal_usage_from_metadata(metadata)
|
||||
processed_metadata, effective_filters = _build_filters_and_metadata(
|
||||
user_id=user_id, agent_id=agent_id, run_id=run_id, input_metadata=metadata
|
||||
)
|
||||
if normalized_expiration_date is not None:
|
||||
processed_metadata["expiration_date"] = normalized_expiration_date
|
||||
|
||||
if memory_type is not None and memory_type != MemoryType.PROCEDURAL.value:
|
||||
raise ValueError(
|
||||
@@ -2512,7 +2663,7 @@ class AsyncMemory(MemoryBase):
|
||||
for idx, (memory_id, text, embedding, payload) in enumerate(records):
|
||||
entities = all_entities[idx] if idx < len(all_entities) else []
|
||||
for entity_type, entity_text in entities:
|
||||
key = entity_text.strip().lower()
|
||||
key = self._normalize_entity_text(entity_text)
|
||||
if key in global_entities:
|
||||
global_entities[key][2].add(memory_id)
|
||||
else:
|
||||
@@ -2547,6 +2698,7 @@ class AsyncMemory(MemoryBase):
|
||||
if valid:
|
||||
valid_indices, valid_keys = zip(*valid)
|
||||
valid_vectors = [entity_embeddings[i] for i in valid_indices]
|
||||
exact_matches = await asyncio.to_thread(self._existing_entities_by_text, search_filters)
|
||||
|
||||
# 7c: Batch search for existing entities
|
||||
valid_texts = [global_entities[k][1] for k in valid_keys]
|
||||
@@ -2563,9 +2715,11 @@ class AsyncMemory(MemoryBase):
|
||||
for j, key in enumerate(valid_keys):
|
||||
entity_type, entity_text, memory_ids = global_entities[key]
|
||||
matches = existing_matches[j] if j < len(existing_matches) else []
|
||||
exact_match = exact_matches.get(key)
|
||||
|
||||
if matches and matches[0].score >= 0.95:
|
||||
match = matches[0]
|
||||
semantic_match = matches[0] if matches and matches[0].score >= 0.95 else None
|
||||
match = exact_match or semantic_match
|
||||
if match:
|
||||
payload = match.payload or {}
|
||||
linked = set(payload.get("linked_memory_ids", []))
|
||||
linked |= memory_ids
|
||||
@@ -2642,6 +2796,7 @@ class AsyncMemory(MemoryBase):
|
||||
"actor_id",
|
||||
"role",
|
||||
"attributed_to",
|
||||
"expiration_date",
|
||||
]
|
||||
|
||||
core_and_promoted_keys = {"data", "hash", "created_at", "updated_at", "id", "text_lemmatized", "attributed_to", *promoted_payload_keys}
|
||||
@@ -2670,6 +2825,7 @@ class AsyncMemory(MemoryBase):
|
||||
*,
|
||||
filters: Optional[Dict[str, Any]] = None,
|
||||
top_k: int = 20,
|
||||
show_expired: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
@@ -2680,6 +2836,7 @@ class AsyncMemory(MemoryBase):
|
||||
Must contain at least one of: user_id, agent_id, run_id.
|
||||
Example: filters={"user_id": "u1", "agent_id": "a1"}
|
||||
top_k (int, optional): The maximum number of memories to return. Defaults to 20.
|
||||
show_expired (bool, optional): Include expired memories. Defaults to False.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing a list of memories under the "results" key.
|
||||
@@ -2718,6 +2875,7 @@ class AsyncMemory(MemoryBase):
|
||||
)
|
||||
|
||||
limit = top_k
|
||||
fetch_limit = limit if show_expired else max(limit * 4, 60)
|
||||
scale_threshold_notice = detect_scale_threshold_from_top_k(top_k)
|
||||
|
||||
keys, encoded_ids = process_telemetry_filters(effective_filters)
|
||||
@@ -2725,7 +2883,7 @@ class AsyncMemory(MemoryBase):
|
||||
"mem0.get_all", self, {"limit": limit, "keys": keys, "encoded_ids": encoded_ids, "sync_type": "async"}
|
||||
)
|
||||
|
||||
all_memories_result = await self._get_all_from_vector_store(effective_filters, limit)
|
||||
all_memories_result = await self._get_all_from_vector_store(effective_filters, fetch_limit, show_expired, limit)
|
||||
|
||||
if scale_threshold_notice:
|
||||
await display_scale_threshold_notice_async(self, "async", "get_all", *scale_threshold_notice)
|
||||
@@ -2733,7 +2891,7 @@ class AsyncMemory(MemoryBase):
|
||||
await display_first_run_notice_async(self, "async", "get_all")
|
||||
return {"results": all_memories_result}
|
||||
|
||||
async def _get_all_from_vector_store(self, filters, limit):
|
||||
async def _get_all_from_vector_store(self, filters, limit, show_expired=False, output_limit=None):
|
||||
memories_result = await asyncio.to_thread(self.vector_store.list, filters=filters, top_k=limit)
|
||||
|
||||
# Handle different vector store return formats by inspecting first element
|
||||
@@ -2756,11 +2914,14 @@ class AsyncMemory(MemoryBase):
|
||||
"actor_id",
|
||||
"role",
|
||||
"attributed_to",
|
||||
"expiration_date",
|
||||
]
|
||||
core_and_promoted_keys = {"data", "hash", "created_at", "updated_at", "id", "text_lemmatized", "attributed_to", *promoted_payload_keys}
|
||||
|
||||
formatted_memories = []
|
||||
for mem in actual_memories:
|
||||
if not show_expired and _payload_is_expired(mem.payload):
|
||||
continue
|
||||
memory_item_dict = MemoryItem(
|
||||
id=mem.id,
|
||||
memory=mem.payload.get("data", ""),
|
||||
@@ -2778,6 +2939,8 @@ class AsyncMemory(MemoryBase):
|
||||
memory_item_dict["metadata"] = additional_metadata
|
||||
|
||||
formatted_memories.append(memory_item_dict)
|
||||
if output_limit is not None and len(formatted_memories) >= output_limit:
|
||||
break
|
||||
|
||||
return formatted_memories
|
||||
|
||||
@@ -2791,6 +2954,7 @@ class AsyncMemory(MemoryBase):
|
||||
rerank: bool = False,
|
||||
explain: bool = False,
|
||||
reference_date: Optional[Any] = None,
|
||||
show_expired: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
@@ -2823,6 +2987,7 @@ class AsyncMemory(MemoryBase):
|
||||
rerank (bool, optional): Whether to rerank results. Defaults to False.
|
||||
explain (bool, optional): Whether to include score_details for each result. Defaults to False.
|
||||
reference_date (Any, optional): Platform-only temporal parameter. Not supported in OSS.
|
||||
show_expired (bool, optional): Include expired memories. Defaults to False.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the search results under a "results" key.
|
||||
@@ -2898,7 +3063,9 @@ class AsyncMemory(MemoryBase):
|
||||
)
|
||||
|
||||
search_start = time.perf_counter()
|
||||
original_memories = await self._search_vector_store(query, effective_filters, limit, threshold, explain=explain)
|
||||
original_memories = await self._search_vector_store(
|
||||
query, effective_filters, limit, threshold, explain=explain, show_expired=show_expired
|
||||
)
|
||||
search_elapsed_seconds = time.perf_counter() - search_start
|
||||
|
||||
# Apply reranking if enabled and reranker is available
|
||||
@@ -3033,7 +3200,7 @@ class AsyncMemory(MemoryBase):
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _search_vector_store(self, query, filters, limit, threshold=0.1, explain=False):
|
||||
async def _search_vector_store(self, query, filters, limit, threshold=0.1, explain=False, show_expired=False):
|
||||
if threshold is None:
|
||||
threshold = 0.1
|
||||
|
||||
@@ -3073,11 +3240,14 @@ class AsyncMemory(MemoryBase):
|
||||
# Step 7: Build candidate set from semantic results
|
||||
candidates = []
|
||||
for mem in semantic_results:
|
||||
payload = mem.payload if hasattr(mem, 'payload') else {}
|
||||
if not show_expired and _payload_is_expired(payload):
|
||||
continue
|
||||
mem_id = str(mem.id)
|
||||
candidates.append({
|
||||
"id": mem_id,
|
||||
"score": mem.score,
|
||||
"payload": mem.payload if hasattr(mem, 'payload') else {},
|
||||
"payload": payload,
|
||||
})
|
||||
|
||||
# Step 8: Score and rank
|
||||
@@ -3098,6 +3268,7 @@ class AsyncMemory(MemoryBase):
|
||||
"actor_id",
|
||||
"role",
|
||||
"attributed_to",
|
||||
"expiration_date",
|
||||
]
|
||||
core_and_promoted_keys = {"data", "hash", "created_at", "updated_at", "id", "text_lemmatized", "attributed_to", *promoted_payload_keys}
|
||||
|
||||
@@ -3137,7 +3308,7 @@ class AsyncMemory(MemoryBase):
|
||||
seen = set()
|
||||
deduped = []
|
||||
for entity_type, entity_text in query_entities[:8]:
|
||||
key = entity_text.strip().lower()
|
||||
key = self._normalize_entity_text(entity_text)
|
||||
if key and key not in seen:
|
||||
seen.add(key)
|
||||
deduped.append((entity_type, entity_text))
|
||||
@@ -3206,14 +3377,21 @@ class AsyncMemory(MemoryBase):
|
||||
|
||||
return memory_boosts
|
||||
|
||||
async def update(self, memory_id, data, metadata: Optional[Dict[str, Any]] = None):
|
||||
async def update(
|
||||
self,
|
||||
memory_id,
|
||||
data: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
expiration_date: Any = _UNSET,
|
||||
):
|
||||
"""
|
||||
Update a memory by ID asynchronously.
|
||||
|
||||
Args:
|
||||
memory_id (str): ID of the memory to update.
|
||||
data (str): New content to update the memory with.
|
||||
data (str, optional): New content to update the memory with.
|
||||
metadata (dict, optional): Metadata to update with the memory. Defaults to None.
|
||||
expiration_date (Any, optional): Date in YYYY-MM-DD format, or None to clear it.
|
||||
|
||||
Returns:
|
||||
dict: Success message indicating the memory was updated.
|
||||
@@ -3224,10 +3402,20 @@ class AsyncMemory(MemoryBase):
|
||||
"""
|
||||
capture_event("mem0.update", self, {"memory_id": memory_id, "sync_type": "async"})
|
||||
|
||||
embeddings = await asyncio.to_thread(self.embedding_model.embed, data, "update")
|
||||
existing_embeddings = {data: embeddings}
|
||||
if data is None and metadata is None and expiration_date is _UNSET:
|
||||
raise ValueError("At least one of data, metadata, or expiration_date must be provided.")
|
||||
|
||||
await self._update_memory(memory_id, data, existing_embeddings, metadata)
|
||||
update_metadata = deepcopy(metadata) if metadata is not None else None
|
||||
if expiration_date is not _UNSET:
|
||||
update_metadata = update_metadata or {}
|
||||
update_metadata["expiration_date"] = _normalize_expiration_date(expiration_date)
|
||||
|
||||
existing_embeddings = {}
|
||||
if data is not None:
|
||||
embeddings = await asyncio.to_thread(self.embedding_model.embed, data, "update")
|
||||
existing_embeddings[data] = embeddings
|
||||
|
||||
await self._update_memory(memory_id, data, existing_embeddings, update_metadata)
|
||||
await display_first_run_notice_async(self, "async", "update")
|
||||
return {"message": "Memory updated successfully!"}
|
||||
|
||||
@@ -3261,6 +3449,10 @@ class AsyncMemory(MemoryBase):
|
||||
agent_id (str, optional): ID of the agent to delete memories for. Defaults to None.
|
||||
run_id (str, optional): ID of the run to delete memories for. Defaults to None.
|
||||
"""
|
||||
user_id = _validate_and_trim_entity_id(user_id, "user_id")
|
||||
agent_id = _validate_and_trim_entity_id(agent_id, "agent_id")
|
||||
run_id = _validate_and_trim_entity_id(run_id, "run_id")
|
||||
|
||||
filters = {}
|
||||
if user_id:
|
||||
filters["user_id"] = user_id
|
||||
@@ -3386,7 +3578,7 @@ class AsyncMemory(MemoryBase):
|
||||
if llm is not None:
|
||||
parsed_messages = convert_to_messages(parsed_messages)
|
||||
response = await asyncio.to_thread(llm.invoke, input=parsed_messages)
|
||||
procedural_memory = response.content
|
||||
procedural_memory = remove_code_blocks(response.content)
|
||||
else:
|
||||
procedural_memory = await asyncio.to_thread(self.llm.generate_response, messages=parsed_messages)
|
||||
procedural_memory = remove_code_blocks(procedural_memory)
|
||||
@@ -3421,6 +3613,11 @@ class AsyncMemory(MemoryBase):
|
||||
raise ValueError(f"Memory with id {memory_id} not found. Please provide a valid 'memory_id'")
|
||||
|
||||
prev_value = existing_memory.payload.get("data")
|
||||
if data is None:
|
||||
data = prev_value
|
||||
if not isinstance(data, str):
|
||||
raise ValueError(f"Memory with id {memory_id} does not have text content to update")
|
||||
text_changed = data != prev_value
|
||||
|
||||
new_metadata = deepcopy(existing_memory.payload)
|
||||
if metadata is not None:
|
||||
@@ -3464,8 +3661,9 @@ class AsyncMemory(MemoryBase):
|
||||
# Entity-store cleanup: strip this memory's id from old-text entities,
|
||||
# then re-extract entities from the new text and link them back.
|
||||
session_filters = {k: new_metadata[k] for k in ("user_id", "agent_id", "run_id") if new_metadata.get(k)}
|
||||
await self._remove_memory_from_entity_store(memory_id, session_filters)
|
||||
await self._link_entities_for_memory(memory_id, data, session_filters)
|
||||
if text_changed:
|
||||
await self._remove_memory_from_entity_store(memory_id, session_filters)
|
||||
await self._link_entities_for_memory(memory_id, data, session_filters)
|
||||
|
||||
return memory_id
|
||||
|
||||
|
||||
+26
-3
@@ -1418,7 +1418,30 @@ def _get_provider_memory_count(memory_instance) -> Optional[int]:
|
||||
try:
|
||||
col_info = getattr(vector_store, "col_info", None)
|
||||
if callable(col_info):
|
||||
return _extract_count(col_info())
|
||||
collection_name = getattr(vector_store, "collection_name", None)
|
||||
if collection_name is None:
|
||||
schema = getattr(vector_store, "schema", None)
|
||||
if isinstance(schema, dict):
|
||||
index = schema.get("index")
|
||||
if isinstance(index, dict):
|
||||
collection_name = index.get("name")
|
||||
if collection_name is not None:
|
||||
try:
|
||||
info = col_info(collection_name)
|
||||
except TypeError:
|
||||
info = col_info()
|
||||
else:
|
||||
info = col_info()
|
||||
value = _extract_count(info)
|
||||
if value is not None:
|
||||
return value
|
||||
|
||||
client = getattr(vector_store, "client", None)
|
||||
client_count = (
|
||||
getattr(client, "count", None) if client is not None and collection_name is not None else None
|
||||
)
|
||||
if callable(client_count):
|
||||
return _extract_count(client_count(index=collection_name))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@@ -1430,7 +1453,7 @@ def _extract_count(info: Any) -> Optional[int]:
|
||||
return None
|
||||
|
||||
if isinstance(info, dict):
|
||||
for key in ("count", "points_count", "vectors_count", "indexed_vectors_count"):
|
||||
for key in ("count", "points_count", "vectors_count", "indexed_vectors_count", "num_docs"):
|
||||
value = _coerce_nonnegative_int(info.get(key), None)
|
||||
if value is not None:
|
||||
return value
|
||||
@@ -1445,7 +1468,7 @@ def _extract_count(info: Any) -> Optional[int]:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
for attr in ("count", "points_count", "vectors_count", "indexed_vectors_count"):
|
||||
for attr in ("count", "points_count", "vectors_count", "indexed_vectors_count", "num_docs"):
|
||||
value = _coerce_nonnegative_int(getattr(info, attr, None), None)
|
||||
if value is not None:
|
||||
return value
|
||||
|
||||
@@ -206,7 +206,10 @@ def parse_vision_messages(messages, llm=None, vision_details="auto"):
|
||||
elif isinstance(content, dict) and content.get("type") == "image_url":
|
||||
if llm is None:
|
||||
continue
|
||||
image_url = content["image_url"]["url"]
|
||||
image_url_obj = content.get("image_url")
|
||||
image_url = image_url_obj.get("url") if isinstance(image_url_obj, dict) else None
|
||||
if not image_url:
|
||||
raise ValueError("image_url content part is missing image_url.url")
|
||||
try:
|
||||
description = get_image_description(image_url, llm, vision_details)
|
||||
returned_messages.append({"role": role, "content": description})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Dict, Any
|
||||
|
||||
@@ -9,6 +10,8 @@ try:
|
||||
except ImportError:
|
||||
COHERE_AVAILABLE = False
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CohereReranker(BaseReranker):
|
||||
"""Cohere-based reranker implementation."""
|
||||
@@ -78,8 +81,9 @@ class CohereReranker(BaseReranker):
|
||||
|
||||
return reranked_docs
|
||||
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# Fallback to original order if reranking fails
|
||||
logger.warning("Cohere reranking failed, falling back to original order: %s", e)
|
||||
for doc in documents:
|
||||
doc['rerank_score'] = 0.0
|
||||
final_top_k = top_k or self.config.top_k
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
from typing import List, Dict, Any, Union
|
||||
import numpy as np
|
||||
|
||||
@@ -12,6 +13,8 @@ try:
|
||||
except ImportError:
|
||||
TRANSFORMERS_AVAILABLE = False
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HuggingFaceReranker(BaseReranker):
|
||||
"""HuggingFace Transformers based reranker implementation."""
|
||||
@@ -56,6 +59,26 @@ class HuggingFaceReranker(BaseReranker):
|
||||
self.model.to(self.device)
|
||||
self.model.eval()
|
||||
|
||||
@staticmethod
|
||||
def _normalize_scores(scores: List[float]) -> List[float]:
|
||||
"""Map raw cross-encoder logits into the [0, 1] range via a sigmoid.
|
||||
|
||||
Cross-encoder rerankers (e.g. ``BAAI/bge-reranker-*``) emit unbounded
|
||||
logits; the documented way to obtain an interpretable [0, 1] relevance
|
||||
score is a per-document sigmoid (``1 / (1 + e^-x)``), which preserves the
|
||||
ranking order.
|
||||
|
||||
This replaces the previous min-max scaling, which produced *set-relative*
|
||||
scores: the lowest-ranked document was always forced to 0.0, and a single
|
||||
document (or any set of tied scores) collapsed to 0.0 — wrongly reporting
|
||||
a result as completely irrelevant. Sigmoid scores each document on its own
|
||||
merit, so those cases are handled naturally.
|
||||
"""
|
||||
if not scores:
|
||||
return []
|
||||
arr = np.asarray(scores, dtype=float)
|
||||
return (1.0 / (1.0 + np.exp(-arr))).tolist()
|
||||
|
||||
def rerank(self, query: str, documents: List[Dict[str, Any]], top_k: int = None) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Rerank documents using HuggingFace cross-encoder model.
|
||||
@@ -115,9 +138,7 @@ class HuggingFaceReranker(BaseReranker):
|
||||
|
||||
# Normalize scores if requested
|
||||
if self.config.normalize:
|
||||
scores = np.array(scores)
|
||||
scores = (scores - scores.min()) / (scores.max() - scores.min() + 1e-8)
|
||||
scores = scores.tolist()
|
||||
scores = self._normalize_scores(scores)
|
||||
|
||||
# Combine documents with scores
|
||||
doc_score_pairs = list(zip(documents, scores))
|
||||
@@ -139,8 +160,9 @@ class HuggingFaceReranker(BaseReranker):
|
||||
|
||||
return reranked_docs
|
||||
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# Fallback to original order if reranking fails
|
||||
logger.warning("HuggingFace reranking failed, falling back to original order: %s", e)
|
||||
for doc in documents:
|
||||
doc['rerank_score'] = 0.0
|
||||
final_top_k = top_k or self.config.top_k
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict, List, Union
|
||||
|
||||
@@ -6,6 +7,8 @@ from mem0.configs.rerankers.llm import LLMRerankerConfig
|
||||
from mem0.reranker.base import BaseReranker
|
||||
from mem0.utils.factory import LlmFactory
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LLMReranker(BaseReranker):
|
||||
"""LLM-based reranker implementation."""
|
||||
@@ -151,8 +154,9 @@ class LLMReranker(BaseReranker):
|
||||
scored_doc['rerank_score'] = score
|
||||
scored_docs.append(scored_doc)
|
||||
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# Fallback: assign neutral score if scoring fails
|
||||
logger.warning("LLM reranking failed for a document, assigning neutral score: %s", e)
|
||||
scored_doc = doc.copy()
|
||||
scored_doc['rerank_score'] = 0.5
|
||||
scored_docs.append(scored_doc)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
from typing import List, Dict, Any, Union
|
||||
import numpy as np
|
||||
|
||||
@@ -11,6 +12,8 @@ try:
|
||||
except ImportError:
|
||||
SENTENCE_TRANSFORMERS_AVAILABLE = False
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SentenceTransformerReranker(BaseReranker):
|
||||
"""Sentence Transformer based reranker implementation."""
|
||||
@@ -102,8 +105,9 @@ class SentenceTransformerReranker(BaseReranker):
|
||||
|
||||
return reranked_docs
|
||||
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# Fallback to original order if reranking fails
|
||||
logger.warning("SentenceTransformer reranking failed, falling back to original order: %s", e)
|
||||
for doc in documents:
|
||||
doc['rerank_score'] = 0.0
|
||||
final_top_k = top_k or self.config.top_k
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Dict, Any
|
||||
|
||||
@@ -9,6 +10,8 @@ try:
|
||||
except ImportError:
|
||||
ZERO_ENTROPY_AVAILABLE = False
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ZeroEntropyReranker(BaseReranker):
|
||||
"""Zero Entropy-based reranker implementation."""
|
||||
@@ -89,8 +92,9 @@ class ZeroEntropyReranker(BaseReranker):
|
||||
|
||||
return reranked_docs
|
||||
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# Fallback to original order if reranking fails
|
||||
logger.warning("Zero Entropy reranking failed, falling back to original order: %s", e)
|
||||
for doc in documents:
|
||||
doc['rerank_score'] = 0.0
|
||||
final_top_k = top_k or self.config.top_k
|
||||
|
||||
+606
-197
@@ -1,82 +1,352 @@
|
||||
"""
|
||||
Entity extraction from text using spaCy NLP.
|
||||
|
||||
Extracts four types of entities from text:
|
||||
Extracts three types of entities from a spaCy-processed document:
|
||||
- **Proper nouns**: Capitalized multi-word sequences (person names, places, brands)
|
||||
- **Quoted text**: Text in single or double quotes (titles, specific terms)
|
||||
- **Noun compounds**: Multi-word noun phrases with specific modifiers (e.g., "machine learning")
|
||||
- **Noun fallback**: Single nouns from circumstantial compound patterns
|
||||
|
||||
Public API:
|
||||
extract_entities(text: str) -> List[Tuple[str, str]]
|
||||
``extract_entities(text)`` accepts a string and owns spaCy model loading.
|
||||
``extract_entities_batch(texts)`` uses ``nlp.pipe`` for batched extraction.
|
||||
|
||||
Internal:
|
||||
_extract_entities_from_doc(doc) -> List[Tuple[str, str]]
|
||||
Returns:
|
||||
List of ``(entity_type, entity_text)`` tuples where entity_type is one of
|
||||
PROPER, QUOTED, TOPIC, or IDENTIFIER. Returns ``[]`` if spaCy is unavailable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
from typing import List, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _EntityCandidate:
|
||||
entity_type: str
|
||||
text: str
|
||||
source: str
|
||||
start: int
|
||||
end: int
|
||||
confidence: float
|
||||
priority: int
|
||||
|
||||
|
||||
# Words that are too generic to be useful as entity heads
|
||||
_GENERIC_HEADS = {
|
||||
"thing", "stuff", "way", "time", "experience", "situation", "case",
|
||||
"fact", "matter", "issue", "idea", "thought", "feeling", "place",
|
||||
"area", "part", "kind", "type", "sort", "lot", "bit", "day", "year",
|
||||
"week", "month", "moment", "instance", "example", "technique",
|
||||
"method", "approach", "process", "step", "tool", "result", "outcome",
|
||||
"goal", "task", "item", "topic", "scale", "size", "level", "degree",
|
||||
"amount", "number", "style", "look", "color", "colour", "shape",
|
||||
"form", "piece", "section", "side", "end", "edge", "surface", "point",
|
||||
"thing",
|
||||
"stuff",
|
||||
"way",
|
||||
"time",
|
||||
"experience",
|
||||
"situation",
|
||||
"case",
|
||||
"fact",
|
||||
"matter",
|
||||
"issue",
|
||||
"idea",
|
||||
"thought",
|
||||
"feeling",
|
||||
"place",
|
||||
"area",
|
||||
"part",
|
||||
"kind",
|
||||
"type",
|
||||
"sort",
|
||||
"lot",
|
||||
"bit",
|
||||
"day",
|
||||
"year",
|
||||
"week",
|
||||
"month",
|
||||
"moment",
|
||||
"instance",
|
||||
"example",
|
||||
"technique",
|
||||
"method",
|
||||
"approach",
|
||||
"process",
|
||||
"step",
|
||||
"tool",
|
||||
"result",
|
||||
"outcome",
|
||||
"goal",
|
||||
"task",
|
||||
"item",
|
||||
"topic",
|
||||
"scale",
|
||||
"size",
|
||||
"level",
|
||||
"degree",
|
||||
"amount",
|
||||
"number",
|
||||
"style",
|
||||
"look",
|
||||
"color",
|
||||
"colour",
|
||||
"shape",
|
||||
"form",
|
||||
"piece",
|
||||
"section",
|
||||
"side",
|
||||
"end",
|
||||
"edge",
|
||||
"surface",
|
||||
"point",
|
||||
}
|
||||
|
||||
# Entity labels emitted by spaCy that are usually safe to treat as named
|
||||
# entities. Numeric and temporal labels are intentionally excluded.
|
||||
_ACCEPTED_NER_LABELS = {
|
||||
"PERSON",
|
||||
"ORG",
|
||||
"GPE",
|
||||
"LOC",
|
||||
"FAC",
|
||||
"PRODUCT",
|
||||
"WORK_OF_ART",
|
||||
"EVENT",
|
||||
"NORP",
|
||||
"LAW",
|
||||
"LANGUAGE",
|
||||
}
|
||||
|
||||
_REJECTED_NER_LABELS = {
|
||||
"DATE",
|
||||
"TIME",
|
||||
"CARDINAL",
|
||||
"ORDINAL",
|
||||
"QUANTITY",
|
||||
"MONEY",
|
||||
"PERCENT",
|
||||
}
|
||||
|
||||
# Generic role words and title-cased English words that should not become
|
||||
# single-token named entities just because spaCy tagged them as PROPN.
|
||||
_GENERIC_SINGLE_ENTITY_TERMS = {
|
||||
"user",
|
||||
"assistant",
|
||||
"agent",
|
||||
"customer",
|
||||
"client",
|
||||
"person",
|
||||
"people",
|
||||
"human",
|
||||
"memory",
|
||||
"message",
|
||||
"conversation",
|
||||
"chat",
|
||||
"session",
|
||||
"system",
|
||||
"top",
|
||||
}
|
||||
|
||||
# Modifiers that describe circumstance, not content
|
||||
_CIRCUMSTANTIAL_MODS = {
|
||||
"solo", "individual", "team", "group", "joint", "collaborative",
|
||||
"first", "last", "next", "previous", "final", "initial", "main", "side",
|
||||
"solo",
|
||||
"individual",
|
||||
"team",
|
||||
"group",
|
||||
"joint",
|
||||
"collaborative",
|
||||
"first",
|
||||
"last",
|
||||
"next",
|
||||
"previous",
|
||||
"final",
|
||||
"initial",
|
||||
"main",
|
||||
"side",
|
||||
"top",
|
||||
}
|
||||
|
||||
# Adjectives too vague to make a compound entity specific
|
||||
_NON_SPECIFIC_ADJ = {
|
||||
"many", "few", "several", "some", "any", "all", "most", "more",
|
||||
"less", "much", "little", "enough", "various", "numerous", "multiple",
|
||||
"countless", "great", "good", "bad", "nice", "terrible", "awful",
|
||||
"awesome", "amazing", "wonderful", "horrible", "excellent", "poor",
|
||||
"best", "worst", "fine", "okay", "new", "old", "recent", "past",
|
||||
"future", "current", "previous", "next", "last", "first", "latest",
|
||||
"early", "late", "former", "modern", "ancient", "big", "small",
|
||||
"large", "tiny", "huge", "enormous", "long", "short", "tall", "high",
|
||||
"low", "wide", "narrow", "thick", "thin", "deep", "shallow",
|
||||
"similar", "different", "same", "other", "another", "such", "certain",
|
||||
"important", "main", "major", "minor", "key", "primary", "real",
|
||||
"actual", "true", "whole", "entire", "full", "complete", "total",
|
||||
"basic", "simple", "interesting", "boring", "exciting", "special",
|
||||
"particular", "general", "common", "unique", "rare", "typical",
|
||||
"usual", "normal", "regular", "possible", "likely", "potential",
|
||||
"available", "necessary", "only", "solo", "individual", "team",
|
||||
"group", "joint", "collaborative", "final", "initial", "side",
|
||||
"many",
|
||||
"few",
|
||||
"several",
|
||||
"some",
|
||||
"any",
|
||||
"all",
|
||||
"most",
|
||||
"more",
|
||||
"less",
|
||||
"much",
|
||||
"little",
|
||||
"enough",
|
||||
"various",
|
||||
"numerous",
|
||||
"multiple",
|
||||
"countless",
|
||||
"great",
|
||||
"good",
|
||||
"bad",
|
||||
"nice",
|
||||
"terrible",
|
||||
"awful",
|
||||
"awesome",
|
||||
"amazing",
|
||||
"wonderful",
|
||||
"horrible",
|
||||
"excellent",
|
||||
"poor",
|
||||
"best",
|
||||
"worst",
|
||||
"fine",
|
||||
"okay",
|
||||
"new",
|
||||
"old",
|
||||
"recent",
|
||||
"past",
|
||||
"future",
|
||||
"current",
|
||||
"previous",
|
||||
"next",
|
||||
"last",
|
||||
"first",
|
||||
"latest",
|
||||
"early",
|
||||
"late",
|
||||
"former",
|
||||
"modern",
|
||||
"ancient",
|
||||
"big",
|
||||
"small",
|
||||
"large",
|
||||
"tiny",
|
||||
"huge",
|
||||
"enormous",
|
||||
"long",
|
||||
"short",
|
||||
"tall",
|
||||
"high",
|
||||
"low",
|
||||
"wide",
|
||||
"narrow",
|
||||
"thick",
|
||||
"thin",
|
||||
"deep",
|
||||
"shallow",
|
||||
"similar",
|
||||
"different",
|
||||
"same",
|
||||
"other",
|
||||
"another",
|
||||
"such",
|
||||
"certain",
|
||||
"important",
|
||||
"main",
|
||||
"major",
|
||||
"minor",
|
||||
"key",
|
||||
"primary",
|
||||
"real",
|
||||
"actual",
|
||||
"true",
|
||||
"whole",
|
||||
"entire",
|
||||
"full",
|
||||
"complete",
|
||||
"total",
|
||||
"basic",
|
||||
"simple",
|
||||
"interesting",
|
||||
"boring",
|
||||
"exciting",
|
||||
"special",
|
||||
"particular",
|
||||
"general",
|
||||
"common",
|
||||
"unique",
|
||||
"rare",
|
||||
"typical",
|
||||
"usual",
|
||||
"normal",
|
||||
"regular",
|
||||
"possible",
|
||||
"likely",
|
||||
"potential",
|
||||
"available",
|
||||
"necessary",
|
||||
"only",
|
||||
"solo",
|
||||
"individual",
|
||||
"team",
|
||||
"group",
|
||||
"joint",
|
||||
"collaborative",
|
||||
"final",
|
||||
"initial",
|
||||
"side",
|
||||
}
|
||||
|
||||
# Generic tail words to strip from compound entities
|
||||
_GENERIC_ENDINGS = {
|
||||
"work", "works", "job", "jobs", "task", "tasks", "stuff", "things",
|
||||
"thing", "info", "information", "details", "data", "content",
|
||||
"material", "materials", "activities", "activity", "efforts", "effort",
|
||||
"options", "option", "choices", "choice", "results", "result",
|
||||
"output", "outputs", "products", "product", "items", "item",
|
||||
"work",
|
||||
"works",
|
||||
"job",
|
||||
"jobs",
|
||||
"task",
|
||||
"tasks",
|
||||
"stuff",
|
||||
"things",
|
||||
"thing",
|
||||
"info",
|
||||
"information",
|
||||
"details",
|
||||
"data",
|
||||
"content",
|
||||
"material",
|
||||
"materials",
|
||||
"activities",
|
||||
"activity",
|
||||
"efforts",
|
||||
"effort",
|
||||
"options",
|
||||
"option",
|
||||
"choices",
|
||||
"choice",
|
||||
"results",
|
||||
"result",
|
||||
"output",
|
||||
"outputs",
|
||||
"products",
|
||||
"product",
|
||||
"items",
|
||||
"item",
|
||||
}
|
||||
|
||||
# Capitalized single words that are too generic to be proper nouns
|
||||
_GENERIC_CAPS = {
|
||||
"works", "items", "things", "stuff", "resources", "options", "tips",
|
||||
"ideas", "steps", "ways", "methods", "tools", "features", "benefits",
|
||||
"examples", "details", "notes", "instructions", "guidelines",
|
||||
"recommendations", "suggestions", "overview", "summary", "conclusion",
|
||||
"introduction", "pros", "cons", "advantages", "disadvantages",
|
||||
"works",
|
||||
"items",
|
||||
"things",
|
||||
"stuff",
|
||||
"resources",
|
||||
"options",
|
||||
"tips",
|
||||
"ideas",
|
||||
"steps",
|
||||
"ways",
|
||||
"methods",
|
||||
"tools",
|
||||
"features",
|
||||
"benefits",
|
||||
"examples",
|
||||
"details",
|
||||
"notes",
|
||||
"instructions",
|
||||
"guidelines",
|
||||
"recommendations",
|
||||
"suggestions",
|
||||
"overview",
|
||||
"summary",
|
||||
"conclusion",
|
||||
"introduction",
|
||||
"pros",
|
||||
"cons",
|
||||
"advantages",
|
||||
"disadvantages",
|
||||
}
|
||||
|
||||
# Markdown/formatting markers to skip during extraction
|
||||
@@ -120,121 +390,208 @@ def _has_artifacts(txt: str) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def extract_entities(text: str) -> List[Tuple[str, str]]:
|
||||
"""Extract named entities, quoted text, and noun compounds from text.
|
||||
|
||||
This is the public API that accepts a string. It loads the spaCy model
|
||||
internally and delegates to _extract_entities_from_doc().
|
||||
|
||||
Args:
|
||||
text: Input text to extract entities from.
|
||||
|
||||
Returns:
|
||||
Deduplicated list of (entity_type, entity_text) tuples.
|
||||
Entity types: PROPER, QUOTED, COMPOUND, NOUN.
|
||||
Returns empty list if spaCy is unavailable.
|
||||
"""
|
||||
from mem0.utils.spacy_models import get_nlp_full
|
||||
|
||||
nlp = get_nlp_full()
|
||||
if nlp is None:
|
||||
return []
|
||||
|
||||
doc = nlp(text)
|
||||
return _extract_entities_from_doc(doc)
|
||||
def _clean_text(txt: str) -> str:
|
||||
txt = re.sub(r"^\*+\s*|\s*\*+$", "", txt.strip())
|
||||
txt = re.sub(r"\s*:+$", "", txt)
|
||||
txt = re.sub(r"^\d+\s*\.\s*", "", txt)
|
||||
return " ".join(txt.split())
|
||||
|
||||
|
||||
def extract_entities_batch(texts: List[str], batch_size: int = 32) -> List[List[Tuple[str, str]]]:
|
||||
"""Extract entities from multiple texts using spaCy's nlp.pipe() for batched NER.
|
||||
|
||||
Uses spaCy's efficient batch processing pipeline instead of calling
|
||||
nlp() individually per text. Significantly faster for multiple texts.
|
||||
|
||||
Args:
|
||||
texts: List of input texts to extract entities from.
|
||||
batch_size: Number of texts to process in each spaCy batch.
|
||||
|
||||
Returns:
|
||||
List of entity lists, one per input text. Each entity list contains
|
||||
(entity_type, entity_text) tuples. Returns list of empty lists if
|
||||
spaCy is unavailable.
|
||||
"""
|
||||
if not texts:
|
||||
return []
|
||||
|
||||
from mem0.utils.spacy_models import get_nlp_full
|
||||
|
||||
nlp = get_nlp_full()
|
||||
if nlp is None:
|
||||
return [[] for _ in texts]
|
||||
|
||||
results = []
|
||||
for doc in nlp.pipe(texts, batch_size=batch_size):
|
||||
results.append(_extract_entities_from_doc(doc))
|
||||
return results
|
||||
def _norm_text(txt: str) -> str:
|
||||
return " ".join(txt.lower().split())
|
||||
|
||||
|
||||
def _extract_entities_from_doc(doc) -> List[Tuple[str, str]]:
|
||||
"""Extract entities from a spaCy Doc object.
|
||||
def _looks_like_technical_identifier(text: str) -> bool:
|
||||
return bool(re.fullmatch(r"[A-Za-z_][\w-]*(?:\.[A-Za-z_][\w-]*)+", text))
|
||||
|
||||
Ported from platform's shared.core.utils.entity_extraction.extract_entities().
|
||||
"""
|
||||
entities: List[Tuple[str, str]] = []
|
||||
text = doc.text
|
||||
|
||||
def _has_internal_cap_or_digit(text: str) -> bool:
|
||||
return any(ch.isdigit() for ch in text) or any(ch.isupper() for ch in text[1:])
|
||||
|
||||
|
||||
def _looks_like_metric_count_token(tok) -> bool:
|
||||
return tok.pos_ == "NUM" and bool(re.fullmatch(r"\d[\d,]*(?:\.\d+)?", tok.text))
|
||||
|
||||
|
||||
def _is_metric_list_context(tokens: list, idx: int) -> bool:
|
||||
prev_text = tokens[idx - 1].text if idx > 0 else ""
|
||||
next_text = tokens[idx + 1].text if idx + 1 < len(tokens) else ""
|
||||
return prev_text in {":", ",", ";"} or next_text in {",", ";"}
|
||||
|
||||
|
||||
def _strip_trailing_metric_counts(span_tokens: list, all_tokens: list) -> list:
|
||||
while len(span_tokens) > 1 and _looks_like_metric_count_token(span_tokens[-1]):
|
||||
tok = span_tokens[-1]
|
||||
if "," not in tok.text and not _is_metric_list_context(all_tokens, tok.i):
|
||||
break
|
||||
span_tokens = span_tokens[:-1]
|
||||
return span_tokens
|
||||
|
||||
|
||||
def _is_list_item_name_token(tokens: list, idx: int) -> bool:
|
||||
tok = tokens[idx]
|
||||
if not tok.text or tok.text in _FORMATTING_MARKERS or not tok.text[0].isupper():
|
||||
return False
|
||||
if not any(ch.isalpha() for ch in tok.text) or _is_bad_single_name_token(tok):
|
||||
return False
|
||||
next_tok = tokens[idx + 1] if idx + 1 < len(tokens) else None
|
||||
if not next_tok or not _looks_like_metric_count_token(next_tok):
|
||||
return False
|
||||
return _is_metric_list_context(tokens, idx) or _is_metric_list_context(tokens, idx + 1)
|
||||
|
||||
|
||||
def _is_name_like_token(tok, tokens: list | None = None, idx: int | None = None) -> bool:
|
||||
if not tok.text or tok.text in _FORMATTING_MARKERS:
|
||||
return False
|
||||
if not tok.text[0].isupper():
|
||||
return False
|
||||
if not any(ch.isalpha() for ch in tok.text):
|
||||
return False
|
||||
if _is_bad_single_name_token(tok):
|
||||
return False
|
||||
if tok.pos_ == "PROPN" or tok.tag_ in {"NNP", "NNPS"}:
|
||||
return True
|
||||
if tokens is not None and idx is not None and _is_list_item_name_token(tokens, idx):
|
||||
return True
|
||||
if _has_internal_cap_or_digit(tok.text):
|
||||
return True
|
||||
return (
|
||||
tokens is not None
|
||||
and idx is not None
|
||||
and tok.pos_ == "NOUN"
|
||||
and tok.dep_ not in {"compound", "amod"}
|
||||
and not _is_sentence_start(tokens, idx)
|
||||
)
|
||||
|
||||
|
||||
def _is_bad_single_name_token(tok) -> bool:
|
||||
lower = tok.text.lower()
|
||||
return lower in _GENERIC_SINGLE_ENTITY_TERMS or lower in _GENERIC_CAPS or tok.is_stop
|
||||
|
||||
|
||||
def _add_candidate(
|
||||
candidates: list[_EntityCandidate],
|
||||
entity_type: str,
|
||||
text: str,
|
||||
source: str,
|
||||
start: int,
|
||||
end: int,
|
||||
confidence: float,
|
||||
priority: int,
|
||||
) -> None:
|
||||
cleaned = _clean_text(text)
|
||||
if not cleaned or len(cleaned) <= 2 or _has_artifacts(cleaned):
|
||||
return
|
||||
candidates.append(
|
||||
_EntityCandidate(
|
||||
entity_type=entity_type,
|
||||
text=cleaned,
|
||||
source=source,
|
||||
start=start,
|
||||
end=end,
|
||||
confidence=confidence,
|
||||
priority=priority,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _add_ner_candidates(doc, candidates: list[_EntityCandidate]) -> None:
|
||||
tokens = list(doc)
|
||||
for ent in doc.ents:
|
||||
if ent.label_ in _REJECTED_NER_LABELS or ent.label_ not in _ACCEPTED_NER_LABELS:
|
||||
continue
|
||||
ent_tokens = _strip_trailing_metric_counts(list(ent), tokens)
|
||||
if not ent_tokens:
|
||||
continue
|
||||
if any(tok.pos_ == "CCONJ" and tok.text.lower() == "and" for tok in ent_tokens):
|
||||
continue
|
||||
if len(ent_tokens) == 1 and _is_bad_single_name_token(ent_tokens[0]):
|
||||
continue
|
||||
if (
|
||||
len(ent_tokens) == 1
|
||||
and ent_tokens[0].dep_ in {"compound", "amod"}
|
||||
and ent_tokens[0].head.pos_ in {"NOUN", "PROPN"}
|
||||
):
|
||||
continue
|
||||
_add_candidate(
|
||||
candidates,
|
||||
"PROPER",
|
||||
"".join(tok.text_with_ws for tok in ent_tokens).strip(),
|
||||
"spacy_ner",
|
||||
ent_tokens[0].i,
|
||||
ent_tokens[-1].i + 1,
|
||||
0.95,
|
||||
0,
|
||||
)
|
||||
|
||||
# === PROPER NOUN SEQUENCES ===
|
||||
|
||||
def _add_technical_identifier_candidates(tokens: list, candidates: list[_EntityCandidate]) -> None:
|
||||
for tok in tokens:
|
||||
if _looks_like_technical_identifier(tok.text):
|
||||
_add_candidate(
|
||||
candidates,
|
||||
"IDENTIFIER",
|
||||
tok.text,
|
||||
"technical_identifier",
|
||||
tok.i,
|
||||
tok.i + 1,
|
||||
0.9,
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
def _add_proper_name_candidates(tokens: list, candidates: list[_EntityCandidate]) -> None:
|
||||
allowed_inner_connectors = {"of", "the", "for", "at", "in"}
|
||||
i = 0
|
||||
while i < len(tokens):
|
||||
tok = tokens[i]
|
||||
if tok.text in _FORMATTING_MARKERS:
|
||||
if not _is_name_like_token(tok, tokens, i):
|
||||
i += 1
|
||||
continue
|
||||
is_cap = tok.text and tok.text[0].isupper()
|
||||
is_label = i + 1 < len(tokens) and tokens[i + 1].text == ":"
|
||||
|
||||
if is_cap and not is_label and tok.pos_ in {"PROPN", "NOUN", "ADJ"}:
|
||||
seq = [(tok, i)]
|
||||
j = i + 1
|
||||
while j < len(tokens):
|
||||
t = tokens[j]
|
||||
if (t.text and t.text[0].isupper()) or t.text.lower() in {
|
||||
"'s", "of", "the", "in", "and", "for", "at", "is",
|
||||
}:
|
||||
seq.append((t, j))
|
||||
j += 1
|
||||
else:
|
||||
break
|
||||
# Strip trailing function words
|
||||
while seq and seq[-1][0].text.lower() in {"of", "the", "in", "and", "for", "at", "is", "'s"}:
|
||||
seq.pop()
|
||||
if seq:
|
||||
has_mid_cap = any(
|
||||
not _is_sentence_start(tokens, idx)
|
||||
for (t, idx) in seq
|
||||
if t.text[0].isupper() and t.text.lower() not in {"'s", "of", "the", "in", "and", "for", "at", "is"}
|
||||
)
|
||||
if has_mid_cap:
|
||||
phrase = "".join(t.text_with_ws for (t, idx) in seq).strip()
|
||||
if len(phrase) > 2:
|
||||
entities.append(("PROPER", phrase))
|
||||
i = j
|
||||
else:
|
||||
i += 1
|
||||
span_tokens = [tok]
|
||||
j = i + 1
|
||||
while j < len(tokens):
|
||||
current = tokens[j]
|
||||
if _is_name_like_token(current, tokens, j):
|
||||
span_tokens.append(current)
|
||||
j += 1
|
||||
continue
|
||||
if (
|
||||
current.text.lower() in allowed_inner_connectors
|
||||
and j + 1 < len(tokens)
|
||||
and _is_name_like_token(tokens[j + 1], tokens, j + 1)
|
||||
):
|
||||
span_tokens.extend([current, tokens[j + 1]])
|
||||
j += 2
|
||||
continue
|
||||
break
|
||||
|
||||
# === QUOTED TEXT ===
|
||||
name_tokens = [
|
||||
t
|
||||
for t in span_tokens
|
||||
if _is_name_like_token(t, tokens, t.i) or (0 <= t.i < len(tokens) and _is_list_item_name_token(tokens, t.i))
|
||||
]
|
||||
if len(name_tokens) > 1 or not _is_bad_single_name_token(name_tokens[0]):
|
||||
text = "".join(t.text_with_ws for t in span_tokens).strip()
|
||||
_add_candidate(candidates, "PROPER", text, "proper_name_span", i, j, 0.8, 2)
|
||||
i = max(j, i + 1)
|
||||
|
||||
|
||||
def _add_quoted_candidates(text: str, candidates: list[_EntityCandidate]) -> None:
|
||||
for m in re.finditer(r'"([^"]+)"', text):
|
||||
if len(m.group(1).strip()) > 2:
|
||||
entities.append(("QUOTED", m.group(1).strip()))
|
||||
_add_candidate(candidates, "QUOTED", m.group(1).strip(), "quoted", -1, -1, 0.75, 3)
|
||||
for m in re.finditer(r"(?:^|[\s\(\[{,;])'([^']+)'(?=[\s\.,;:!?\)\]]|$)", text):
|
||||
if len(m.group(1).strip()) > 2:
|
||||
entities.append(("QUOTED", m.group(1).strip()))
|
||||
_add_candidate(candidates, "QUOTED", m.group(1).strip(), "quoted", -1, -1, 0.75, 3)
|
||||
|
||||
# === NOUN-NOUN COMPOUNDS ===
|
||||
|
||||
def _add_topic_phrase_candidates(doc, candidates: list[_EntityCandidate]) -> None:
|
||||
for chunk in doc.noun_chunks:
|
||||
chunk_tokens = list(chunk)
|
||||
split_indices: list = []
|
||||
poss_splits: list = []
|
||||
split_indices: list[int] = []
|
||||
poss_splits: list[int] = []
|
||||
for idx, tok in enumerate(chunk_tokens):
|
||||
if tok.dep_ == "case" and tok.text in {"'s", "\u2019s", "'"}:
|
||||
split_indices.append(idx)
|
||||
@@ -243,14 +600,14 @@ def _extract_entities_from_doc(doc) -> List[Tuple[str, str]]:
|
||||
split_indices.append(idx)
|
||||
|
||||
if split_indices:
|
||||
groups: list = []
|
||||
groups: list[list] = []
|
||||
prev = 0
|
||||
for split_idx in split_indices:
|
||||
if split_idx > prev:
|
||||
groups.append(chunk_tokens[prev:split_idx])
|
||||
if split_idx in poss_splits:
|
||||
next_split = next((s for s in split_indices if s > split_idx), None)
|
||||
owned = chunk_tokens[split_idx + 1: next_split if next_split else len(chunk_tokens)]
|
||||
owned = chunk_tokens[split_idx + 1 : next_split if next_split else len(chunk_tokens)]
|
||||
if owned:
|
||||
first_content = next((t for t in owned if t.pos_ not in {"PUNCT", "PART"}), None)
|
||||
if not (first_content and first_content.text and first_content.text[0].isupper()):
|
||||
@@ -272,7 +629,8 @@ def _extract_entities_from_doc(doc) -> List[Tuple[str, str]]:
|
||||
content = [
|
||||
t
|
||||
for t in group
|
||||
if t.pos_ not in {"DET", "PRON", "PUNCT", "PART", "ADP", "SCONJ", "NUM"} and (t.pos_ == "ADJ" or not t.is_stop)
|
||||
if t.pos_ not in {"DET", "PRON", "PUNCT", "PART", "ADP", "SCONJ", "NUM"}
|
||||
and (t.pos_ == "ADJ" or not t.is_stop)
|
||||
]
|
||||
if not content:
|
||||
continue
|
||||
@@ -286,78 +644,129 @@ def _extract_entities_from_doc(doc) -> List[Tuple[str, str]]:
|
||||
if compound_toks:
|
||||
is_circ = any(t.lemma_.lower() in _CIRCUMSTANTIAL_MODS for t in compound_toks)
|
||||
if is_circ:
|
||||
val = head.lemma_ if head.pos_ == "NOUN" else head.text
|
||||
val = head.text
|
||||
if len(val) > 2:
|
||||
entities.append(("NOUN", val))
|
||||
_add_candidate(
|
||||
candidates,
|
||||
"TOPIC",
|
||||
val,
|
||||
"topic_phrase",
|
||||
head.i,
|
||||
head.i + 1,
|
||||
0.45,
|
||||
4,
|
||||
)
|
||||
else:
|
||||
filtered = _strip_generic_ending(
|
||||
[t for t in content if not (t.pos_ == "ADJ" and t.lemma_.lower() in _NON_SPECIFIC_ADJ)]
|
||||
)
|
||||
if filtered:
|
||||
phrase = _lemmatize_compound(filtered)
|
||||
phrase = " ".join(t.text for t in filtered)
|
||||
if len(phrase) > 3 and " " in phrase:
|
||||
entities.append(("COMPOUND", phrase))
|
||||
_add_candidate(
|
||||
candidates,
|
||||
"TOPIC",
|
||||
phrase,
|
||||
"topic_phrase",
|
||||
filtered[0].i,
|
||||
filtered[-1].i + 1,
|
||||
0.45,
|
||||
4,
|
||||
)
|
||||
elif len(content) > 1 and has_spec_adj:
|
||||
filtered = _strip_generic_ending(
|
||||
[t for t in content if not ((t.pos_ == "ADJ" or t.dep_ == "amod") and t.lemma_.lower() in _NON_SPECIFIC_ADJ)]
|
||||
[
|
||||
t
|
||||
for t in content
|
||||
if not ((t.pos_ == "ADJ" or t.dep_ == "amod") and t.lemma_.lower() in _NON_SPECIFIC_ADJ)
|
||||
]
|
||||
)
|
||||
if filtered:
|
||||
phrase = _lemmatize_compound(filtered)
|
||||
phrase = " ".join(t.text for t in filtered)
|
||||
if len(phrase) > 3 and " " in phrase:
|
||||
entities.append(("COMPOUND", phrase))
|
||||
_add_candidate(
|
||||
candidates,
|
||||
"TOPIC",
|
||||
phrase,
|
||||
"topic_phrase",
|
||||
filtered[0].i,
|
||||
filtered[-1].i + 1,
|
||||
0.45,
|
||||
4,
|
||||
)
|
||||
|
||||
# === FALLBACK: Mis-tagged VERB heads ===
|
||||
processed = {e[1].lower() for e in entities if e[0] == "COMPOUND"}
|
||||
generic_verb_heads = _GENERIC_HEADS | {"find", "buy", "purchase", "sale", "deal", "trip", "visit"}
|
||||
|
||||
def collect_compounds(head):
|
||||
return [t for t in doc if t.head == head and t.dep_ == "compound"]
|
||||
def _spans_overlap(a: _EntityCandidate, b: _EntityCandidate) -> bool:
|
||||
if a.start < 0 or b.start < 0:
|
||||
return False
|
||||
return a.start < b.end and b.start < a.end
|
||||
|
||||
for tok in doc:
|
||||
if tok.pos_ == "VERB" and tok.dep_ in {"pobj", "dobj", "nsubj"}:
|
||||
comps = sorted(collect_compounds(tok), key=lambda t: t.i)
|
||||
if comps:
|
||||
phrase_toks = comps if tok.lemma_.lower() in generic_verb_heads else comps + [tok]
|
||||
phrase = " ".join(t.text for t in phrase_toks)
|
||||
if phrase.lower() not in processed and len(phrase) > 3 and " " in phrase:
|
||||
entities.append(("COMPOUND", phrase))
|
||||
processed.add(phrase.lower())
|
||||
|
||||
# === DEDUPLICATION & CLEANUP ===
|
||||
seen: set = set()
|
||||
deduped = []
|
||||
for t, e in entities:
|
||||
k = e.lower().strip()
|
||||
if k not in seen and len(k) > 2:
|
||||
seen.add(k)
|
||||
deduped.append((t, e))
|
||||
def _resolve_candidates(candidates: list[_EntityCandidate]) -> list[tuple[str, str]]:
|
||||
deduped_by_text: dict[str, _EntityCandidate] = {}
|
||||
for candidate in candidates:
|
||||
key = _norm_text(candidate.text)
|
||||
current = deduped_by_text.get(key)
|
||||
if current is None or (candidate.priority, -candidate.confidence) < (current.priority, -current.confidence):
|
||||
deduped_by_text[key] = candidate
|
||||
|
||||
cleaned: List[Tuple[str, str]] = []
|
||||
for etype, etext in deduped:
|
||||
txt = re.sub(r"^\*+\s*|\s*\*+$", "", etext.strip())
|
||||
txt = re.sub(r"\s*:+$", "", txt)
|
||||
txt = re.sub(r"^\d+\s*\.\s*", "", txt)
|
||||
if not txt or len(txt) <= 2 or _has_artifacts(txt):
|
||||
ordered = sorted(
|
||||
deduped_by_text.values(),
|
||||
key=lambda c: (c.priority, -c.confidence, -(c.end - c.start), c.start),
|
||||
)
|
||||
accepted: list[_EntityCandidate] = []
|
||||
for candidate in ordered:
|
||||
if any(
|
||||
_spans_overlap(candidate, existing)
|
||||
and not (candidate.entity_type == "TOPIC" and " " in candidate.text and existing.entity_type == "PROPER")
|
||||
for existing in accepted
|
||||
):
|
||||
continue
|
||||
if etype == "PROPER" and " " not in txt and txt.lower() in _GENERIC_CAPS:
|
||||
continue
|
||||
cleaned.append((etype, txt))
|
||||
accepted.append(candidate)
|
||||
|
||||
# Keep best type per entity (PROPER > COMPOUND > QUOTED > NOUN)
|
||||
type_pri = {"PROPER": 0, "COMPOUND": 1, "QUOTED": 2, "NOUN": 3, "VERB": 4}
|
||||
best: dict = {}
|
||||
for t, e in cleaned:
|
||||
k = e.lower()
|
||||
if k not in best or type_pri.get(t, 99) < type_pri.get(best[k][0], 99):
|
||||
best[k] = (t, e)
|
||||
deduped = list(best.values())
|
||||
accepted.sort(key=lambda c: (c.start if c.start >= 0 else 10**9, c.end, c.priority))
|
||||
return [(candidate.entity_type, candidate.text) for candidate in accepted]
|
||||
|
||||
# Remove entities that are whole-word substrings of longer entities.
|
||||
# Word-boundary anchoring avoids dropping distinct entities that only share a
|
||||
# leading substring (e.g. "Sam" must survive alongside "Samsung").
|
||||
all_lower = [e[1].lower() for e in deduped]
|
||||
return [
|
||||
(t, e)
|
||||
for t, e in deduped
|
||||
if not any(e.lower() != o and re.search(rf"\b{re.escape(e.lower())}\b", o) for o in all_lower)
|
||||
]
|
||||
|
||||
def _extract_entities_from_doc(doc) -> list[tuple[str, str]]:
|
||||
"""Extract typed entity candidates from a spaCy Doc.
|
||||
|
||||
Args:
|
||||
doc: A spaCy ``Doc`` object (from ``nlp(text)``).
|
||||
|
||||
Returns:
|
||||
Deduplicated list of ``(entity_type, entity_text)`` tuples.
|
||||
Entity types include PROPER, QUOTED, TOPIC, and IDENTIFIER.
|
||||
"""
|
||||
tokens = list(doc)
|
||||
candidates: list[_EntityCandidate] = []
|
||||
_add_ner_candidates(doc, candidates)
|
||||
_add_technical_identifier_candidates(tokens, candidates)
|
||||
_add_proper_name_candidates(tokens, candidates)
|
||||
_add_quoted_candidates(doc.text, candidates)
|
||||
_add_topic_phrase_candidates(doc, candidates)
|
||||
return _resolve_candidates(candidates)
|
||||
|
||||
|
||||
def extract_entities(text: str) -> list[tuple[str, str]]:
|
||||
"""Extract typed entity candidates from text."""
|
||||
from mem0.utils.spacy_models import get_nlp_full
|
||||
|
||||
nlp = get_nlp_full()
|
||||
if nlp is None:
|
||||
return []
|
||||
return _extract_entities_from_doc(nlp(text))
|
||||
|
||||
|
||||
def extract_entities_batch(texts: list[str], batch_size: int = 32) -> list[list[tuple[str, str]]]:
|
||||
"""Extract typed entity candidates from multiple texts."""
|
||||
if not texts:
|
||||
return []
|
||||
|
||||
from mem0.utils.spacy_models import get_nlp_full
|
||||
|
||||
nlp = get_nlp_full()
|
||||
if nlp is None:
|
||||
return [[] for _ in texts]
|
||||
|
||||
return [_extract_entities_from_doc(doc) for doc in nlp.pipe(texts, batch_size=batch_size)]
|
||||
|
||||
@@ -298,9 +298,9 @@ class AzureAISearch(VectorStoreBase):
|
||||
payload (Dict, optional): Updated payload.
|
||||
"""
|
||||
document = {"id": vector_id}
|
||||
if vector:
|
||||
if vector is not None:
|
||||
document["vector"] = vector
|
||||
if payload:
|
||||
if payload is not None:
|
||||
json_payload = json.dumps(payload)
|
||||
document["payload"] = json_payload
|
||||
for field in ["user_id", "run_id", "agent_id"]:
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user