Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e7adc4d12 | ||
|
|
14393b5962 | ||
|
|
f590c9596a | ||
|
|
dd5f7e39a8 | ||
|
|
70ab76a053 | ||
|
|
2af3a72f73 | ||
|
|
8005e18aec | ||
|
|
39551145b8 | ||
|
|
c2bc28e589 | ||
|
|
fec2fe6a2c | ||
|
|
d0c23a5950 | ||
|
|
b05cce581b | ||
|
|
8a57967c8a | ||
|
|
756b0b1b6d | ||
|
|
726bcc80b2 |
@@ -9,12 +9,10 @@ body:
|
||||
label: Component
|
||||
description: Which part of mem0 is affected?
|
||||
options:
|
||||
- Core / Python SDK
|
||||
- Python SDK
|
||||
- TypeScript SDK
|
||||
- Vector Store (Qdrant, PGVector, Redis, Chroma, etc.)
|
||||
- Graph Memory (Neo4j, Memgraph, etc.)
|
||||
- Ollama / Local Models
|
||||
- OpenClaw
|
||||
- Vector Store
|
||||
- Plugin
|
||||
- REST API
|
||||
- Other
|
||||
validations:
|
||||
|
||||
@@ -9,14 +9,11 @@ body:
|
||||
label: Component
|
||||
description: Which part of mem0 does this relate to?
|
||||
options:
|
||||
- Core / Python SDK
|
||||
- Python SDK
|
||||
- TypeScript SDK
|
||||
- Vector Store (Qdrant, PGVector, Redis, Chroma, etc.)
|
||||
- Graph Memory (Neo4j, Memgraph, etc.)
|
||||
- Ollama / Local Models
|
||||
- OpenClaw
|
||||
- Vector Store
|
||||
- Plugin
|
||||
- REST API
|
||||
- Benchmarks / Evals
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
# Maps dropdown selections to GitHub labels
|
||||
# Used by the advanced-issue-labeler GitHub Action
|
||||
|
||||
component:
|
||||
- label: "sdk-python"
|
||||
matcher: "Core / Python SDK"
|
||||
- label: "sdk-typescript"
|
||||
matcher: "TypeScript SDK"
|
||||
- label: "vector-store"
|
||||
matcher: "Vector Store"
|
||||
- label: "graph-memory"
|
||||
matcher: "Graph Memory"
|
||||
- label: "ollama"
|
||||
matcher: "Ollama"
|
||||
- label: "openclaw"
|
||||
matcher: "OpenClaw"
|
||||
- label: "rest-api"
|
||||
matcher: "REST API"
|
||||
policy:
|
||||
- section:
|
||||
- id: ['component']
|
||||
block-list: ['Other']
|
||||
label:
|
||||
- name: 'sdk-python'
|
||||
keys: ['Python SDK']
|
||||
- name: 'sdk-typescript'
|
||||
keys: ['TypeScript SDK']
|
||||
- name: 'vector-store'
|
||||
keys: ['Vector Store']
|
||||
- name: 'plugin'
|
||||
keys: ['Plugin']
|
||||
- name: 'rest-api'
|
||||
keys: ['REST API']
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"language": {
|
||||
"sdk-python": [
|
||||
"python", "pip install", "pypi", "pyproject", "requirements.txt",
|
||||
"from mem0", "import mem0", "traceback", "pydantic", "asyncmemory",
|
||||
"poetry", "virtualenv", "venv", "conda", "pytest", "async def"
|
||||
],
|
||||
"sdk-typescript": [
|
||||
"typescript", "javascript", "pnpm", "yarn", "node.js", "nodejs",
|
||||
"mem0-ts", "mem0ai/oss", "tsconfig", "await import",
|
||||
"=> {", "undefined is not"
|
||||
]
|
||||
},
|
||||
"area": {
|
||||
"plugin": [
|
||||
"openclaw", "openclaw-mem0", "openclaw.json", "openclaw plugin",
|
||||
"claude code", "opencode", "pi agent", "mem0-plugin",
|
||||
"cursor plugin", "codex plugin", "editor plugin"
|
||||
],
|
||||
"openmemory": [
|
||||
"openmemory", "open memory", "localhost:8765", "localhost:3000",
|
||||
"openmemory ui", "openmemory/api", "openmemory/ui"
|
||||
],
|
||||
"cli": ["mem0-cli", "@mem0/cli", "npx mem0", "command line"],
|
||||
"vector-store": [
|
||||
"pgvector", "pinecone", "chroma", "chromadb", "weaviate",
|
||||
"milvus", "faiss", "vector store", "vectorstore",
|
||||
"elasticsearch", "supabase", "azure ai search",
|
||||
"s3 vectors", "mongodb"
|
||||
],
|
||||
"integrations": [
|
||||
"vercel ai", "vercel-ai-sdk", "@mem0/vercel-ai-provider",
|
||||
"llamaindex", "crewai", "autogen", "langgraph"
|
||||
],
|
||||
"rest-api": [
|
||||
"rest api", "fastapi", "docker-compose", "/v1/memories",
|
||||
"localhost:8000", "localhost:8888", "curl -x", "http endpoint"
|
||||
],
|
||||
"documentation": [
|
||||
"docs.mem0.ai", "documentation", "typo", "readme", "docstring", "broken link",
|
||||
"issue on docs", "docs:", "link to the docs page", "issue with current documentation"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
sdk-python:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- 'mem0/**'
|
||||
- 'tests/**'
|
||||
- 'cli/python/**'
|
||||
- 'pyproject.toml'
|
||||
- 'poetry.lock'
|
||||
|
||||
sdk-typescript:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- 'mem0-ts/**'
|
||||
- 'cli/node/**'
|
||||
|
||||
vector-store:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- 'mem0/vector_stores/**'
|
||||
- 'mem0-ts/src/oss/src/vector_stores/**'
|
||||
|
||||
rest-api:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'server/**'
|
||||
|
||||
openmemory:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'openmemory/**'
|
||||
|
||||
integrations:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'integrations/**'
|
||||
|
||||
plugin:
|
||||
- changed-files:
|
||||
- all-globs-to-any-file:
|
||||
- 'integrations/**'
|
||||
- '!integrations/vercel-ai-sdk/**'
|
||||
- any-glob-to-any-file:
|
||||
- 'skills/**'
|
||||
- '.agents/**'
|
||||
- '.claude-plugin/**'
|
||||
- '.codex-plugin/**'
|
||||
- '.cursor-plugin/**'
|
||||
- 'marketplace.json'
|
||||
|
||||
cli:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'cli/**'
|
||||
|
||||
documentation:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- 'docs/**'
|
||||
- 'examples/**'
|
||||
- '*.md'
|
||||
|
||||
ci:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- '.github/**'
|
||||
- 'scripts/**'
|
||||
- '.pre-commit-config.yaml'
|
||||
@@ -0,0 +1,44 @@
|
||||
const fs = require('fs');
|
||||
|
||||
function componentLabels(keywords) {
|
||||
return Object.values(keywords).flatMap(Object.keys);
|
||||
}
|
||||
|
||||
function toMatcher(term) {
|
||||
const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const prefix = /^[a-z0-9]/i.test(term) ? '\\b' : '';
|
||||
return new RegExp(prefix + escaped, 'i');
|
||||
}
|
||||
|
||||
function scoreGroup(text, group) {
|
||||
let winner = null;
|
||||
let best = 0;
|
||||
for (const [label, terms] of Object.entries(group)) {
|
||||
const score = terms.reduce((n, term) => n + (toMatcher(term).test(text) ? 1 : 0), 0);
|
||||
if (score > best) {
|
||||
winner = label;
|
||||
best = score;
|
||||
}
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
|
||||
const UMBRELLA = { plugin: 'integrations' };
|
||||
|
||||
function inferComponentLabels(text, keywords) {
|
||||
if (!text) return [];
|
||||
const labels = [scoreGroup(text, keywords.language), scoreGroup(text, keywords.area)].filter(
|
||||
Boolean,
|
||||
);
|
||||
for (const label of labels.slice()) {
|
||||
const parent = UMBRELLA[label];
|
||||
if (parent && !labels.includes(parent)) labels.push(parent);
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
function loadKeywords(file) {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
module.exports = { componentLabels, inferComponentLabels, loadKeywords };
|
||||
@@ -0,0 +1,108 @@
|
||||
const assert = require('assert');
|
||||
const path = require('path');
|
||||
const { inferComponentLabels, loadKeywords } = require('./infer-component-labels.js');
|
||||
|
||||
const keywords = loadKeywords(path.join(__dirname, '..', 'component-keywords.json'));
|
||||
|
||||
const cases = [
|
||||
{
|
||||
number: 6210,
|
||||
title: "but(anthropic): sampling parameters returns 400 error for new model",
|
||||
body: "### Component\n\nCore / Python SDK\n\n### Description\n\n### Summary\n\nWhen using Anthropic latest models such as `claude-opus-4-7`, `claude-opus-4-8`, or `claude-sonnet-5`, Mem0 still sends sampling parameters like `temperature` / `top_p`. These models do not support those parameters, causing Anthropic API requests to fail.\n\nSee https://platform.claude.com/docs/en/about-claude/models/migration-guide\n\n### Steps to Reproduce\n\n```python\n from mem0 import Memory\n\n m = Memory.from_config({\n \"llm\": {\n \"provider\": \"anthropic\",\n \"config\": {\n \"model\": \"claude-opus-4-8\",\n \"api_key\": \"your-anthropic-api-key\"\n },\n },\n ...\n })\n```\n\n### Expected Behavior\n\nMem0 should detect Anthropic models that do not support sampling parameters and omit temperature and top_p from the request.\n\nFor models that still support sampling parameters, such as claude-opus-4-6, claude-sonnet-4-6, and claude-haiku-4-5, Mem0 should continue sending supported sampling parameters till they're deprecated.\n\n### Actual Behavior\n\nMem0 includes temperature by default for Anthropic requests. With newer Anthropic models that do not support sampling parameters, the API request fails because unsupported parameters are sent.\n\n### Environment\n\n - mem0 version: 2.0.11\n - Python/Node version: Python 3.11\n - OS: macOS\n",
|
||||
expected: ["sdk-python"],
|
||||
},
|
||||
{
|
||||
number: 5770,
|
||||
title: "feat(ts-sdk): add FastEmbed embedding provider",
|
||||
body: "## Summary\n\nThe Python SDK supports **FastEmbed** as an embedding provider, but the TypeScript OSS SDK (`mem0ai/oss`) does not. Add it to bring the TS SDK to parity.\n\n| | |\n|---|---|\n| Python reference | `mem0/embeddings/fastembed.py` |\n| Registered in (Python) | `mem0/utils/factory.py` (EmbedderFactory) |\n| Target file (TypeScript) | `mem0-ts/src/oss/src/embeddings/fastembed.ts` |\n| Suggested implementation | Use the `fastembed` npm package (ONNX local embeddings). |\n\n## Requirements\n\n- [ ] Implement `FastEmbedEmbedder` in `mem0-ts/src/oss/src/embeddings/fastembed.ts`, extending `Embedder` (`mem0-ts/src/oss/src/embeddings/base.ts`) and mirroring the Python provider's behavior (embed / embedBatch).\n- [ ] Register the `\"fastembed\"` provider in `mem0-ts/src/oss/src/utils/factory.ts` (EmbedderFactory).\n- [ ] Add config typing in `mem0-ts/src/oss/src/types/`.\n- [ ] Add a unit test under `mem0-ts/src/oss/src/tests/`.\n- [ ] Add `fastembed` to `mem0-ts/package.json` (optional/peer dependency, lazy-imported like other providers).\n- [ ] Update docs under `docs/` if this provider is user-facing.\n\n## Reference pattern\n\nMirror an existing TS provider: `embeddings/openai.ts`.\n\n## Notes\n\n`fastembed` (v2.x) is the JS port of Qdrant's FastEmbed — local/offline embeddings. Mirror the default model in `mem0/embeddings/fastembed.py`.\n\n---\n_Part of the TypeScript ↔ Python SDK provider-parity effort. One provider per issue (atomic)._\n",
|
||||
expected: ["sdk-typescript"],
|
||||
},
|
||||
{
|
||||
number: 3940,
|
||||
title: "Milvus database will return distance not similarity score",
|
||||
body: "### 🐛 Describe the bug\n\nMilvus database will return distance not similarity score\n\n## in milvus.py\n\ndef _parse_output(self, data: list):\n \"\"\"\n Parse the output data.\n\n Args:\n data (Dict): Output data.\n\n Returns:\n List[OutputData]: Parsed output data.\n \"\"\"\n memory = []\n\n for value in data:\n uid, score, metadata = (\n value.get(\"id\"),\n value.get(\"distance\"), # here\n value.get(\"entity\", {}).get(\"metadata\"),\n )\n\n memory_obj = OutputData(id=uid, score=score, payload=metadata)\n memory.append(memory_obj)\n\n return memory\n",
|
||||
expected: ["vector-store"],
|
||||
},
|
||||
{
|
||||
number: 5290,
|
||||
title: "Recall search failed: Bad Request Using OpenAI Embedding Model",
|
||||
body: "### Component\n\nOpenClaw\n\n### Description\n\n### Summary\nuse openclaw.json config:\n\n```json\n...\n\"embedder\": {\n \"provider\": \"openai\",\n \"config\": {\n \"model\": \"bge-base-zh-v1.5\",\n \"embedding_dims\": 1024,\n \"embeddingDims\": 1024,\n \"url\": \"https://xxxxxxxxx/v1\",\n \"apiKey\": \"xxxxxxxxxxxx\"\n }\n },\n\"vectorStore\": {\n \"provider\": \"qdrant\",\n \"config\": {\n \"url\": \"http://qdrant:6333\",\n \"apiKey\": \"${QDRANT_API_KEY}\",\n \"collectionName\": \"mem0\",\n \"embeddingModelDims\": 1024\n }\n }\n```\n```\n\nopenclaw log info is:\n\n```\n23:14:20 Api key is used with unsecure connection.\n23:14:21 [mem0] Recall search failed: Bad Request\n23:14:21 [plugins] openclaw-mem0: skills-mode recall (strategy=smart) injecting 0 memories (~20 tokens)\n23:14:22 [ws] ⇄ res ✓ sessions.list 256ms conn=d1eb9bc4…17da id=201b8113…c9dc\n23:14:22 [ws] ⇄ res ✓ sessions.list 264ms conn=d1eb9bc4…17da id=4939f962…2f16\n23:14:34 [ws] ⇄ res ✓ sessions.list 250ms conn=d1eb9bc4…17da id=f7ad503f…baa6\n23:15:12 [mem0] **Recall search failed: Bad Request**\n23:15:12 [plugins] openclaw-mem0: skills-mode recall (strategy=smart) injecting 0 memories (~20 tokens)\n23:15:12 [ws] ⇄ res ✓ sessions.list 288ms conn=d1eb9bc4…17da id=9e20bb86…371e\n23:15:13 [ws] ⇄ res ✓ sessions.list 268ms conn=d1eb9bc4…17da id=3b49a2ad…7ada\n23:15:20 [ws] ⇄ res ✓ sessions.list 235ms conn=d1eb9bc4…17da id=a192da30…069f\n```\n\n### Actual Behavior\n\nembedding model response ok,response message has 1024 vectors,but the vectors are submitted to vector-db:qdrant with all zero vectors,and vectors has only 256 size.\n\n```http\nPOST /collections/mem0/points/search HTTP/1.1\nhost: qdrant:6333\nconnection: keep-alive\nuser-agent: qdrant-js/1.13.0\napi-key: xxxxxxxxxxxxxxxxxxxxxxxxxxxx\nContent-Type: application/json\nAccept: application/json\naccept-language: *\nsec-fetch-mode: cors\naccept-encoding: gzip, deflate\ncontent-length: 651\n\n{\"vector\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\"limit\":120,\"offset\":0,\"filter\":{\"must\":[{\"key\":\"user_id\",\"match\":{\"value\":\"agent\"}}]},\"with_payload\":true,\"with_vector\":false}\n\n**HTTP/1.1 400 Bad Request**\ntransfer-encoding: chunked\ncontent-type: application/json\nvary: accept-encoding, Origin, Access-Control-Request-Method, Access-Control-Request-Headers\ncontent-encoding: gzip\n\n```\n\n### Expected Behavior\n\nembedding model response ok by tcpdump, response message has 1024 vectors,and this vectors are submitted to vector-db:qdrant with the same vectors,and vectors has also 1024 size.\n\n\n### Environment\n\n- openclaw-mem0 version: 1.0.11\n- qdrant: 1.13.6\n",
|
||||
expected: ["plugin", "integrations"],
|
||||
},
|
||||
{
|
||||
number: 3696,
|
||||
title: "Cannot set expiration_date for memory in REST API server (Docker Compose)",
|
||||
body: "### 🐛 Describe the bug\n\nI'm using docker compose to deploy a REST API server. When adding memory, I'm unable to set the expiration_date. Is this feature not supported?",
|
||||
expected: ["rest-api"],
|
||||
},
|
||||
{
|
||||
number: 3444,
|
||||
title: "Fix: Openmemory run.sh non-existent vector-store route",
|
||||
body: "### 🐛 Describe the bug\n\n# Vector_store not implemented\nThere is many references to ` ${NEXT_PUBLIC_API_URL}/api/v1/config/mem0/vector_store` in lines 280, 293, 306, 319, 332, 345, 358, and 371. \n```bash\ncurl -fsS -X PUT \"${NEXT_PUBLIC_API_URL}/api/v1/config/mem0/vector_store\" # Line 280 and for each vector store\n```\nBut the api route is not implemented in `api/app/routers/config.py`.\n# Suggested solution\nI would implement `vector_store` route or remove and use `update_configuration` for all config updates. Also Create class with all config keys for vector_store",
|
||||
expected: ["openmemory"],
|
||||
},
|
||||
{
|
||||
number: 6252,
|
||||
title: "cursor: on_file_read_cursor.sh ignores auto_search / MEM0_AUTO_SEARCH",
|
||||
body: "### Component\n\nCursor / mem0-plugin\n\n### Description\n\n`on_file_read_cursor.sh` never checks `MEM0_AUTO_SEARCH`. In Claude Code, #6065/#6071 added a guard on `on_file_read.sh`, but the Cursor PreToolUse variant still always calls `file_context.py` (and thus Platform search) once `MEM0_API_KEY` is set.\n\n### Expected\n\nWhen `auto_search: false` / `MEM0_AUTO_SEARCH=false`, `on_file_read_cursor.sh` should exit 0 without searching.\n\n### Actual\n\nTimeline search still runs.\n\n### Related\n\n#6065, #6071, #6250\n",
|
||||
expected: ["plugin", "integrations"],
|
||||
},
|
||||
{
|
||||
number: 6032,
|
||||
title: "docs: fix typos and punctuation errors across docs",
|
||||
body: "### Description\n\n### Page\nMultiple pages — see list below.\n\n### What's Wrong or Missing\n1. https://docs.mem0.ai/components/llms/overview — \"a llm\" should be \"an LLM\"\n2. https://docs.mem0.ai/components/vectordbs/dbs/azure — 2 comma splices + \"setup\" used as a verb (should be \"set up\")\n3. https://docs.mem0.ai/components/embedders/models/azure_openai — \"from the Azure.\" is an incomplete sentence\n4. https://docs.mem0.ai/components/llms/models/azure_openai — same incomplete \"from the Azure\" phrasing\n5. https://docs.mem0.ai/cookbooks/companions/voice-companion-openai — \"an important information\" (uncountable noun)\n6. https://docs.mem0.ai/cookbooks/essentials/exporting-memories — comma splice\n7. https://docs.mem0.ai/cookbooks/integrations/tavily-search — \"usecase\" should be \"use case\"\n8. https://docs.mem0.ai/cookbooks/overview — broken parallelism in bullet list\n9. README.md — \"Github App\" should be \"GitHub App\"\n10. https://docs.mem0.ai/platform/overview — table cell not capitalized like other rows\n\n### Suggested Fix\nApply the corrections listed above for each page. I will submit a PR soon addressing all of the issues mentioned.",
|
||||
expected: ["documentation"],
|
||||
},
|
||||
];
|
||||
|
||||
const cliRegressionCase = {
|
||||
number: 3144,
|
||||
title: "Bug Report: Memory Score Does Not Match Expected Relevance in Local Search",
|
||||
body: "### 🐛 Describe the bug\n\n#### Description\n\nWhen using the locally deployed `mem0` server, the returned memory `score` from the `search` interface does not align with the expected semantic relevance. In particular, irrelevant or less relevant memories sometimes receive higher scores than directly related ones.\n\n#### Reproduction Steps\n\n```python\nmem0 = mem0_client(mode=\"local\")\nprint(\"Mem0 client initialized successfully.\")\n\nprint(\"Adding memories...\")\nresult = mem0.add(messages=[\n {\"role\": \"user\", \"content\": \"I like drinking coffee in the morning\"},\n {\"role\": \"user\", \"content\": \"I enjoy reading books at night\"}\n], user_id=\"alice\")\nprint(\"Memory added:\", result)\n\nprint(\"Searching memories...\")\nsearch_result = mem0.search(query=\"coffee\", user_id=\"alice\", top_k=2)\nprint(\"Search results:\", search_result)\n```\n\n#### Actual Output\n\n```json\n{\n \"results\": [\n {\n \"id\": \"5099b5be-c673-4f09-99de-a196f43b6476\",\n \"memory\": \"Likes drinking coffee in the morning\",\n \"score\": 0.5115111920687857\n },\n {\n \"id\": \"08df5c51-c52b-4c45-a5b6-b3f864ea149a\",\n \"memory\": \"Enjoys reading books at night\",\n \"score\": 0.7755568273863331\n }\n ],\n \"relations\": [\n {\"source\": \"coffee\", \"relationship\": \"consumed_in\", \"destination\": \"morning\"},\n {\"source\": \"user_id:_alice\", \"relationship\": \"likes\", \"destination\": \"coffee\"},\n {\"source\": \"user_id:_alice\", \"relationship\": \"likes_drinking\", \"destination\": \"coffee\"},\n {\"source\": \"user_id:_alice\", \"relationship\": \"in_time\", \"destination\": \"morning\"},\n {\"source\": \"user_id:_alice\", \"relationship\": \"drinks_in\", \"destination\": \"morning\"}\n ]\n}\n```\n\n#### Expected Behavior\n\nThe memory `\"Likes drinking coffee in the morning\"` should have a **higher score** than `\"Enjoys reading books at night\"` when querying for `\"coffee\"`, since it is directly semantically related.",
|
||||
};
|
||||
|
||||
let failures = 0;
|
||||
|
||||
function run(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(`PASS ${name}`);
|
||||
} catch (err) {
|
||||
failures++;
|
||||
console.error(`FAIL ${name}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const { number, title, body, expected } of cases) {
|
||||
const text = `${title}
|
||||
|
||||
${body}`;
|
||||
run(`#${number}`, () => {
|
||||
assert.deepStrictEqual(inferComponentLabels(text, keywords), expected);
|
||||
});
|
||||
}
|
||||
|
||||
run('#3144 cliKeywordPrefixSubstringRegression', () => {
|
||||
const text = `${cliRegressionCase.title}
|
||||
|
||||
${cliRegressionCase.body}`;
|
||||
const inferred = inferComponentLabels(text, keywords);
|
||||
assert.ok(!inferred.includes('cli'), `expected 'cli' absent (body contains 'Mem0 client', a substring of the removed 'mem0 cli' term), got ${JSON.stringify(inferred)}`);
|
||||
});
|
||||
|
||||
run('noKeywordMatchReturnsEmptyArray', () => {
|
||||
const text = 'The weather today is sunny and I went for a walk in the park with my dog.';
|
||||
assert.deepStrictEqual(inferComponentLabels(text, keywords), []);
|
||||
});
|
||||
|
||||
run('emptyStringReturnsEmptyArray', () => {
|
||||
assert.deepStrictEqual(inferComponentLabels('', keywords), []);
|
||||
});
|
||||
|
||||
if (failures > 0) {
|
||||
console.error(`
|
||||
${failures} test(s) failed.`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`
|
||||
All ${cases.length + 3} tests passed.`);
|
||||
@@ -40,8 +40,6 @@ jobs:
|
||||
openclaw: ${{ steps.filter.outputs.openclaw }}
|
||||
opencode_plugin: ${{ steps.filter.outputs.opencode_plugin }}
|
||||
pi_agent_plugin: ${{ steps.filter.outputs.pi_agent_plugin }}
|
||||
n8n_nodes_mem0: ${{ steps.filter.outputs.n8n_nodes_mem0 }}
|
||||
zapier_mem0: ${{ steps.filter.outputs.zapier_mem0 }}
|
||||
docs_llms_txt: ${{ steps.filter.outputs.docs_llms_txt }}
|
||||
steps:
|
||||
- uses: dorny/paths-filter@v3
|
||||
@@ -81,14 +79,6 @@ jobs:
|
||||
- 'integrations/pi-agent-plugin/**'
|
||||
- '.github/workflows/pi-agent-plugin-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
n8n_nodes_mem0:
|
||||
- 'integrations/n8n-nodes-mem0/**'
|
||||
- '.github/workflows/n8n-nodes-mem0-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
zapier_mem0:
|
||||
- 'integrations/zapier-mem0/**'
|
||||
- '.github/workflows/zapier-mem0-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
docs_llms_txt:
|
||||
- 'docs/**/*.mdx'
|
||||
- 'docs/llms.txt'
|
||||
@@ -146,20 +136,6 @@ jobs:
|
||||
uses: ./.github/workflows/pi-agent-plugin-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
n8n-nodes-mem0:
|
||||
name: n8n Node
|
||||
needs: changes
|
||||
if: needs.changes.outputs.n8n_nodes_mem0 == 'true'
|
||||
uses: ./.github/workflows/n8n-nodes-mem0-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
zapier-mem0:
|
||||
name: Zapier App
|
||||
needs: changes
|
||||
if: needs.changes.outputs.zapier_mem0 == 'true'
|
||||
uses: ./.github/workflows/zapier-mem0-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
docs-llms-txt:
|
||||
name: docs llms.txt
|
||||
needs: changes
|
||||
@@ -178,8 +154,6 @@ jobs:
|
||||
- openclaw
|
||||
- opencode-plugin
|
||||
- pi-agent-plugin
|
||||
- n8n-nodes-mem0
|
||||
- zapier-mem0
|
||||
- docs-llms-txt
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -12,28 +12,56 @@ jobs:
|
||||
label:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: stefanbuck/github-issue-parser@v3
|
||||
id: issue-parser
|
||||
continue-on-error: true
|
||||
with:
|
||||
template-path: .github/ISSUE_TEMPLATE/bug_report.yml
|
||||
|
||||
- uses: redhat-plumbers-in-action/advanced-issue-labeler@v3
|
||||
continue-on-error: true
|
||||
with:
|
||||
issue-form: ${{ steps.issue-parser.outputs.jsonString }}
|
||||
section: component
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
config-path: .github/advanced-issue-labeler.yml
|
||||
|
||||
- uses: stefanbuck/github-issue-parser@v3
|
||||
id: feature-parser
|
||||
if: contains(github.event.issue.labels.*.name, 'enhancement')
|
||||
- name: Infer component from text when the form was not used
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
template-path: .github/ISSUE_TEMPLATE/feature_request.yml
|
||||
script: |
|
||||
const {
|
||||
componentLabels,
|
||||
inferComponentLabels,
|
||||
loadKeywords,
|
||||
} = require(`${process.env.GITHUB_WORKSPACE}/.github/scripts/infer-component-labels.js`);
|
||||
|
||||
- uses: redhat-plumbers-in-action/advanced-issue-labeler@v3
|
||||
if: contains(github.event.issue.labels.*.name, 'enhancement')
|
||||
with:
|
||||
issue-form: ${{ steps.feature-parser.outputs.jsonString }}
|
||||
section: component
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
config-path: .github/advanced-issue-labeler.yml
|
||||
const { data: issue } = await github.rest.issues.get({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
});
|
||||
|
||||
const keywords = loadKeywords(`${process.env.GITHUB_WORKSPACE}/.github/component-keywords.json`);
|
||||
const known = componentLabels(keywords);
|
||||
const existing = issue.labels.map((label) => label.name || label);
|
||||
if (existing.some((name) => known.includes(name))) {
|
||||
core.info(`Component label already present: ${existing.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const labels = inferComponentLabels(`${issue.title}\n\n${issue.body || ''}`, keywords);
|
||||
|
||||
if (labels.length === 0) {
|
||||
core.info('No component could be inferred from the issue text');
|
||||
return;
|
||||
}
|
||||
|
||||
core.info(`Inferred: ${labels.join(', ')}`);
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
labels,
|
||||
});
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
name: Publish n8n-nodes-mem0 📦 to npm
|
||||
|
||||
# Dispatched by release.yml (Release Router) when a release tagged
|
||||
# n8n-nodes-mem0-v* is published. Can also be dispatched manually to
|
||||
# re-publish a tag.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to build and publish (e.g. n8n-nodes-mem0-v0.1.0)'
|
||||
required: true
|
||||
type: string
|
||||
prerelease:
|
||||
description: 'Publish under the version preid dist-tag instead of latest'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
build-n-publish:
|
||||
name: Build and publish n8n-nodes-mem0 📦 to npm
|
||||
if: startsWith(inputs.tag, 'n8n-nodes-mem0-v')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
defaults:
|
||||
run:
|
||||
working-directory: integrations/n8n-nodes-mem0
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.tag }}
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/n8n-nodes-mem0/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile --ignore-scripts
|
||||
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
|
||||
- name: Publish to npm
|
||||
run: |
|
||||
if [ "${{ inputs.prerelease }}" = "true" ]; then
|
||||
PREID=$(node -p "require('./package.json').version.split('-')[1].split('.')[0]")
|
||||
npx npm@latest publish --provenance --access public --tag "$PREID"
|
||||
else
|
||||
npx npm@latest publish --provenance --access public
|
||||
fi
|
||||
@@ -1,65 +0,0 @@
|
||||
name: n8n-nodes-mem0 checks
|
||||
|
||||
# On PRs this is invoked by ci-gate.yml (the single required check);
|
||||
# push-to-main and manual runs remain standalone.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'integrations/n8n-nodes-mem0/**'
|
||||
- '.github/workflows/n8n-nodes-mem0-checks.yml'
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/n8n-nodes-mem0/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd integrations/n8n-nodes-mem0 && pnpm install --frozen-lockfile --ignore-scripts
|
||||
|
||||
- name: Lint
|
||||
run: cd integrations/n8n-nodes-mem0 && pnpm run lint
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/n8n-nodes-mem0/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd integrations/n8n-nodes-mem0 && pnpm install --frozen-lockfile --ignore-scripts
|
||||
|
||||
- name: Build
|
||||
run: cd integrations/n8n-nodes-mem0 && pnpm run build
|
||||
|
||||
- name: Verify dist output exists
|
||||
run: |
|
||||
test -f integrations/n8n-nodes-mem0/dist/nodes/Mem0/Mem0.node.js || (echo "Build output missing: dist/nodes/Mem0/Mem0.node.js" && exit 1)
|
||||
test -f integrations/n8n-nodes-mem0/dist/credentials/Mem0Api.credentials.js || (echo "Build output missing: dist/credentials/Mem0Api.credentials.js" && exit 1)
|
||||
test -f integrations/n8n-nodes-mem0/dist/nodes/Mem0/mem0.svg || (echo "Build output missing: dist/nodes/Mem0/mem0.svg" && exit 1)
|
||||
@@ -0,0 +1,64 @@
|
||||
name: PR Labeler
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
|
||||
concurrency:
|
||||
group: pr-labeler-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: read
|
||||
|
||||
jobs:
|
||||
label:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/labeler@v5
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Propagate labels from linked issues
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const allowed = new Set([
|
||||
'sdk-python', 'sdk-typescript', 'vector-store', 'plugin',
|
||||
'rest-api', 'openmemory', 'documentation', 'ci', 'cli', 'integrations',
|
||||
]);
|
||||
const umbrella = { plugin: 'integrations' };
|
||||
const { repository } = await github.graphql(
|
||||
`query ($owner: String!, $repo: String!, $number: Int!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
pullRequest(number: $number) {
|
||||
closingIssuesReferences(first: 20) {
|
||||
nodes { labels(first: 50) { nodes { name } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ owner: context.repo.owner, repo: context.repo.repo, number: context.issue.number },
|
||||
);
|
||||
|
||||
const labels = new Set();
|
||||
for (const issue of repository.pullRequest.closingIssuesReferences.nodes) {
|
||||
for (const label of issue.labels.nodes) {
|
||||
if (allowed.has(label.name)) labels.add(label.name);
|
||||
}
|
||||
}
|
||||
|
||||
for (const label of [...labels]) {
|
||||
if (umbrella[label]) labels.add(umbrella[label]);
|
||||
}
|
||||
|
||||
if (labels.size > 0) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
labels: [...labels],
|
||||
});
|
||||
}
|
||||
@@ -45,7 +45,6 @@ jobs:
|
||||
openclaw-v*) workflow="openclaw-cd.yml" ;;
|
||||
opencode-v*) workflow="opencode-plugin-cd.yml" ;;
|
||||
pi-agent-v*) workflow="pi-agent-plugin-cd.yml" ;;
|
||||
n8n-nodes-mem0-v*) workflow="n8n-nodes-mem0-cd.yml" ;;
|
||||
v*) workflow="cd.yml" ;;
|
||||
*)
|
||||
echo "::error::Release tag '$TAG' does not match any known package prefix — nothing will be published. See the tag prefix table in AGENTS.md."
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
name: Deploy zapier-mem0 to Zapier
|
||||
|
||||
# Zapier apps deploy to Zapier's own platform (not npm), so this is NOT wired
|
||||
# into the npm release router (release.yml). It is manual workflow_dispatch
|
||||
# only and requires the ZAPIER_DEPLOY_KEY repo secret.
|
||||
#
|
||||
# gh workflow run zapier-mem0-cd.yml --ref main
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
push:
|
||||
name: Push zapier-mem0 to Zapier
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: integrations/zapier-mem0
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/zapier-mem0/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Push to Zapier
|
||||
env:
|
||||
ZAPIER_DEPLOY_KEY: ${{ secrets.ZAPIER_DEPLOY_KEY }}
|
||||
run: npx zapier-platform-cli@19 push
|
||||
@@ -1,44 +0,0 @@
|
||||
name: zapier-mem0 checks
|
||||
|
||||
# On PRs this is invoked by ci-gate.yml (the single required check);
|
||||
# push-to-main and manual runs remain standalone.
|
||||
#
|
||||
# CI runs `zapier validate` (offline schema + style checks) plus the offline
|
||||
# jest unit suite (test/unit.test.js — mocked z.request, no network). The
|
||||
# end-to-end jest suite is skipped here because it hits the live Mem0 API — it
|
||||
# runs locally with MEM0_API_KEY set (see the package README).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'integrations/zapier-mem0/**'
|
||||
- '.github/workflows/zapier-mem0-checks.yml'
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/zapier-mem0/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd integrations/zapier-mem0 && pnpm install --frozen-lockfile
|
||||
|
||||
- name: Validate Zapier app definition
|
||||
run: cd integrations/zapier-mem0 && npx zapier-platform-cli@19 validate
|
||||
|
||||
- name: Run offline unit tests
|
||||
run: cd integrations/zapier-mem0 && pnpm test:unit
|
||||
@@ -431,8 +431,6 @@ PR testing is orchestrated by a single entry point: **`ci-gate.yml` (CI Gate)**
|
||||
| OpenClaw | `openclaw-checks.yml` | Push to main (on `integrations/openclaw/`), manual | tsc + vitest (with Codecov) + tsup build on Node 20, 22 |
|
||||
| OpenCode Plugin | `opencode-plugin-checks.yml` | Push to main (on `integrations/mem0-plugin/.opencode-plugin/`), manual | Bun: tsc type-check + build + dist artifact check |
|
||||
| Pi Agent Plugin | `pi-agent-plugin-checks.yml` | Push to main (on `integrations/pi-agent-plugin/`), manual | tsc + vitest + tsup build (dist artifact check) on Node 20, 22 |
|
||||
| n8n Node | `n8n-nodes-mem0-checks.yml` | Push to main (on `integrations/n8n-nodes-mem0/`), manual | ESLint (n8n-nodes-base) + tsc build (dist artifact check) on Node 20 |
|
||||
| Zapier App | `zapier-mem0-checks.yml` | Push to main (on `integrations/zapier-mem0/`), manual | `zapier validate` (schema + style checks) on Node 20 |
|
||||
| docs llms.txt | `docs-llms-txt-check.yml` | Manual | `docs/llms.txt` coverage check |
|
||||
|
||||
When adding a new package CI workflow: give it `workflow_call` (plus `push`/`workflow_dispatch` as needed, but no `pull_request` trigger), then register it in `ci-gate.yml` — a path filter under the `changes` job, a call job, and an entry in the gate job's `needs` list.
|
||||
@@ -452,13 +450,11 @@ Publishing is routed through a single entry point: **`release.yml` (Release Rout
|
||||
| OpenClaw | `openclaw-cd.yml` | `openclaw-v*` | npm (`@mem0/openclaw-mem0`) |
|
||||
| OpenCode Plugin | `opencode-plugin-cd.yml` | `opencode-v*` | npm (`@mem0/opencode-plugin`) |
|
||||
| Pi Agent Plugin | `pi-agent-plugin-cd.yml` | `pi-agent-v*` | npm (`@mem0/pi-agent-plugin`) |
|
||||
| n8n Node | `n8n-nodes-mem0-cd.yml` | `n8n-nodes-mem0-v*` | npm (`n8n-nodes-mem0`) |
|
||||
|
||||
- Package CD workflows are `workflow_dispatch`-only (inputs: `tag`, `prerelease`); they check out and build the given tag. Registry trusted-publisher settings stay pinned to each package's own workflow filename.
|
||||
- All publishing uses **OIDC trusted publishing** — no tokens or secrets required.
|
||||
- First publish of a new npm package must be done manually; OIDC works for subsequent versions.
|
||||
- To re-publish a release (e.g. after a registry settings fix), do **not** delete/recreate the GitHub release — manually dispatch the package workflow instead: `gh workflow run <package>-cd.yml --ref refs/tags/<tag> -f tag=<tag>`.
|
||||
- The **Zapier app** (`integrations/zapier-mem0`) deploys to Zapier's own platform, not npm, so it is **not** in the release router. Deploy it manually: `gh workflow run zapier-mem0-cd.yml --ref main` (requires the `ZAPIER_DEPLOY_KEY` secret).
|
||||
- When adding a new package: add its CD workflow (`workflow_dispatch` with `tag`/`prerelease` inputs), then register its tag prefix in the `case` block in `release.yml`. Keep the bare `v*` arm last.
|
||||
|
||||
### Utility Workflows
|
||||
@@ -466,6 +462,7 @@ Publishing is routed through a single entry point: **`release.yml` (Release Rout
|
||||
| Workflow | File | Purpose |
|
||||
|----------|------|---------|
|
||||
| Issue Labeler | `issue-labeler.yml` | Automatic issue labeling |
|
||||
| PR Labeler | `pr-labeler.yml` | Path-based PR labeling plus propagating labels from linked issues |
|
||||
| Stale Bot | `stale.yml` | Marks stale issues and PRs |
|
||||
| llms.txt Check | `docs-llms-txt-check.yml` | Blocks PRs touching `docs/**/*.mdx` when `docs/llms.txt` is out of sync. Fix locally with `python scripts/check-llms-txt-coverage.py --write`. |
|
||||
|
||||
|
||||
@@ -7,6 +7,23 @@ mode: "wide"
|
||||
<Tabs>
|
||||
<Tab title="Python">
|
||||
|
||||
<Update label="2026-07-22" description="v2.0.13">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Vector Stores:** Fix `reset()` silently leaving stale vectors behind on local (on-disk) Qdrant when the old collection directory could not be removed, for example an open file handle on Windows or NFS ([#6412](https://github.com/mem0ai/mem0/pull/6412))
|
||||
- **Core:** Stop `update()` metadata from overwriting or injecting `user_id`, `agent_id`, `run_id`, or `actor_id`. These identity fields are immutable after creation, so passing them in `metadata` can no longer move a memory into a different tenant's scope ([#6278](https://github.com/mem0ai/mem0/pull/6278))
|
||||
- **Vector Stores:** Scope Pinecone `delete_col()`/`reset()` to the configured namespace instead of deleting the whole index, so resetting a namespaced Pinecone store no longer wipes out the other namespaces sharing that index ([#6287](https://github.com/mem0ai/mem0/pull/6287))
|
||||
- **Vector Stores:** Convert Baidu Mochow's raw L2 distance into a similarity score in `search()` (`1 / (1 + distance)`), so closer matches rank higher instead of lower, matching the Milvus provider and the rest of the `VectorStoreBase` contract ([#6435](https://github.com/mem0ai/mem0/pull/6435))
|
||||
- **LLMs:** Read `OPENAI_BASE_URL` (was `OPENAI_API_BASE`) in `OpenAIStructuredLLM`, matching the official OpenAI SDK's environment variable and the rest of the OpenAI-compatible providers ([#6322](https://github.com/mem0ai/mem0/pull/6322))
|
||||
|
||||
**Improvements:**
|
||||
- **LLMs:** Remove a dead, no-op `api_key` attribute check from `LLMBase.__init__` ([#6460](https://github.com/mem0ai/mem0/pull/6460))
|
||||
|
||||
**Changes:**
|
||||
- **Client:** Remove the `retrieval_criteria` parameter from `MemoryClient.update_project()`/`AsyncMemoryClient.update_project()` and `Project.update()`/`AsyncProject.update()`. It was accepted and forwarded but never affected retrieval, so removing it is not a behavior change ([#6313](https://github.com/mem0ai/mem0/pull/6313))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-07-13" description="v2.0.12">
|
||||
|
||||
**New Features:**
|
||||
@@ -1128,6 +1145,23 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
|
||||
|
||||
<Tab title="TypeScript">
|
||||
|
||||
<Update label="2026-07-22" description="v3.1.1">
|
||||
|
||||
**New Features:**
|
||||
- **Embeddings:** Add an AWS Bedrock embedding provider ([#6185](https://github.com/mem0ai/mem0/pull/6185))
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Packaging:** Finish the lazy-loading work started in v3.1.0. The remaining LLMs (Anthropic, Google, Groq, LangChain, Mistral, Ollama), embedders (Google, LangChain, Ollama, Vertex AI), vector stores (Azure AI Search, Azure MySQL, Baidu, LangChain, Qdrant, Redis, Supabase, Valkey, Vectorize), and the Supabase history store still imported their SDKs at module load, so importing `mem0ai/oss` required every provider package to be installed ([#6389](https://github.com/mem0ai/mem0/pull/6389))
|
||||
- **Vector Stores:** Convert Baidu Mochow's raw L2 distance into a similarity score in `search()` (`1 / (1 + distance)`), so closer matches rank higher instead of lower. A row the backend returns without a score is now left `undefined` instead of being treated as the closest match ([#6485](https://github.com/mem0ai/mem0/pull/6485))
|
||||
- **Memory (OSS):** Coerce non-string entity IDs (e.g. a numeric `user_id`) to strings instead of crashing on `.trim()` ([#6263](https://github.com/mem0ai/mem0/pull/6263))
|
||||
- **Memory (OSS):** Stop `update()` metadata from overwriting or injecting `user_id`, `agent_id`, `run_id`, or `actor_id` (in either snake_case or camelCase). These identity fields are immutable after creation, so passing them in `metadata` can no longer move a memory into a different tenant's scope ([#6343](https://github.com/mem0ai/mem0/pull/6343))
|
||||
- **Vector Stores:** Scope Pinecone `deleteCol()`/`reset()` to the configured namespace instead of deleting the whole index, so resetting a namespaced Pinecone store no longer wipes out the other namespaces sharing that index ([#6287](https://github.com/mem0ai/mem0/pull/6287))
|
||||
|
||||
**Changes:**
|
||||
- **Client:** Remove the unused `retrievalCriteria` field from `PromptUpdatePayload`. It was accepted and forwarded but never affected retrieval, so removing it is not a behavior change ([#6313](https://github.com/mem0ai/mem0/pull/6313))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-07-13" description="v3.1.0">
|
||||
|
||||
The largest provider release for the TypeScript OSS SDK so far: 17 new vector stores, 5 new LLM providers, 4 new embedders, and reranking support. Importing `mem0ai/oss` no longer pulls in any provider SDK, so you only install what you actually configure.
|
||||
@@ -2084,6 +2118,13 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
|
||||
|
||||
<Tab title="OpenCode">
|
||||
|
||||
<Update label="2026-07-22" description="OpenCode plugin v0.2.2">
|
||||
|
||||
**Fixes:**
|
||||
- **Shell-profile API key recovery:** When `MEM0_API_KEY` isn't set in the process environment, the plugin now falls back to reading it from `.zshrc`, `.bashrc`, `.zprofile`, `.bash_profile`, or `.profile`, fixing startup failures on clients (e.g. Desktop) that launch without shell-exported environment variables.
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-30" description="OpenCode plugin v0.2.1">
|
||||
|
||||
**Improvements:**
|
||||
|
||||
@@ -348,8 +348,6 @@
|
||||
"pages": [
|
||||
"integrations/dify",
|
||||
"integrations/flowise",
|
||||
"integrations/n8n",
|
||||
"integrations/zapier",
|
||||
"integrations/langchain-tools",
|
||||
"integrations/agentops",
|
||||
"integrations/respan",
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
---
|
||||
title: n8n
|
||||
description: "Add long-term memory to n8n workflows and AI Agents with the Mem0 community node, no code required."
|
||||
---
|
||||
|
||||
The [`n8n-nodes-mem0`](https://www.npmjs.com/package/n8n-nodes-mem0) community node brings [Mem0](https://mem0.ai) memory to [n8n](https://n8n.io). Add, search, and manage long-term memories inside any workflow, and use it as a tool for the n8n AI Agent.
|
||||
|
||||
## Overview
|
||||
|
||||
The node wraps the hosted Mem0 REST API and supports six operations on the **Memory** resource:
|
||||
|
||||
| Operation | Endpoint |
|
||||
| --- | --- |
|
||||
| **Add** | `POST /v3/memories/add/` |
|
||||
| **Search** | `POST /v3/memories/search/` |
|
||||
| **Get** | `GET /v1/memories/{id}/` |
|
||||
| **Get Many** | `POST /v3/memories/` |
|
||||
| **Update** | `PUT /v1/memories/{id}/` |
|
||||
| **Delete** | `DELETE /v1/memories/{id}/` |
|
||||
|
||||
It is marked `usableAsTool`, so the n8n AI Agent (Tools Agent) can call it directly to remember and recall information.
|
||||
|
||||
## Installation
|
||||
|
||||
Install it like any n8n community node:
|
||||
|
||||
1. In n8n, go to **Settings → Community Nodes → Install**.
|
||||
2. Enter `n8n-nodes-mem0` and confirm.
|
||||
|
||||
The node then appears in the nodes panel under the AI category.
|
||||
|
||||
## Authentication
|
||||
|
||||
Create a **Mem0 API** credential in n8n:
|
||||
|
||||
- **API Key**: from the <a href="https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=integration-n8n" rel="nofollow">Mem0 API Key dashboard</a>. Sent as `Authorization: Token <key>`.
|
||||
- **Base URL**: defaults to `https://api.mem0.ai`.
|
||||
|
||||
## Operations
|
||||
|
||||
### Add
|
||||
|
||||
Extracts and stores memories from one or more messages. Provide at least one entity id (**User ID**, **Agent ID**, **Run ID**, or **App ID** in Additional Fields); the node validates this before calling the API. Additional Fields also expose **Metadata (JSON)** and **Infer** (run LLM extraction, or store verbatim).
|
||||
|
||||
Extraction is asynchronous. **Wait for Completion** (on by default) polls the event until it finishes and returns the resulting memories; turn it off to return immediately with the event ID.
|
||||
|
||||
### Search
|
||||
|
||||
Semantic search over stored memories. Provide a **Query**, a **User ID** (required, the API needs an entity filter), and an optional **Limit**.
|
||||
|
||||
### Get Many
|
||||
|
||||
Lists memories for a **User ID** with **Page** and **Page Size** controls.
|
||||
|
||||
### Get / Update / Delete
|
||||
|
||||
Operate on a single memory by **Memory ID**. Update accepts new **Text** and/or **Metadata (JSON)**.
|
||||
|
||||
## Choosing a `userId`
|
||||
|
||||
The `userId` is a stable string you choose to identify whose memories these are. It is not looked up in the dashboard. Common choices are your app's internal user ID, an email, or a UUID. Use the same value across Add, Search, and Get Many so recall works.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Zapier Integration" icon="bolt" href="/integrations/zapier">
|
||||
Add memory to Zaps across thousands of apps
|
||||
</Card>
|
||||
<Card title="Flowise Integration" icon="blocks" href="/integrations/flowise">
|
||||
Add memory to Flowise chatflows
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Snippet file="star-on-github.mdx" />
|
||||
@@ -1,61 +0,0 @@
|
||||
---
|
||||
title: Zapier
|
||||
description: "Add, search, and manage Mem0 memories from any Zap using the Mem0 Zapier app, no code required."
|
||||
---
|
||||
|
||||
The [Mem0](https://mem0.ai) Zapier app lets you add, search, list, and delete long-term memories from any [Zapier](https://zapier.com) workflow. Wire "remember" and "recall" into thousands of apps without writing code.
|
||||
|
||||
## Overview
|
||||
|
||||
The app wraps the hosted Mem0 REST API and exposes four actions:
|
||||
|
||||
| Type | Action | Endpoint |
|
||||
| --- | --- | --- |
|
||||
| Create | **Add Memory** | `POST /v3/memories/add/` |
|
||||
| Create | **Delete Memory** | `DELETE /v1/memories/{id}/` |
|
||||
| Search | **Search Memories** | `POST /v3/memories/search/` |
|
||||
| Search | **Get Memories** | `POST /v3/memories/` |
|
||||
|
||||
## Authentication
|
||||
|
||||
The app uses API key authentication. Grab a key from the <a href="https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=integration-zapier" rel="nofollow">Mem0 API Key dashboard</a> and paste it when connecting your Mem0 account in Zapier. The key is sent as `Authorization: Token <key>` on every request.
|
||||
|
||||
## Actions
|
||||
|
||||
### Add Memory
|
||||
|
||||
Extracts and stores memories from a message. Fields:
|
||||
|
||||
- **Content** (required): the message text to extract memories from.
|
||||
- **Role**: `user`, `assistant`, or `system`.
|
||||
- **User ID / Agent ID / Run ID**: entity the memory belongs to.
|
||||
- **Metadata (JSON)**: optional structured metadata.
|
||||
- **Infer**: run LLM extraction (default) or store the message verbatim.
|
||||
- **Wait for Completion**: off by default. Extraction is asynchronous, so the action returns immediately with an event ID. Turn this on to poll until extraction finishes and return the resulting memories. Extraction can take longer than a single Zapier step is allowed to run, so a timeout here does not mean the add failed; it usually still completes on the server.
|
||||
|
||||
### Search Memories
|
||||
|
||||
Semantic search over stored memories. Provide a **Query**, a **User ID** (required, the API needs an entity filter), and an optional **Limit**.
|
||||
|
||||
### Get Memories
|
||||
|
||||
Lists stored memories for a user. Provide a **User ID** (required), a **Limit** (page size), and a **Page** (1-based) to page through larger result sets.
|
||||
|
||||
### Delete Memory
|
||||
|
||||
Deletes a single memory by its **Memory ID**.
|
||||
|
||||
## Choosing a `userId`
|
||||
|
||||
The `user_id` is a stable string you choose to identify whose memories these are. It is not looked up in the dashboard. Common choices are your app's internal user ID, an email, or a UUID. Use the same value across Add, Search, and Get so recall works.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="n8n Integration" icon="diagram-project" href="/integrations/n8n">
|
||||
Build workflows with the Mem0 n8n community node
|
||||
</Card>
|
||||
<Card title="Flowise Integration" icon="blocks" href="/integrations/flowise">
|
||||
Add memory to Flowise chatflows
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Snippet file="star-on-github.mdx" />
|
||||
@@ -281,8 +281,6 @@ If the user is on a pre-current major (Python < 2, TS < 3, or Platform `output_f
|
||||
### Developer Tools
|
||||
- [Dify](https://docs.mem0.ai/integrations/dify) [Both]: Use when the user is on Dify LLMOps.
|
||||
- [Flowise](https://docs.mem0.ai/integrations/flowise) [Both]: Use when the user is on Flowise no-code.
|
||||
- [n8n](https://docs.mem0.ai/integrations/n8n) [Both]: Use when the user builds workflows or AI agents in n8n.
|
||||
- [Zapier](https://docs.mem0.ai/integrations/zapier) [Both]: Use when the user automates workflows with Zapier.
|
||||
- [AgentOps](https://docs.mem0.ai/integrations/agentops) [Both]: Use when tracking agent observability with memory metadata.
|
||||
- [Respan](https://docs.mem0.ai/integrations/respan) [Both]: Use when monitoring Mem0 with Respan (formerly Keywords AI) LLM observability.
|
||||
- [Raycast](https://docs.mem0.ai/integrations/raycast) [Both]: Use when the user wants quick memory access via Raycast.
|
||||
|
||||
@@ -148,7 +148,7 @@ See the full catalog in <Link href="/components/llms/overview">Components</Link>
|
||||
- Qdrant connection errors: confirm port `6333` is exposed and the API key (if set) matches.
|
||||
- Empty search results: verify the embedder model name. A mismatch causes dimension errors.
|
||||
- `Unknown reranker` (Python): upgrade the SDK with `pip install --upgrade mem0ai` to load the latest provider registry.
|
||||
- `Cannot find module` (Node): import from the OSS entry point, `import { Memory } from "mem0ai/oss"`, not `"mem0ai"`.
|
||||
- `Cannot find module` (Node): two common causes. First, import from the OSS entry point, `import { Memory } from "mem0ai/oss"`, not `"mem0ai"`. Second, provider SDKs are optional peer dependencies loaded on demand, so install the one for the provider you configured (for example `npm install @qdrant/js-client-rest` for Qdrant). Installing `mem0ai` alone only pulls in the providers used by default; you do not need SDKs for providers you never select.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import {afterEach, describe, expect, test} from "bun:test";
|
||||
import {mkdtempSync, mkdirSync, writeFileSync} from "fs";
|
||||
import {tmpdir} from "os";
|
||||
import {join} from "path";
|
||||
import {parseApiKeyLine, resolveApiKey} from "./api-key";
|
||||
import Mem0Plugin from "./opencode-mem0";
|
||||
|
||||
const originalKey = process.env.MEM0_API_KEY;
|
||||
const originalHome = process.env.HOME;
|
||||
const originalUserProfile = process.env.USERPROFILE;
|
||||
const originalTelemetry = process.env.MEM0_TELEMETRY;
|
||||
const originalFetch = globalThis.fetch;
|
||||
const testCleanups: Array<() => Promise<void> | void> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (testCleanups.length > 0) {
|
||||
await testCleanups.pop()?.();
|
||||
}
|
||||
if (originalKey === undefined) delete process.env.MEM0_API_KEY;
|
||||
else process.env.MEM0_API_KEY = originalKey;
|
||||
if (originalHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = originalHome;
|
||||
if (originalUserProfile === undefined) delete process.env.USERPROFILE;
|
||||
else process.env.USERPROFILE = originalUserProfile;
|
||||
if (originalTelemetry === undefined) delete process.env.MEM0_TELEMETRY;
|
||||
else process.env.MEM0_TELEMETRY = originalTelemetry;
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
function home(): string {
|
||||
return mkdtempSync(join(tmpdir(), "mem0-api-key-"));
|
||||
}
|
||||
|
||||
function pluginContext(logs: unknown[]) {
|
||||
return {
|
||||
client: {app: {log: async (entry: unknown) => logs.push(entry)}},
|
||||
$: () => ({quiet: async () => ({stdout: ""})}),
|
||||
} as any;
|
||||
}
|
||||
|
||||
function stubFetch(): void {
|
||||
globalThis.fetch = (async (input) => {
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
const body =
|
||||
url.includes("/v1/ping/")
|
||||
? {status: "ok", userEmail: "plugin-test@mem0.dev"}
|
||||
: url.includes("/v1/projects/")
|
||||
? {customCategories: []}
|
||||
: {};
|
||||
return new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: {"content-type": "application/json"},
|
||||
});
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
function captureDeferredPluginCleanup(): () => Promise<void> {
|
||||
const baseline = new Set(process.listeners("beforeExit"));
|
||||
return async () => {
|
||||
await Promise.resolve();
|
||||
for (const listener of process.listeners("beforeExit")) {
|
||||
if (!baseline.has(listener)) {
|
||||
process.off("beforeExit", listener as (...args: any[]) => void);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe("parseApiKeyLine", () => {
|
||||
test("accepts literal export and assignment forms", () => {
|
||||
expect(parseApiKeyLine('export MEM0_API_KEY="m0-quoted" # comment')).toBe("m0-quoted");
|
||||
expect(parseApiKeyLine("MEM0_API_KEY=m0-literal")).toBe("m0-literal");
|
||||
});
|
||||
|
||||
test("rejects unrelated, empty, and executable-looking values", () => {
|
||||
expect(parseApiKeyLine("OTHER_KEY=value")).toBeUndefined();
|
||||
expect(parseApiKeyLine("MEM0_API_KEY=")).toBeUndefined();
|
||||
expect(parseApiKeyLine("MEM0_API_KEY=$MEM0_API_KEY")).toBeUndefined();
|
||||
expect(parseApiKeyLine("MEM0_API_KEY=$(cat secret)")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveApiKey", () => {
|
||||
test("explicit environment value wins over profiles", () => {
|
||||
const dir = home();
|
||||
writeFileSync(join(dir, ".zshrc"), "MEM0_API_KEY=profile\n");
|
||||
expect(resolveApiKey({MEM0_API_KEY: " explicit "}, dir)).toBe("explicit");
|
||||
});
|
||||
|
||||
test("uses the first valid allowlisted profile", () => {
|
||||
const dir = home();
|
||||
writeFileSync(join(dir, ".zshrc"), "MEM0_API_KEY=$UNSET\n");
|
||||
writeFileSync(join(dir, ".bashrc"), "export MEM0_API_KEY='m0-from-bashrc'\n");
|
||||
writeFileSync(join(dir, ".profile"), "MEM0_API_KEY=late\n");
|
||||
expect(resolveApiKey({}, dir)).toBe("m0-from-bashrc");
|
||||
});
|
||||
|
||||
test("continues after an unreadable or absent earlier profile", () => {
|
||||
const dir = home();
|
||||
mkdirSync(join(dir, ".zshrc"));
|
||||
writeFileSync(join(dir, ".profile"), "MEM0_API_KEY=m0-later\n");
|
||||
expect(resolveApiKey({}, dir)).toBe("m0-later");
|
||||
});
|
||||
|
||||
test("ignores unsupported files and invalid assignments", () => {
|
||||
const dir = home();
|
||||
writeFileSync(join(dir, ".env"), "MEM0_API_KEY=unsupported\n");
|
||||
writeFileSync(join(dir, ".zshrc"), "MEM0_API_KEY= # empty\nMEM0_API_KEY=$(unsafe)\n");
|
||||
expect(resolveApiKey({}, dir)).toBe("");
|
||||
});
|
||||
|
||||
test("keeps the missing-key guard when no source yields a key", async () => {
|
||||
const dir = home();
|
||||
writeFileSync(join(dir, ".zshrc"), "MEM0_API_KEY= # empty\nMEM0_API_KEY=$UNSET\n");
|
||||
delete process.env.MEM0_API_KEY;
|
||||
process.env.HOME = dir;
|
||||
process.env.USERPROFILE = dir;
|
||||
process.env.MEM0_TELEMETRY = "false";
|
||||
stubFetch();
|
||||
testCleanups.push(captureDeferredPluginCleanup());
|
||||
|
||||
const logs: unknown[] = [];
|
||||
const plugin = await Mem0Plugin(pluginContext(logs));
|
||||
|
||||
expect(logs).toHaveLength(1);
|
||||
expect(logs[0]).toMatchObject({
|
||||
body: {
|
||||
level: "error",
|
||||
message: "MEM0_API_KEY environment variable not set. Get one at https://app.mem0.ai/dashboard/api-keys",
|
||||
},
|
||||
});
|
||||
expect(plugin).toEqual({});
|
||||
});
|
||||
|
||||
test("recovers the issue's shell-profile startup path", async () => {
|
||||
const dir = home();
|
||||
// Problem 2 in issue #6003: Desktop has no process key, but .zshrc does.
|
||||
writeFileSync(join(dir, ".zshrc"), 'export MEM0_API_KEY="m0-from-profile"\n');
|
||||
delete process.env.MEM0_API_KEY;
|
||||
process.env.HOME = dir;
|
||||
process.env.USERPROFILE = dir;
|
||||
process.env.MEM0_TELEMETRY = "false";
|
||||
stubFetch();
|
||||
testCleanups.push(captureDeferredPluginCleanup());
|
||||
|
||||
const logs: unknown[] = [];
|
||||
const plugin = await Mem0Plugin(pluginContext(logs));
|
||||
|
||||
expect(logs).toHaveLength(0);
|
||||
expect(Object.keys(plugin)).toContain("chat.message");
|
||||
expect(plugin).toHaveProperty("tool");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import {readFileSync} from "fs";
|
||||
import {homedir} from "os";
|
||||
import {join} from "path";
|
||||
|
||||
const PROFILE_FILES = [".zshrc", ".bashrc", ".zprofile", ".bash_profile", ".profile"];
|
||||
|
||||
export function parseApiKeyLine(line: string): string | undefined {
|
||||
const match = line.match(/^\s*(?:export\s+)?MEM0_API_KEY=(.*)$/);
|
||||
if (!match) return undefined;
|
||||
|
||||
const value = match[1].replace(/#.*$/, "").trim().replace(/^("|')(.*)\1$/, "$2").trim();
|
||||
return value && !value.startsWith("$") ? value : undefined;
|
||||
}
|
||||
|
||||
export function resolveApiKey(env: NodeJS.ProcessEnv = process.env, homeDir = homedir()): string {
|
||||
const explicit = env.MEM0_API_KEY?.trim();
|
||||
if (explicit) return explicit;
|
||||
|
||||
for (const profile of PROFILE_FILES) {
|
||||
try {
|
||||
for (const line of readFileSync(join(homeDir, profile), "utf8").split(/\r?\n/)) {
|
||||
const key = parseApiKeyLine(line);
|
||||
if (key) return key;
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from "./dream";
|
||||
import {asScope, scopeSearchFilters, scopeWriteParams, resolveDefaultScope, SCOPE_GUIDANCE, type Scope} from "./scope";
|
||||
import {parseProjectFromRemote} from "./project";
|
||||
import {resolveApiKey} from "./api-key";
|
||||
|
||||
async function getUserId(): Promise<string> {
|
||||
if (process.env.MEM0_USER_ID) return process.env.MEM0_USER_ID;
|
||||
@@ -258,7 +259,7 @@ function extractUserText(input: any, output: any): string {
|
||||
const Mem0Plugin: Plugin = async (ctx) => {
|
||||
const {$, client} = ctx;
|
||||
|
||||
const apiKey = process.env.MEM0_API_KEY;
|
||||
const apiKey = resolveApiKey();
|
||||
|
||||
if (!apiKey) {
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@mem0/opencode-plugin",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.2",
|
||||
"type": "module",
|
||||
"description": "Mem0 persistent memory plugin for OpenCode — add, search, and manage memories across sessions",
|
||||
"main": "dist/index.js",
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
env: { browser: true, es6: true, node: true },
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: { sourceType: 'module', extraFileExtensions: ['.json'] },
|
||||
ignorePatterns: ['.eslintrc.js', '**/*.js', '**/node_modules/**', '**/dist/**'],
|
||||
overrides: [
|
||||
{
|
||||
files: ['package.json'],
|
||||
plugins: ['eslint-plugin-n8n-nodes-base'],
|
||||
extends: ['plugin:n8n-nodes-base/community'],
|
||||
rules: { 'n8n-nodes-base/community-package-json-name-still-default': 'off' },
|
||||
},
|
||||
{
|
||||
files: ['./credentials/**/*.ts'],
|
||||
plugins: ['eslint-plugin-n8n-nodes-base'],
|
||||
extends: ['plugin:n8n-nodes-base/credentials'],
|
||||
rules: {
|
||||
// This rule only applies to nodes in n8n's main repository (where
|
||||
// documentationUrl is an internal docs slug). Community nodes use a
|
||||
// full external URL, so it is disabled here.
|
||||
'n8n-nodes-base/cred-class-field-documentation-url-miscased': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['./nodes/**/*.ts'],
|
||||
plugins: ['eslint-plugin-n8n-nodes-base'],
|
||||
extends: ['plugin:n8n-nodes-base/nodes'],
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -1,8 +0,0 @@
|
||||
node_modules/
|
||||
dist/
|
||||
package-lock.json
|
||||
*.tsbuildinfo
|
||||
.env
|
||||
coverage/
|
||||
*.log
|
||||
.DS_Store
|
||||
@@ -1,9 +0,0 @@
|
||||
module.exports = {
|
||||
semi: true,
|
||||
trailingComma: 'all',
|
||||
bracketSpacing: true,
|
||||
useTabs: true,
|
||||
tabWidth: 2,
|
||||
printWidth: 100,
|
||||
singleQuote: true,
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Mem0
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,54 +0,0 @@
|
||||
# n8n-nodes-mem0
|
||||
|
||||
This is an n8n community node that lets you use [Mem0](https://mem0.ai) — the memory layer for AI agents — in your n8n workflows.
|
||||
|
||||
Mem0 gives your agents long-term memory: add memories from conversations, then search and recall them across sessions.
|
||||
|
||||
[n8n](https://n8n.io) is a [fair-code licensed](https://docs.n8n.io/reference/license/) workflow automation platform.
|
||||
|
||||
[Installation](#installation) · [Operations](#operations) · [Credentials](#credentials) · [Usage](#usage) · [Resources](#resources)
|
||||
|
||||
## Installation
|
||||
|
||||
Follow the [community nodes installation guide](https://docs.n8n.io/integrations/community-nodes/installation/) and install `n8n-nodes-mem0`.
|
||||
|
||||
## Operations
|
||||
|
||||
The **Memory** resource supports:
|
||||
|
||||
| Operation | Description | Endpoint |
|
||||
| --- | --- | --- |
|
||||
| **Add** | Extract and store memories from messages | `POST /v3/memories/add/` |
|
||||
| **Search** | Semantic search over stored memories | `POST /v3/memories/search/` |
|
||||
| **Get Many** | List memories for a user (paginated) | `POST /v3/memories/` |
|
||||
| **Get** | Retrieve a single memory by ID | `GET /v1/memories/{id}/` |
|
||||
| **Update** | Update a memory's text or metadata | `PUT /v1/memories/{id}/` |
|
||||
| **Delete** | Delete a single memory by ID | `DELETE /v1/memories/{id}/` |
|
||||
|
||||
### Add & asynchronous extraction
|
||||
|
||||
By default, **Add** runs LLM-based extraction asynchronously — the API returns an event ID and the node polls until extraction finishes, then returns the resulting memories. Disable **Wait for Completion** to return immediately with the event ID, or set **Infer = false** (under Additional Fields) to store messages verbatim and return synchronously.
|
||||
|
||||
## Credentials
|
||||
|
||||
You need a Mem0 API key. Create one at [app.mem0.ai](https://app.mem0.ai) → Settings → API Keys. The key is sent as `Authorization: Token <key>`.
|
||||
|
||||
## Usage
|
||||
|
||||
This node is also **usable as a tool** by n8n's AI Agent node — attach it so an agent can "remember" and "recall" autonomously.
|
||||
|
||||
A typical loop:
|
||||
|
||||
1. **Search** memory before answering, filtered by `User ID`.
|
||||
2. **Add** durable facts after a meaningful exchange.
|
||||
|
||||
Memory writes are asynchronous by default; allow a moment after an Add before searching for the same content.
|
||||
|
||||
## Resources
|
||||
|
||||
- [Mem0 documentation](https://docs.mem0.ai)
|
||||
- [n8n community nodes documentation](https://docs.n8n.io/integrations/community-nodes/)
|
||||
|
||||
## License
|
||||
|
||||
[MIT](./LICENSE)
|
||||
@@ -1,53 +0,0 @@
|
||||
import {
|
||||
IAuthenticateGeneric,
|
||||
ICredentialTestRequest,
|
||||
ICredentialType,
|
||||
INodeProperties,
|
||||
} from 'n8n-workflow';
|
||||
|
||||
export class Mem0Api implements ICredentialType {
|
||||
name = 'mem0Api';
|
||||
|
||||
displayName = 'Mem0 API';
|
||||
|
||||
documentationUrl = 'https://docs.mem0.ai/platform/quickstart';
|
||||
|
||||
properties: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'API Key',
|
||||
name: 'apiKey',
|
||||
type: 'string',
|
||||
typeOptions: { password: true },
|
||||
default: '',
|
||||
required: true,
|
||||
description: 'Your Mem0 API key (starts with "m0-"). Create one at app.mem0.ai → Settings → API Keys.',
|
||||
},
|
||||
{
|
||||
displayName: 'Base URL',
|
||||
name: 'baseUrl',
|
||||
type: 'string',
|
||||
default: 'https://api.mem0.ai',
|
||||
description: 'Mem0 API base URL. Override only for self-hosted or non-default deployments.',
|
||||
},
|
||||
];
|
||||
|
||||
// Injects "Authorization: Token <apiKey>" on every request, matching the
|
||||
// scheme used by Mem0's official SDKs (Authorization: Token m0-...).
|
||||
authenticate: IAuthenticateGeneric = {
|
||||
type: 'generic',
|
||||
properties: {
|
||||
headers: {
|
||||
Authorization: '=Token {{$credentials.apiKey}}',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Cheap authenticated GET; validates the key when the user clicks "Test".
|
||||
test: ICredentialTestRequest = {
|
||||
request: {
|
||||
baseURL: '={{$credentials.baseUrl}}',
|
||||
url: '/v1/ping/',
|
||||
method: 'GET',
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
const path = require('path');
|
||||
const { task, src, dest } = require('gulp');
|
||||
|
||||
task('build:icons', copyIcons);
|
||||
|
||||
function copyIcons() {
|
||||
// Copy icons and the codex (*.node.json) next to the compiled nodes; tsc emits
|
||||
// only .js, so these static assets need copying for n8n to pick them up.
|
||||
const nodeSource = path.resolve('nodes', '**', '*.{png,svg,json}');
|
||||
const nodeDestination = path.resolve('dist', 'nodes');
|
||||
src(nodeSource).pipe(dest(nodeDestination));
|
||||
|
||||
const credSource = path.resolve('credentials', '**', '*.{png,svg}');
|
||||
const credDestination = path.resolve('dist', 'credentials');
|
||||
return src(credSource, { allowEmpty: true }).pipe(dest(credDestination));
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
// n8n loads nodes and credentials via the "n8n" key in package.json.
|
||||
// This entry point is intentionally empty.
|
||||
module.exports = {};
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"node": "n8n-nodes-mem0.mem0",
|
||||
"nodeVersion": "1.0",
|
||||
"codexVersion": "1.0",
|
||||
"categories": ["AI"],
|
||||
"subcategories": {
|
||||
"AI": ["Memory"]
|
||||
},
|
||||
"resources": {
|
||||
"primaryDocumentation": [
|
||||
{
|
||||
"url": "https://docs.mem0.ai/integrations/n8n"
|
||||
}
|
||||
],
|
||||
"credentialDocumentation": [
|
||||
{
|
||||
"url": "https://docs.mem0.ai/integrations/n8n"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,463 +0,0 @@
|
||||
import {
|
||||
IExecuteFunctions,
|
||||
IDataObject,
|
||||
IHttpRequestMethods,
|
||||
IHttpRequestOptions,
|
||||
INodeExecutionData,
|
||||
INodeType,
|
||||
INodeTypeDescription,
|
||||
JsonObject,
|
||||
NodeApiError,
|
||||
NodeOperationError,
|
||||
sleep,
|
||||
} from 'n8n-workflow';
|
||||
|
||||
// Poll settings for asynchronous (infer=true) memory addition.
|
||||
const POLL_INTERVAL_MS = 1500;
|
||||
const MAX_POLL_ATTEMPTS = 40; // ~60s ceiling
|
||||
|
||||
export class Mem0 implements INodeType {
|
||||
description: INodeTypeDescription = {
|
||||
displayName: 'Mem0',
|
||||
name: 'mem0',
|
||||
icon: 'file:mem0.svg',
|
||||
group: ['transform'],
|
||||
version: 1,
|
||||
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
|
||||
description: 'Add, search, and manage long-term memories with Mem0',
|
||||
defaults: {
|
||||
name: 'Mem0',
|
||||
},
|
||||
// Makes the node available to the AI Agent (Tools Agent) node.
|
||||
usableAsTool: true,
|
||||
inputs: ['main'],
|
||||
outputs: ['main'],
|
||||
credentials: [
|
||||
{
|
||||
name: 'mem0Api',
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
properties: [
|
||||
{
|
||||
displayName: 'Resource',
|
||||
name: 'resource',
|
||||
type: 'options',
|
||||
noDataExpression: true,
|
||||
options: [{ name: 'Memory', value: 'memory' }],
|
||||
default: 'memory',
|
||||
},
|
||||
{
|
||||
displayName: 'Operation',
|
||||
name: 'operation',
|
||||
type: 'options',
|
||||
noDataExpression: true,
|
||||
displayOptions: { show: { resource: ['memory'] } },
|
||||
options: [
|
||||
{
|
||||
name: 'Add',
|
||||
value: 'add',
|
||||
action: 'Add a memory',
|
||||
description: 'Extract and store memories from messages',
|
||||
},
|
||||
{
|
||||
name: 'Delete',
|
||||
value: 'delete',
|
||||
action: 'Delete a memory',
|
||||
description: 'Delete a single memory by ID',
|
||||
},
|
||||
{
|
||||
name: 'Get',
|
||||
value: 'get',
|
||||
action: 'Get a memory',
|
||||
description: 'Retrieve a single memory by ID',
|
||||
},
|
||||
{
|
||||
name: 'Get Many',
|
||||
value: 'getAll',
|
||||
action: 'Get many memories',
|
||||
description: 'List stored memories for an entity',
|
||||
},
|
||||
{
|
||||
name: 'Search',
|
||||
value: 'search',
|
||||
action: 'Search memories',
|
||||
description: 'Semantic search over stored memories',
|
||||
},
|
||||
{
|
||||
name: 'Update',
|
||||
value: 'update',
|
||||
action: 'Update a memory',
|
||||
description: 'Update the text or metadata of a memory',
|
||||
},
|
||||
],
|
||||
default: 'add',
|
||||
},
|
||||
|
||||
// ---- Add ---------------------------------------------------------
|
||||
{
|
||||
displayName: 'Messages',
|
||||
name: 'messages',
|
||||
placeholder: 'Add Message',
|
||||
type: 'fixedCollection',
|
||||
typeOptions: { multipleValues: true },
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['add'] } },
|
||||
default: {},
|
||||
description: 'The conversation messages to extract memories from',
|
||||
options: [
|
||||
{
|
||||
name: 'message',
|
||||
displayName: 'Message',
|
||||
values: [
|
||||
{
|
||||
displayName: 'Role',
|
||||
name: 'role',
|
||||
type: 'options',
|
||||
options: [
|
||||
{ name: 'User', value: 'user' },
|
||||
{ name: 'Assistant', value: 'assistant' },
|
||||
{ name: 'System', value: 'system' },
|
||||
],
|
||||
default: 'user',
|
||||
},
|
||||
{
|
||||
displayName: 'Content',
|
||||
name: 'content',
|
||||
type: 'string',
|
||||
typeOptions: { rows: 2 },
|
||||
default: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
displayName: 'User ID',
|
||||
name: 'userId',
|
||||
type: 'string',
|
||||
default: '',
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['add'] } },
|
||||
description: 'Associate the memories with this user',
|
||||
},
|
||||
{
|
||||
displayName: 'Wait for Completion',
|
||||
name: 'waitForCompletion',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['add'] } },
|
||||
description:
|
||||
'Whether to poll until memory extraction finishes and return the resulting memories. Turn off to return immediately with the event ID.',
|
||||
},
|
||||
{
|
||||
displayName: 'Additional Fields',
|
||||
name: 'addFields',
|
||||
type: 'collection',
|
||||
placeholder: 'Add Field',
|
||||
default: {},
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['add'] } },
|
||||
options: [
|
||||
{
|
||||
displayName: 'Agent ID',
|
||||
name: 'agent_id',
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'App ID',
|
||||
name: 'app_id',
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'Infer',
|
||||
name: 'infer',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
description:
|
||||
'Whether to run LLM extraction over the messages. Turn off to store them verbatim. ' +
|
||||
'This controls extraction only — use "Wait for Completion" to control whether the node waits.',
|
||||
},
|
||||
{
|
||||
displayName: 'Metadata (JSON)',
|
||||
name: 'metadata',
|
||||
type: 'json',
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
displayName: 'Run ID',
|
||||
name: 'run_id',
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
// ---- Search ------------------------------------------------------
|
||||
{
|
||||
displayName: 'Query',
|
||||
name: 'query',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: true,
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['search'] } },
|
||||
description: 'What to recall from memory',
|
||||
},
|
||||
{
|
||||
displayName: 'User ID',
|
||||
name: 'userId',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: true,
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['search'] } },
|
||||
description: 'Restrict the search to this user (required — the API needs an entity filter)',
|
||||
},
|
||||
{
|
||||
displayName: 'Limit',
|
||||
name: 'limit',
|
||||
type: 'number',
|
||||
typeOptions: { minValue: 1 },
|
||||
default: 50,
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['search'] } },
|
||||
description: 'Max number of results to return',
|
||||
},
|
||||
|
||||
// ---- Get Many ----------------------------------------------------
|
||||
{
|
||||
displayName: 'User ID',
|
||||
name: 'userId',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: true,
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['getAll'] } },
|
||||
description: 'Restrict the listing to this user (required — the API needs an entity filter)',
|
||||
},
|
||||
{
|
||||
displayName: 'Page',
|
||||
name: 'page',
|
||||
type: 'number',
|
||||
typeOptions: { minValue: 1 },
|
||||
default: 1,
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['getAll'] } },
|
||||
},
|
||||
{
|
||||
displayName: 'Page Size',
|
||||
name: 'pageSize',
|
||||
type: 'number',
|
||||
typeOptions: { minValue: 1 },
|
||||
default: 50,
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['getAll'] } },
|
||||
},
|
||||
|
||||
// ---- Get / Update / Delete (by ID) -------------------------------
|
||||
{
|
||||
displayName: 'Memory ID',
|
||||
name: 'memoryId',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: true,
|
||||
displayOptions: {
|
||||
show: { resource: ['memory'], operation: ['get', 'update', 'delete'] },
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'Text',
|
||||
name: 'text',
|
||||
type: 'string',
|
||||
default: '',
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['update'] } },
|
||||
description: 'The new memory text',
|
||||
},
|
||||
{
|
||||
displayName: 'Metadata (JSON)',
|
||||
name: 'metadata',
|
||||
type: 'json',
|
||||
default: '',
|
||||
displayOptions: { show: { resource: ['memory'], operation: ['update'] } },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
|
||||
const items = this.getInputData();
|
||||
const returnData: INodeExecutionData[] = [];
|
||||
const baseUrl = ((await this.getCredentials('mem0Api')).baseUrl as string) || 'https://api.mem0.ai';
|
||||
|
||||
const request = async (
|
||||
method: IHttpRequestMethods,
|
||||
url: string,
|
||||
body?: IDataObject,
|
||||
qs?: IDataObject,
|
||||
): Promise<IDataObject> => {
|
||||
const options: IHttpRequestOptions = {
|
||||
method,
|
||||
url: `${baseUrl}${url}`,
|
||||
json: true,
|
||||
...(body ? { body } : {}),
|
||||
...(qs ? { qs } : {}),
|
||||
};
|
||||
return (await this.helpers.httpRequestWithAuthentication.call(
|
||||
this,
|
||||
'mem0Api',
|
||||
options,
|
||||
)) as IDataObject;
|
||||
};
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
try {
|
||||
const operation = this.getNodeParameter('operation', i) as string;
|
||||
let responseData: IDataObject | IDataObject[] = {};
|
||||
|
||||
if (operation === 'add') {
|
||||
const messagesUi = this.getNodeParameter('messages.message', i, []) as IDataObject[];
|
||||
if (!messagesUi.length) {
|
||||
throw new NodeOperationError(this.getNode(), 'At least one message is required', {
|
||||
itemIndex: i,
|
||||
});
|
||||
}
|
||||
const addFields = this.getNodeParameter('addFields', i, {}) as IDataObject;
|
||||
const body: IDataObject = {
|
||||
messages: messagesUi.map((m) => ({ role: m.role, content: m.content })),
|
||||
infer: addFields.infer !== undefined ? addFields.infer : true,
|
||||
};
|
||||
const userId = this.getNodeParameter('userId', i, '') as string;
|
||||
if (userId) body.user_id = userId;
|
||||
if (addFields.agent_id) body.agent_id = addFields.agent_id;
|
||||
if (addFields.app_id) body.app_id = addFields.app_id;
|
||||
if (addFields.run_id) body.run_id = addFields.run_id;
|
||||
if (addFields.metadata) {
|
||||
try {
|
||||
body.metadata =
|
||||
typeof addFields.metadata === 'string'
|
||||
? JSON.parse(addFields.metadata as string)
|
||||
: addFields.metadata;
|
||||
} catch {
|
||||
throw new NodeOperationError(this.getNode(), 'Invalid JSON in "Metadata" field', {
|
||||
itemIndex: i,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// API requires at least one entity id — fail clearly instead of a raw 4xx.
|
||||
if (!body.user_id && !body.agent_id && !body.run_id && !body.app_id) {
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
'Add requires at least one of User ID, Agent ID, Run ID, or App ID',
|
||||
{ itemIndex: i },
|
||||
);
|
||||
}
|
||||
|
||||
const addResp = await request('POST', '/v3/memories/add/', body);
|
||||
const waitForCompletion = this.getNodeParameter('waitForCompletion', i, true) as boolean;
|
||||
const addStatus = addResp.status as string | undefined;
|
||||
const isTerminal = addStatus === 'SUCCEEDED' || addStatus === 'FAILED';
|
||||
|
||||
// Add returns {event_id, status:PENDING|RUNNING}; poll until terminal when asked to wait.
|
||||
if (waitForCompletion && addResp.event_id && !isTerminal) {
|
||||
responseData = await pollEvent(request, addResp.event_id as string, this, i);
|
||||
} else if (addStatus === 'FAILED') {
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
`Mem0 memory add failed: ${(addResp.message as string) || 'unknown error'}`,
|
||||
{ itemIndex: i },
|
||||
);
|
||||
} else {
|
||||
// If the response is already terminal, unwrap results; otherwise return as-is.
|
||||
responseData = Array.isArray(addResp.results)
|
||||
? (addResp.results as IDataObject[])
|
||||
: addResp;
|
||||
}
|
||||
} else if (operation === 'search') {
|
||||
const body: IDataObject = {
|
||||
query: this.getNodeParameter('query', i) as string,
|
||||
output_format: 'v1.1',
|
||||
top_k: this.getNodeParameter('limit', i, 50) as number,
|
||||
};
|
||||
const userId = this.getNodeParameter('userId', i, '') as string;
|
||||
if (userId) body.filters = { user_id: userId };
|
||||
const resp = await request('POST', '/v3/memories/search/', body);
|
||||
responseData = Array.isArray(resp.results) ? (resp.results as IDataObject[]) : [];
|
||||
} else if (operation === 'getAll') {
|
||||
const userId = this.getNodeParameter('userId', i, '') as string;
|
||||
const page = this.getNodeParameter('page', i, 1) as number;
|
||||
const pageSize = this.getNodeParameter('pageSize', i, 50) as number;
|
||||
const body: IDataObject = {};
|
||||
if (userId) body.filters = { user_id: userId };
|
||||
const resp = await request('POST', '/v3/memories/', body, { page, page_size: pageSize });
|
||||
responseData = Array.isArray(resp.results) ? (resp.results as IDataObject[]) : [];
|
||||
} else if (operation === 'get') {
|
||||
const memoryId = this.getNodeParameter('memoryId', i) as string;
|
||||
responseData = await request('GET', `/v1/memories/${memoryId}/`);
|
||||
} else if (operation === 'update') {
|
||||
const memoryId = this.getNodeParameter('memoryId', i) as string;
|
||||
const body: IDataObject = {};
|
||||
const text = this.getNodeParameter('text', i, '') as string;
|
||||
const metadata = this.getNodeParameter('metadata', i, '') as string;
|
||||
if (text) body.text = text;
|
||||
if (metadata) {
|
||||
try {
|
||||
body.metadata = typeof metadata === 'string' ? JSON.parse(metadata) : metadata;
|
||||
} catch {
|
||||
throw new NodeOperationError(this.getNode(), 'Invalid JSON in "Metadata" field', {
|
||||
itemIndex: i,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (Object.keys(body).length === 0) {
|
||||
throw new NodeOperationError(this.getNode(), 'Provide text or metadata to update', {
|
||||
itemIndex: i,
|
||||
});
|
||||
}
|
||||
responseData = await request('PUT', `/v1/memories/${memoryId}/`, body);
|
||||
} else if (operation === 'delete') {
|
||||
const memoryId = this.getNodeParameter('memoryId', i) as string;
|
||||
responseData = await request('DELETE', `/v1/memories/${memoryId}/`);
|
||||
}
|
||||
|
||||
const arr = Array.isArray(responseData) ? responseData : [responseData];
|
||||
for (const entry of arr) {
|
||||
returnData.push({ json: entry, pairedItem: { item: i } });
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.continueOnFail()) {
|
||||
returnData.push({ json: { error: (error as Error).message }, pairedItem: { item: i } });
|
||||
continue;
|
||||
}
|
||||
if (error instanceof NodeApiError || error instanceof NodeOperationError) throw error;
|
||||
throw new NodeApiError(this.getNode(), error as JsonObject);
|
||||
}
|
||||
}
|
||||
|
||||
return [returnData];
|
||||
}
|
||||
}
|
||||
|
||||
// Polls GET /v1/event/{id}/ until the memory-addition event resolves.
|
||||
async function pollEvent(
|
||||
request: (m: IHttpRequestMethods, u: string) => Promise<IDataObject>,
|
||||
eventId: string,
|
||||
ctx: IExecuteFunctions,
|
||||
itemIndex: number,
|
||||
): Promise<IDataObject | IDataObject[]> {
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
|
||||
const event = await request('GET', `/v1/event/${eventId}/`);
|
||||
const status = event.status as string;
|
||||
if (status === 'SUCCEEDED') {
|
||||
// Match the shape of search/getAll (a clean array); fall back to the envelope.
|
||||
return Array.isArray(event.results) ? (event.results as IDataObject[]) : event;
|
||||
}
|
||||
if (status === 'FAILED') {
|
||||
const reason = (event.error as string) || (event.message as string) || 'unknown error';
|
||||
throw new NodeOperationError(
|
||||
ctx.getNode(),
|
||||
`Mem0 memory event ${eventId} failed: ${reason}`,
|
||||
{ itemIndex },
|
||||
);
|
||||
}
|
||||
await sleep(POLL_INTERVAL_MS);
|
||||
}
|
||||
throw new NodeOperationError(
|
||||
ctx.getNode(),
|
||||
`Timed out waiting for memory event ${eventId} to complete`,
|
||||
{ itemIndex },
|
||||
);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
<svg width="307" height="307" viewBox="0 0 307 307" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M162.496 25.3505C165.003 25.3505 167.453 24.6071 169.538 23.2144C171.622 21.8216 173.247 19.8419 174.206 17.5258C175.165 15.2097 175.416 12.6612 174.927 10.2024C174.438 7.74365 173.231 5.48516 171.458 3.71249C169.686 1.93983 167.427 0.73263 164.968 0.243552C162.51 -0.245525 159.961 0.00550576 157.645 0.964866C155.329 1.92423 153.349 3.54885 151.956 5.63328C150.564 7.71772 149.82 10.1683 149.82 12.6753C149.818 14.3404 150.145 15.9895 150.781 17.5283C151.417 19.0671 152.351 20.4653 153.528 21.6427C154.706 22.8201 156.104 23.7537 157.643 24.39C159.181 25.0262 160.83 25.3526 162.496 25.3505Z" fill="white"/>
|
||||
<path d="M69.3342 56.559C71.1066 54.7862 72.3135 52.5277 72.8024 50.069C73.2913 47.6103 73.0401 45.0619 72.0807 42.7459C71.1213 40.43 69.4967 38.4505 67.4123 37.0579C65.3279 35.6652 62.8774 34.9219 60.3706 34.9219C57.8637 34.9219 55.4132 35.6652 53.3288 37.0579C51.2444 38.4505 49.6198 40.43 48.6604 42.7459C47.701 45.0619 47.4498 47.6103 47.9387 50.069C48.4276 52.5277 49.6345 54.7862 51.4069 56.559C52.5839 57.7363 53.9813 58.6701 55.5193 59.3073C57.0573 59.9444 58.7058 60.2724 60.3706 60.2724C62.0353 60.2724 63.6838 59.9444 65.2218 59.3073C66.7598 58.6701 68.1572 57.7363 69.3342 56.559Z" fill="white"/>
|
||||
<path d="M25.3505 144.504C25.3505 141.997 24.6071 139.547 23.2143 137.462C21.8216 135.378 19.842 133.753 17.5259 132.794C15.2098 131.835 12.6612 131.584 10.2024 132.073C7.74368 132.562 5.48513 133.769 3.71247 135.542C1.9398 137.314 0.732655 139.573 0.243578 142.032C-0.2455 144.49 0.00543354 147.039 0.964793 149.355C1.92415 151.671 3.54877 153.651 5.63321 155.044C7.71764 156.436 10.1683 157.18 12.6752 157.18C16.0369 157.18 19.261 155.844 21.638 153.467C24.0151 151.09 25.3505 147.866 25.3505 144.504Z" fill="white"/>
|
||||
<path d="M56.5589 237.749C54.7862 235.976 52.5277 234.769 50.069 234.28C47.6103 233.792 45.0619 234.043 42.7459 235.002C40.43 235.962 38.4505 237.586 37.0579 239.671C35.6652 241.755 34.9219 244.206 34.9219 246.712C34.9219 249.219 35.6652 251.67 37.0579 253.754C38.4505 255.838 40.43 257.463 42.7459 258.423C45.0619 259.382 47.6103 259.633 50.069 259.144C52.5277 258.655 54.7862 257.448 56.5589 255.676C57.7362 254.499 58.6701 253.102 59.3073 251.564C59.9444 250.026 60.2724 248.377 60.2724 246.712C60.2724 245.048 59.9444 243.399 59.3073 241.861C58.6701 240.323 57.7362 238.926 56.5589 237.749Z" fill="white"/>
|
||||
<path d="M144.488 281.648C141.981 281.648 139.53 282.392 137.446 283.785C135.361 285.177 133.737 287.157 132.777 289.473C131.818 291.789 131.567 294.338 132.056 296.797C132.545 299.255 133.752 301.514 135.525 303.286C137.298 305.059 139.556 306.266 142.015 306.755C144.474 307.244 147.022 306.993 149.338 306.034C151.655 305.075 153.634 303.45 155.027 301.366C156.42 299.281 157.163 296.831 157.163 294.324C157.159 290.963 155.822 287.742 153.446 285.366C151.07 282.989 147.848 281.653 144.488 281.648Z" fill="white"/>
|
||||
<path d="M237.751 250.487C235.978 252.26 234.771 254.518 234.282 256.977C233.794 259.435 234.045 261.984 235.004 264.3C235.964 266.616 237.588 268.595 239.673 269.988C241.757 271.381 244.207 272.124 246.714 272.124C249.221 272.124 251.672 271.381 253.756 269.988C255.84 268.595 257.465 266.616 258.424 264.3C259.384 261.984 259.635 259.435 259.146 256.977C258.657 254.518 257.45 252.26 255.678 250.487C254.501 249.31 253.104 248.376 251.566 247.739C250.028 247.101 248.379 246.773 246.714 246.773C245.05 246.773 243.401 247.101 241.863 247.739C240.325 248.376 238.928 249.31 237.751 250.487Z" fill="white"/>
|
||||
<path d="M281.648 162.512C281.648 165.019 282.392 167.469 283.785 169.554C285.177 171.638 287.157 173.263 289.473 174.222C291.789 175.181 294.338 175.432 296.797 174.943C299.255 174.454 301.514 173.247 303.286 171.474C305.059 169.702 306.266 167.443 306.755 164.984C307.244 162.526 306.993 159.977 306.034 157.661C305.075 155.345 303.45 153.365 301.366 151.973C299.281 150.58 296.831 149.836 294.324 149.836C290.962 149.836 287.738 151.172 285.361 153.549C282.984 155.926 281.648 159.15 281.648 162.512Z" fill="white"/>
|
||||
<path d="M250.471 69.3303C252.244 71.1027 254.503 72.3097 256.961 72.7985C259.42 73.2874 261.968 73.0363 264.284 72.0768C266.6 71.1174 268.58 69.4928 269.972 67.4084C271.365 65.324 272.108 62.8735 272.108 60.3667C272.108 57.8599 271.365 55.4093 269.972 53.3249C268.58 51.2406 266.6 49.616 264.284 48.6565C261.968 47.6971 259.42 47.4459 256.961 47.9348C254.503 48.4236 252.244 49.6306 250.471 51.403C249.294 52.58 248.36 53.9775 247.723 55.5155C247.086 57.0535 246.758 58.7019 246.758 60.3667C246.758 62.0314 247.086 63.6799 247.723 65.2179C248.36 66.7559 249.294 68.1533 250.471 69.3303Z" fill="white"/>
|
||||
<path d="M184.782 60.8054C180.168 63.4713 178.3 69.0427 177.63 74.3267C177.047 78.9358 175.033 83.2457 171.87 86.6488C168.707 90.052 164.556 92.3766 160.002 93.2951C155.448 94.2136 150.721 93.6796 146.487 91.7683C142.252 89.857 138.724 86.6649 136.401 82.642C134.077 78.6192 133.075 73.9684 133.535 69.3455C133.995 64.7226 135.895 60.3607 138.966 56.8748C142.037 53.389 146.125 50.9549 150.653 49.9159C155.181 48.8768 159.921 49.2852 164.204 51.0834C169.121 53.1428 174.884 54.2762 179.514 51.6422C184.143 49.0082 185.995 43.4049 186.665 38.1208C187.245 33.5107 189.257 29.1987 192.418 25.7931C195.579 22.3876 199.73 20.0603 204.284 19.1394C208.838 18.2185 213.567 18.7505 217.803 20.6605C222.039 22.5704 225.568 25.7618 227.893 29.7846C230.218 33.8075 231.222 38.4587 230.763 43.0824C230.303 47.7062 228.404 52.0691 225.333 55.5559C222.262 59.0426 218.173 61.4773 213.645 62.5165C209.116 63.5557 204.375 63.147 200.091 61.3481C195.174 59.3048 189.411 58.1554 184.782 60.8054Z" fill="white"/>
|
||||
<path d="M110.073 65.8178C108.7 70.9742 111.318 76.2422 114.575 80.4567C117.417 84.1261 119.036 88.595 119.204 93.2335C119.372 97.872 118.08 102.446 115.51 106.311C112.941 110.177 109.223 113.138 104.881 114.778C100.538 116.419 95.7912 116.655 91.3077 115.454C86.8242 114.253 82.8306 111.675 79.8898 108.084C76.9489 104.493 75.2091 100.07 74.9155 95.4379C74.6219 90.8057 75.7894 86.1981 78.2533 82.2645C80.7173 78.331 84.3534 75.2698 88.6494 73.5124C93.5822 71.485 98.4991 68.2444 99.8241 63.0881C101.149 57.9317 98.579 52.6637 95.3224 48.4493C92.4827 44.7781 90.8665 40.3083 90.7018 35.6699C90.537 31.0315 91.8319 26.4583 94.4039 22.5949C96.976 18.7314 100.695 15.7724 105.038 14.1349C109.381 12.4974 114.128 12.2639 118.611 13.4673C123.094 14.6708 127.085 17.2505 130.024 20.8429C132.963 24.4354 134.7 28.8594 134.991 33.4916C135.283 38.1237 134.113 42.7305 131.647 46.6627C129.182 50.5948 125.544 53.6541 121.248 55.4095C116.363 57.4209 111.462 60.6775 110.073 65.8178Z" fill="white"/>
|
||||
<path d="M60.7892 122.218C63.4552 126.831 69.0425 128.699 74.3265 129.37C78.9361 129.955 83.2455 131.973 86.6471 135.138C90.0487 138.304 92.3707 142.457 93.2857 147.013C94.2006 151.569 93.6625 156.296 91.747 160.53C89.8314 164.763 86.6353 168.288 82.6093 170.608C78.5833 172.928 73.9305 173.926 69.3073 173.46C64.6841 172.995 60.3236 171.09 56.841 168.014C53.3583 164.938 50.9292 160.846 49.8962 156.316C48.8631 151.785 49.2783 147.045 51.0832 142.763C53.1426 137.846 54.2759 132.083 51.6419 127.454C49.0079 122.824 43.4046 120.973 38.1047 120.302C33.4951 119.717 29.1856 117.699 25.7841 114.533C22.3825 111.368 20.0604 107.214 19.1454 102.659C18.2304 98.1032 18.7687 93.3752 20.6842 89.1418C22.5997 84.9084 25.7959 81.3832 29.8219 79.0632C33.8479 76.7433 38.5006 75.7457 43.1238 76.2113C47.7471 76.6768 52.1075 78.582 55.5902 81.658C59.0728 84.7341 61.502 88.8258 62.535 93.3561C63.568 97.8865 63.1528 102.627 61.3479 106.908C59.2886 111.825 58.1552 117.588 60.7892 122.218Z" fill="white"/>
|
||||
<path d="M65.8204 196.93C70.9767 198.303 76.2287 195.685 80.4592 192.428C84.1286 189.586 88.5975 187.967 93.236 187.799C97.8745 187.631 102.449 188.923 106.314 191.493C110.179 194.062 113.141 197.78 114.781 202.122C116.421 206.464 116.657 211.212 115.457 215.695C114.256 220.179 111.678 224.172 108.087 227.113C104.496 230.054 100.073 231.794 95.4404 232.087C90.8082 232.381 86.2006 231.214 82.2671 228.75C78.3335 226.286 75.2723 222.649 73.5149 218.353C71.4875 213.421 68.231 208.504 63.0906 207.179C57.9503 205.854 52.6662 208.424 48.4518 211.681C44.7804 214.528 40.308 216.151 35.6652 216.32C31.0224 216.49 26.4435 215.199 22.5738 212.628C18.7042 210.057 15.7391 206.336 14.0968 201.99C12.4544 197.644 12.2176 192.892 13.4197 188.404C14.6218 183.917 17.2021 179.919 20.7969 176.976C24.3917 174.033 28.8195 172.293 33.4562 172C38.0929 171.708 42.7045 172.878 46.6407 175.345C50.577 177.813 53.6394 181.454 55.3961 185.755C57.4235 190.656 60.6641 195.541 65.8204 196.93Z" fill="white"/>
|
||||
<path d="M122.205 246.21C126.818 243.544 128.686 237.956 129.373 232.672C129.96 228.068 131.978 223.763 135.142 220.366C138.306 216.969 142.456 214.651 147.008 213.738C151.559 212.825 156.283 213.364 160.512 215.278C164.741 217.192 168.263 220.385 170.58 224.408C172.898 228.43 173.895 233.078 173.43 237.697C172.966 242.316 171.064 246.673 167.991 250.153C164.919 253.633 160.832 256.061 156.306 257.095C151.781 258.129 147.045 257.717 142.766 255.916C137.833 253.856 132.07 252.723 127.457 255.357C122.843 257.991 120.96 263.594 120.289 268.894C119.7 273.498 117.681 277.8 114.517 281.196C111.353 284.591 107.204 286.908 102.653 287.821C98.1027 288.733 93.3808 288.194 89.1525 286.281C84.9243 284.367 81.4031 281.175 79.085 277.154C76.767 273.134 75.7689 268.487 76.2316 263.869C76.6942 259.251 78.5942 254.895 81.6638 251.414C84.7334 247.933 88.8179 245.503 93.3417 244.466C97.8655 243.429 102.601 243.838 106.88 245.635C111.828 247.694 117.591 248.876 122.205 246.21Z" fill="white"/>
|
||||
<path d="M196.915 241.18C198.304 236.024 195.686 230.756 192.414 226.542C189.567 222.87 187.944 218.398 187.774 213.755C187.604 209.112 188.896 204.533 191.467 200.664C194.038 196.794 197.759 193.829 202.104 192.187C206.45 190.544 211.202 190.307 215.69 191.509C220.178 192.712 224.175 195.292 227.118 198.887C230.061 202.481 231.802 206.909 232.094 211.546C232.387 216.183 231.217 220.794 228.749 224.731C226.281 228.667 222.64 231.729 218.339 233.486C213.406 235.513 208.505 238.77 207.164 243.91C205.823 249.051 208.393 254.335 211.666 258.549C214.513 262.22 216.136 266.693 216.306 271.335C216.476 275.978 215.184 280.557 212.613 284.427C210.042 288.297 206.321 291.262 201.975 292.904C197.629 294.546 192.877 294.783 188.39 293.581C183.902 292.379 179.905 289.799 176.962 286.204C174.019 282.609 172.278 278.181 171.985 273.545C171.693 268.908 172.863 264.296 175.331 260.36C177.799 256.424 181.44 253.361 185.741 251.605C190.658 249.577 195.543 246.337 196.915 241.18Z" fill="white"/>
|
||||
<path d="M246.195 184.797C243.529 180.184 237.957 178.316 232.673 177.629C228.069 177.045 223.764 175.03 220.365 171.869C216.967 168.708 214.646 164.56 213.729 160.01C212.813 155.46 213.348 150.737 215.258 146.507C217.168 142.277 220.357 138.753 224.376 136.431C228.395 134.11 233.041 133.108 237.66 133.567C242.279 134.026 246.637 135.923 250.12 138.991C253.604 142.058 256.037 146.141 257.077 150.664C258.117 155.188 257.711 159.923 255.917 164.204C253.857 169.137 252.724 174.9 255.342 179.513C257.96 184.127 263.595 186.01 268.879 186.681C273.484 187.267 277.789 189.283 281.186 192.446C284.584 195.608 286.904 199.757 287.819 204.308C288.733 208.859 288.197 213.582 286.285 217.811C284.372 222.041 281.181 225.564 277.16 227.884C273.14 230.203 268.492 231.203 263.874 230.741C259.255 230.279 254.897 228.379 251.416 225.31C247.934 222.24 245.503 218.155 244.466 213.63C243.429 209.106 243.838 204.37 245.636 200.09C247.695 195.173 248.861 189.411 246.195 184.797Z" fill="white"/>
|
||||
<path d="M241.18 110.07C236.024 108.697 230.756 111.315 226.542 114.588C222.87 117.435 218.398 119.058 213.755 119.228C209.112 119.398 204.533 118.106 200.664 115.535C196.794 112.964 193.829 109.243 192.187 104.897C190.544 100.551 190.307 95.7994 191.509 91.3117C192.712 86.824 195.292 82.8268 198.887 79.8837C202.481 76.9405 206.909 75.2 211.546 74.9073C216.183 74.6147 220.794 75.7849 224.731 78.2527C228.667 80.7206 231.729 84.3617 233.486 88.6627C235.513 93.5955 238.754 98.4964 243.91 99.8374C249.066 101.178 254.335 98.6082 258.549 95.3356C262.22 92.4959 266.69 90.8798 271.328 90.7151C275.967 90.5503 280.54 91.8452 284.403 94.4172C288.267 96.9892 291.226 100.709 292.863 105.052C294.501 109.394 294.734 114.142 293.531 118.624C292.327 123.107 289.748 127.099 286.155 130.037C282.563 132.976 278.139 134.714 273.507 135.005C268.875 135.296 264.268 134.126 260.336 131.661C256.403 129.195 253.344 125.557 251.589 121.261C249.577 116.36 246.321 111.459 241.18 110.07Z" fill="white"/>
|
||||
<path d="M153.491 191.533C174.501 191.533 191.533 174.501 191.533 153.491C191.533 132.482 174.501 115.45 153.491 115.45C132.481 115.45 115.449 132.482 115.449 153.491C115.449 174.501 132.481 191.533 153.491 191.533Z" fill="white"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 13 KiB |
@@ -1,61 +0,0 @@
|
||||
{
|
||||
"name": "n8n-nodes-mem0",
|
||||
"version": "0.1.0",
|
||||
"description": "n8n community node for Mem0 — the memory layer for AI agents. Add, search, get, update, and delete long-term memories.",
|
||||
"keywords": [
|
||||
"n8n-community-node-package",
|
||||
"mem0",
|
||||
"memory",
|
||||
"ai",
|
||||
"agents",
|
||||
"llm"
|
||||
],
|
||||
"license": "MIT",
|
||||
"homepage": "https://mem0.ai",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
"email": "founders@mem0.ai"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/mem0ai/mem0",
|
||||
"directory": "integrations/n8n-nodes-mem0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.15"
|
||||
},
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"build": "npx rimraf dist && tsc && gulp build:icons",
|
||||
"dev": "tsc --watch",
|
||||
"format": "prettier nodes credentials --write",
|
||||
"lint": "eslint nodes credentials package.json",
|
||||
"lintfix": "eslint nodes credentials package.json --fix",
|
||||
"prepublishOnly": "npm run build && npm run lint"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"n8n": {
|
||||
"n8nNodesApiVersion": 1,
|
||||
"credentials": [
|
||||
"dist/credentials/Mem0Api.credentials.js"
|
||||
],
|
||||
"nodes": [
|
||||
"dist/nodes/Mem0/Mem0.node.js"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@typescript-eslint/parser": "^8.0.0",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-plugin-n8n-nodes-base": "^1.16.3",
|
||||
"gulp": "^5.0.0",
|
||||
"n8n-workflow": "*",
|
||||
"prettier": "^3.3.0",
|
||||
"rimraf": "^5.0.0",
|
||||
"typescript": "^5.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"n8n-workflow": "*"
|
||||
}
|
||||
}
|
||||
-2886
File diff suppressed because it is too large
Load Diff
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"target": "es2019",
|
||||
"lib": ["es2019", "es2020", "es2022.error"],
|
||||
"removeComments": true,
|
||||
"useUnknownInCatchVariables": false,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noImplicitAny": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": true,
|
||||
"strictNullChecks": true,
|
||||
"preserveConstEnums": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"incremental": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "./dist/"
|
||||
},
|
||||
"include": ["credentials/**/*", "nodes/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
node_modules/
|
||||
package-lock.json
|
||||
.env
|
||||
.zapierapprc
|
||||
build/
|
||||
coverage/
|
||||
*.log
|
||||
.DS_Store
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Mem0
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,35 +0,0 @@
|
||||
# Zapier integration for Mem0
|
||||
|
||||
A [Zapier](https://zapier.com) integration for [Mem0](https://mem0.ai) — the memory layer for AI agents. Add, search, list, and delete long-term memories from any Zap.
|
||||
|
||||
Built with the [Zapier Platform CLI](https://docs.zapier.com/platform/quickstart/cli-tutorial).
|
||||
|
||||
## Actions
|
||||
|
||||
| Type | Name | Endpoint |
|
||||
| --- | --- | --- |
|
||||
| Create | **Add Memory** | `POST /v3/memories/add/` |
|
||||
| Create | **Delete Memory** | `DELETE /v1/memories/{id}/` |
|
||||
| Search | **Search Memories** | `POST /v3/memories/search/` |
|
||||
| Search | **Get Memories** | `POST /v3/memories/` |
|
||||
|
||||
**Add Memory** runs LLM extraction asynchronously and returns immediately with an event ID by default. Turn on **Wait for Completion** to have the action poll until extraction finishes and return the resulting memories — note that extraction can take longer than Zapier allows a single step to run, and a timeout there does **not** mean the add failed (it typically still completes server-side). Set **Infer = false** to store the message verbatim instead of extracting.
|
||||
|
||||
**Get Memories** returns one page at a time; use the **Page** and **Limit** fields to page through larger result sets.
|
||||
|
||||
## Authentication
|
||||
|
||||
Custom (API key) auth. Provide a Mem0 API key from [app.mem0.ai](https://app.mem0.ai) → Settings → API Keys. It is sent as `Authorization: Token <key>`.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
npm install
|
||||
MEM0_API_KEY=m0-... npm test # runs the E2E suite against api.mem0.ai
|
||||
```
|
||||
|
||||
To deploy (maintainers): `zapier login && zapier push`.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -1,31 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// Custom (API key) authentication for Mem0.
|
||||
// The key is sent as "Authorization: Token <apiKey>" (matches Mem0's SDKs).
|
||||
const test = (z, _bundle) =>
|
||||
z.request({ url: '/v1/ping/', method: 'GET' });
|
||||
|
||||
module.exports = {
|
||||
type: 'custom',
|
||||
test,
|
||||
fields: [
|
||||
{
|
||||
key: 'apiKey',
|
||||
label: 'Mem0 API Key',
|
||||
type: 'string',
|
||||
required: true,
|
||||
helpText:
|
||||
'Your Mem0 API key (starts with `m0-`). Create one at [app.mem0.ai](https://app.mem0.ai) → Settings → API Keys.',
|
||||
},
|
||||
{
|
||||
key: 'baseUrl',
|
||||
label: 'Base URL',
|
||||
type: 'string',
|
||||
required: false,
|
||||
default: 'https://api.mem0.ai',
|
||||
helpText: 'Override only for self-hosted or non-default deployments.',
|
||||
},
|
||||
],
|
||||
// Shown on the connection label in the Zap editor.
|
||||
connectionLabel: 'Mem0',
|
||||
};
|
||||
@@ -1,120 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const POLL_INTERVAL_MS = 1500;
|
||||
// Bounded so the poll budget stays under Zapier's per-step execution timeout.
|
||||
const MAX_POLL_ATTEMPTS = 12;
|
||||
|
||||
// Polls GET /v1/event/{id}/ until the async memory-addition event resolves.
|
||||
const pollEvent = async (z, eventId) => {
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
|
||||
const res = await z.request({ url: `/v1/event/${eventId}/`, method: 'GET' });
|
||||
const status = res.data && res.data.status;
|
||||
if (status === 'SUCCEEDED') {
|
||||
return res.data;
|
||||
}
|
||||
if (status === 'FAILED') {
|
||||
const reason = (res.data && (res.data.error || res.data.message)) || 'unknown error';
|
||||
throw new z.errors.Error(`Mem0 memory event ${eventId} failed: ${reason}`, 'Mem0EventFailed', 400);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
||||
}
|
||||
throw new z.errors.Error(
|
||||
`Timed out waiting for memory event ${eventId}. The add was accepted and is ` +
|
||||
`likely still completing on the server — a timeout here does not mean it failed.`,
|
||||
'Mem0Timeout',
|
||||
408,
|
||||
);
|
||||
};
|
||||
|
||||
const perform = async (z, bundle) => {
|
||||
// Zapier boolean fields can arrive as the strings 'true'/'false'; coerce
|
||||
// explicitly so "Infer = No" / "Wait = No" are honored.
|
||||
const infer = String(bundle.inputData.infer) !== 'false';
|
||||
// Waiting is opt-in (the poll path can exceed Zapier's step timeout).
|
||||
const wait = String(bundle.inputData.waitForCompletion) === 'true';
|
||||
|
||||
const body = {
|
||||
messages: [{ role: bundle.inputData.role || 'user', content: bundle.inputData.content }],
|
||||
infer,
|
||||
};
|
||||
if (bundle.inputData.user_id) body.user_id = bundle.inputData.user_id;
|
||||
if (bundle.inputData.agent_id) body.agent_id = bundle.inputData.agent_id;
|
||||
if (bundle.inputData.run_id) body.run_id = bundle.inputData.run_id;
|
||||
if (bundle.inputData.metadata) {
|
||||
try {
|
||||
body.metadata =
|
||||
typeof bundle.inputData.metadata === 'string'
|
||||
? JSON.parse(bundle.inputData.metadata)
|
||||
: bundle.inputData.metadata;
|
||||
} catch (e) {
|
||||
throw new z.errors.Error('Metadata must be valid JSON.', 'InvalidInput', 400);
|
||||
}
|
||||
}
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/add/',
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
|
||||
const data = response.data;
|
||||
|
||||
// Add returns {event_id, status:PENDING|RUNNING}; poll only when opted in.
|
||||
if (wait && data.event_id && data.status !== 'SUCCEEDED' && data.status !== 'FAILED') {
|
||||
return pollEvent(z, data.event_id);
|
||||
}
|
||||
if (data.status === 'FAILED') {
|
||||
const reason = data.error || data.message || 'unknown error';
|
||||
throw new z.errors.Error(`Mem0 memory add failed: ${reason}`, 'Mem0EventFailed', 400);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
key: 'add_memory',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Add Memory',
|
||||
description: 'Extract and store memories from a message.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{
|
||||
key: 'content',
|
||||
label: 'Content',
|
||||
type: 'text',
|
||||
required: true,
|
||||
helpText: 'The message content to extract memories from.',
|
||||
},
|
||||
{
|
||||
key: 'role',
|
||||
label: 'Role',
|
||||
choices: { user: 'User', assistant: 'Assistant', system: 'System' },
|
||||
default: 'user',
|
||||
},
|
||||
{ key: 'user_id', label: 'User ID', type: 'string' },
|
||||
{ key: 'agent_id', label: 'Agent ID', type: 'string' },
|
||||
{ key: 'run_id', label: 'Run ID', type: 'string' },
|
||||
{ key: 'metadata', label: 'Metadata (JSON)', type: 'string' },
|
||||
{
|
||||
key: 'infer',
|
||||
label: 'Infer',
|
||||
type: 'boolean',
|
||||
default: 'true',
|
||||
helpText: 'Run LLM extraction over the message. Turn off to store it verbatim.',
|
||||
},
|
||||
{
|
||||
key: 'waitForCompletion',
|
||||
label: 'Wait for Completion',
|
||||
type: 'boolean',
|
||||
default: 'false',
|
||||
helpText:
|
||||
'Poll until extraction finishes and return the resulting memories. ' +
|
||||
'Leave off (default) to return immediately with an event ID — extraction can take ' +
|
||||
'longer than Zapier allows this step to run, and a timeout does not mean the add failed.',
|
||||
},
|
||||
],
|
||||
sample: { status: 'SUCCEEDED', event_id: '00000000-0000-0000-0000-000000000000', results: [] },
|
||||
},
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const perform = async (z, bundle) => {
|
||||
// Trailing slash required (Django APPEND_SLASH); id encoded so a stray slash can't mistarget the path.
|
||||
const response = await z.request({
|
||||
url: `/v1/memories/${encodeURIComponent(bundle.inputData.memory_id)}/`,
|
||||
method: 'DELETE',
|
||||
});
|
||||
return response.data || { message: 'Deleted', memory_id: bundle.inputData.memory_id };
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
key: 'delete_memory',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Delete Memory',
|
||||
description: 'Delete a single memory by its ID.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{ key: 'memory_id', label: 'Memory ID', type: 'string', required: true },
|
||||
],
|
||||
sample: { message: 'Memory deleted successfully' },
|
||||
},
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const authentication = require('./authentication');
|
||||
const { includeApiKey, handleBadResponses } = require('./middleware');
|
||||
|
||||
const addMemory = require('./creates/add_memory');
|
||||
const deleteMemory = require('./creates/delete_memory');
|
||||
const searchMemories = require('./searches/search_memories');
|
||||
const getMemories = require('./searches/get_memories');
|
||||
|
||||
const { version } = require('./package.json');
|
||||
const platformVersion = require('zapier-platform-core').version;
|
||||
|
||||
module.exports = {
|
||||
version,
|
||||
platformVersion,
|
||||
|
||||
authentication,
|
||||
|
||||
beforeRequest: [includeApiKey],
|
||||
afterResponse: [handleBadResponses],
|
||||
|
||||
creates: {
|
||||
[addMemory.key]: addMemory,
|
||||
[deleteMemory.key]: deleteMemory,
|
||||
},
|
||||
|
||||
searches: {
|
||||
[searchMemories.key]: searchMemories,
|
||||
[getMemories.key]: getMemories,
|
||||
},
|
||||
|
||||
resources: {},
|
||||
triggers: {},
|
||||
};
|
||||
@@ -1,40 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// Prepend the configured base URL and inject the auth header on every request.
|
||||
const includeApiKey = (request, z, bundle) => {
|
||||
if (bundle.authData && bundle.authData.apiKey) {
|
||||
request.headers = request.headers || {};
|
||||
request.headers.Authorization = `Token ${bundle.authData.apiKey}`;
|
||||
}
|
||||
// Resolve relative URLs against the configured base URL.
|
||||
if (request.url && request.url.startsWith('/')) {
|
||||
const base = (bundle.authData && bundle.authData.baseUrl) || 'https://api.mem0.ai';
|
||||
request.url = `${base.replace(/\/$/, '')}${request.url}`;
|
||||
}
|
||||
return request;
|
||||
};
|
||||
|
||||
// Surface HTTP failures as errors. z.request does NOT throw on non-2xx by
|
||||
// default, so without this a 4xx/5xx would flow downstream as a fake success
|
||||
// (empty search results / error body returned as a created memory).
|
||||
const handleBadResponses = (response, z, _bundle) => {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new z.errors.Error(
|
||||
'The Mem0 API key you supplied is invalid or lacks access.',
|
||||
'AuthenticationError',
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
if (response.status >= 400) {
|
||||
const data = response.data || {};
|
||||
const detail = data.detail || data.error || data.message || response.content || 'unknown error';
|
||||
throw new z.errors.Error(
|
||||
`Mem0 API request failed (HTTP ${response.status}): ${detail}`,
|
||||
'Mem0ApiError',
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
module.exports = { includeApiKey, handleBadResponses };
|
||||
@@ -1,39 +0,0 @@
|
||||
{
|
||||
"name": "zapier-mem0",
|
||||
"version": "0.1.0",
|
||||
"description": "Zapier integration for Mem0 — the memory layer for AI agents.",
|
||||
"keywords": [
|
||||
"zapier",
|
||||
"mem0",
|
||||
"memory",
|
||||
"ai",
|
||||
"agents"
|
||||
],
|
||||
"homepage": "https://mem0.ai",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
"email": "founders@mem0.ai"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/mem0ai/mem0",
|
||||
"directory": "integrations/zapier-mem0"
|
||||
},
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "jest --testTimeout 120000",
|
||||
"test:unit": "jest test/unit.test.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18",
|
||||
"npm": ">=5.6.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"zapier-platform-core": "19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.7.0"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
Generated
-3029
File diff suppressed because it is too large
Load Diff
@@ -1,48 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const perform = async (z, bundle) => {
|
||||
const body = {};
|
||||
if (bundle.inputData.user_id) body.filters = { user_id: bundle.inputData.user_id };
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/',
|
||||
method: 'POST',
|
||||
params: {
|
||||
page: Math.max(1, Math.floor(Number(bundle.inputData.page) || 1)),
|
||||
page_size: Math.max(1, Math.floor(Number(bundle.inputData.limit) || 50)),
|
||||
},
|
||||
body,
|
||||
});
|
||||
const data = response.data;
|
||||
return Array.isArray(data) ? data : data.results || [];
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
key: 'get_memories',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Get Memories',
|
||||
description: 'List stored memories for a user.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{ key: 'user_id', label: 'User ID', type: 'string', required: true },
|
||||
{
|
||||
key: 'limit',
|
||||
label: 'Limit',
|
||||
type: 'integer',
|
||||
default: '50',
|
||||
helpText: 'Max memories per page. Use Page to page through larger result sets.',
|
||||
},
|
||||
{
|
||||
key: 'page',
|
||||
label: 'Page',
|
||||
type: 'integer',
|
||||
default: '1',
|
||||
helpText: 'Which page of results to return (1-based).',
|
||||
},
|
||||
],
|
||||
sample: { id: '00000000-0000-0000-0000-000000000000', memory: 'User loves hiking' },
|
||||
},
|
||||
};
|
||||
@@ -1,37 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const perform = async (z, bundle) => {
|
||||
const body = {
|
||||
query: bundle.inputData.query,
|
||||
output_format: 'v1.1',
|
||||
top_k: Math.max(1, Math.floor(Number(bundle.inputData.limit) || 50)),
|
||||
};
|
||||
if (bundle.inputData.user_id) body.filters = { user_id: bundle.inputData.user_id };
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/search/',
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
// Searches must return an array.
|
||||
const data = response.data;
|
||||
return Array.isArray(data) ? data : data.results || [];
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
key: 'search_memories',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Search Memories',
|
||||
description: 'Semantic search over stored memories.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{ key: 'query', label: 'Query', type: 'string', required: true },
|
||||
{ key: 'user_id', label: 'User ID', type: 'string', required: true },
|
||||
{ key: 'limit', label: 'Limit', type: 'integer', default: '50' },
|
||||
],
|
||||
sample: { id: '00000000-0000-0000-0000-000000000000', memory: 'User loves hiking' },
|
||||
},
|
||||
};
|
||||
@@ -1,95 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/* global describe, it, expect, beforeAll */
|
||||
|
||||
const zapier = require('zapier-platform-core');
|
||||
const App = require('../index');
|
||||
|
||||
const appTester = zapier.createAppTester(App);
|
||||
|
||||
const authData = {
|
||||
apiKey: process.env.MEM0_API_KEY,
|
||||
baseUrl: process.env.MEM0_BASE_URL || 'https://api.mem0.ai',
|
||||
};
|
||||
|
||||
const userId = `zapier-e2e-${Date.now()}`;
|
||||
|
||||
// Retry an async op until `done` is satisfied or attempts run out. Extraction is
|
||||
// async, so the default Add returns before the memory is searchable.
|
||||
const until = async (fn, done, { attempts = 30, delayMs = 2000 } = {}) => {
|
||||
let last;
|
||||
for (let i = 0; i < attempts; i++) {
|
||||
last = await fn();
|
||||
if (done(last)) return last;
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
return last;
|
||||
};
|
||||
|
||||
// The E2E suite hits the live Mem0 API, so it only runs when MEM0_API_KEY is
|
||||
// set (locally / with a secret). In CI without a key it is skipped, not failed.
|
||||
const describeE2E = authData.apiKey ? describe : describe.skip;
|
||||
|
||||
describeE2E('Mem0 Zapier integration (E2E)', () => {
|
||||
|
||||
it('authentication.test succeeds', async () => {
|
||||
const res = await appTester(App.authentication.test, { authData });
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('adds, searches, lists, and deletes a memory', async () => {
|
||||
// Add via the default path: returns immediately with an event id.
|
||||
const added = await appTester(App.creates.add_memory.operation.perform, {
|
||||
authData,
|
||||
inputData: {
|
||||
content: 'I love hiking in the Alps and my favorite food is sushi',
|
||||
user_id: userId,
|
||||
},
|
||||
});
|
||||
expect(added.event_id).toBeDefined();
|
||||
|
||||
// Extraction is async; retry search until the memory is indexed.
|
||||
const found = await until(
|
||||
() =>
|
||||
appTester(App.searches.search_memories.operation.perform, {
|
||||
authData,
|
||||
inputData: { query: 'outdoor activities', user_id: userId, limit: 5 },
|
||||
}),
|
||||
(r) => Array.isArray(r) && r.length > 0,
|
||||
);
|
||||
expect(Array.isArray(found)).toBe(true);
|
||||
expect(found.length).toBeGreaterThan(0);
|
||||
|
||||
// Get all
|
||||
const all = await appTester(App.searches.get_memories.operation.perform, {
|
||||
authData,
|
||||
inputData: { user_id: userId },
|
||||
});
|
||||
expect(Array.isArray(all)).toBe(true);
|
||||
expect(all.length).toBeGreaterThan(0);
|
||||
|
||||
// Cleanup: delete every memory we created
|
||||
for (const mem of all) {
|
||||
await appTester(App.creates.delete_memory.operation.perform, {
|
||||
authData,
|
||||
inputData: { memory_id: mem.id },
|
||||
});
|
||||
}
|
||||
|
||||
const afterDelete = await appTester(App.searches.get_memories.operation.perform, {
|
||||
authData,
|
||||
inputData: { user_id: userId },
|
||||
});
|
||||
expect(afterDelete.length).toBe(0);
|
||||
});
|
||||
|
||||
it('surfaces API errors instead of returning an empty array (search needs a filter)', async () => {
|
||||
// filters is required by the API; omitting it must throw, not return [].
|
||||
await expect(
|
||||
appTester(App.searches.search_memories.operation.perform, {
|
||||
authData,
|
||||
inputData: { query: 'anything' },
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,124 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/* global describe, it, expect */
|
||||
|
||||
// Offline unit tests: they mock `z.request`, so they run unconditionally in CI
|
||||
// (unlike the live E2E suite in mem0.test.js, gated on MEM0_API_KEY). They cover
|
||||
// what `zapier validate` can't: boolean coercion, URL join, metadata, array shapes.
|
||||
|
||||
const addMemory = require('../creates/add_memory');
|
||||
const deleteMemory = require('../creates/delete_memory');
|
||||
const searchMemories = require('../searches/search_memories');
|
||||
const getMemories = require('../searches/get_memories');
|
||||
const { includeApiKey } = require('../middleware');
|
||||
|
||||
// Minimal `z` stub: hands back queued responses and records every request.
|
||||
const makeZ = (responses = []) => {
|
||||
const queue = [...responses];
|
||||
const requests = [];
|
||||
return {
|
||||
requests,
|
||||
request: async (opts) => {
|
||||
requests.push(opts);
|
||||
const next = queue.shift();
|
||||
return next !== undefined ? next : { data: {} };
|
||||
},
|
||||
errors: {
|
||||
Error: class Mem0Error extends Error {
|
||||
constructor(message, name, status) {
|
||||
super(message);
|
||||
this.name = name || 'Error';
|
||||
this.status = status;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
describe('add_memory (offline)', () => {
|
||||
it('coerces infer="false" to a boolean and does not poll by default', async () => {
|
||||
const z = makeZ([{ data: { event_id: 'e1', status: 'PENDING' } }]);
|
||||
const res = await addMemory.operation.perform(z, {
|
||||
inputData: { content: 'hi', user_id: 'u1', infer: 'false' },
|
||||
});
|
||||
// waitForCompletion defaults off -> a single request (the add), no poll.
|
||||
expect(z.requests).toHaveLength(1);
|
||||
expect(z.requests[0].body.infer).toBe(false);
|
||||
expect(res.status).toBe('PENDING');
|
||||
});
|
||||
|
||||
it('polls the event only when waitForCompletion="true"', async () => {
|
||||
const z = makeZ([
|
||||
{ data: { event_id: 'e1', status: 'PENDING' } },
|
||||
{ data: { status: 'SUCCEEDED', results: [{ id: 'm1' }] } },
|
||||
]);
|
||||
const res = await addMemory.operation.perform(z, {
|
||||
inputData: { content: 'hi', user_id: 'u1', waitForCompletion: 'true' },
|
||||
});
|
||||
expect(z.requests).toHaveLength(2);
|
||||
expect(z.requests[1].url).toBe('/v1/event/e1/');
|
||||
expect(res.status).toBe('SUCCEEDED');
|
||||
});
|
||||
|
||||
it('throws a clear error on invalid JSON metadata', async () => {
|
||||
const z = makeZ();
|
||||
await expect(
|
||||
addMemory.operation.perform(z, {
|
||||
inputData: { content: 'hi', user_id: 'u1', metadata: '{not json' },
|
||||
}),
|
||||
).rejects.toThrow('Metadata must be valid JSON.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('search / get array-shape enforcement (offline)', () => {
|
||||
it('search unwraps an object {results:[...]} into an array', async () => {
|
||||
const z = makeZ([{ data: { results: [{ id: 'm1' }] } }]);
|
||||
const res = await searchMemories.operation.perform(z, {
|
||||
inputData: { query: 'x', user_id: 'u1' },
|
||||
});
|
||||
expect(Array.isArray(res)).toBe(true);
|
||||
expect(res).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('get_memories returns [] when the API returns neither array nor results', async () => {
|
||||
const z = makeZ([{ data: {} }]);
|
||||
const res = await getMemories.operation.perform(z, { inputData: { user_id: 'u1' } });
|
||||
expect(Array.isArray(res)).toBe(true);
|
||||
expect(res).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('get_memories forwards page and page_size as numbers', async () => {
|
||||
const z = makeZ([{ data: { results: [] } }]);
|
||||
await getMemories.operation.perform(z, {
|
||||
inputData: { user_id: 'u1', page: '2', limit: '10' },
|
||||
});
|
||||
expect(z.requests[0].params).toEqual({ page: 2, page_size: 10 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete_memory (offline)', () => {
|
||||
it('encodes the memory id in the URL path', async () => {
|
||||
const z = makeZ([{ data: {} }]);
|
||||
await deleteMemory.operation.perform(z, { inputData: { memory_id: 'a/b c' } });
|
||||
expect(z.requests[0].url).toBe('/v1/memories/a%2Fb%20c/');
|
||||
});
|
||||
});
|
||||
|
||||
describe('includeApiKey middleware (offline)', () => {
|
||||
it('prepends the base URL and injects the auth header', () => {
|
||||
const req = includeApiKey(
|
||||
{ url: '/v3/memories/' },
|
||||
null,
|
||||
{ authData: { apiKey: 'k', baseUrl: 'https://api.mem0.ai/' } },
|
||||
);
|
||||
expect(req.url).toBe('https://api.mem0.ai/v3/memories/');
|
||||
expect(req.headers.Authorization).toBe('Token k');
|
||||
});
|
||||
|
||||
it('leaves absolute URLs untouched', () => {
|
||||
const req = includeApiKey({ url: 'https://other.example/x' }, null, {
|
||||
authData: { apiKey: 'k' },
|
||||
});
|
||||
expect(req.url).toBe('https://other.example/x');
|
||||
});
|
||||
});
|
||||
+37
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0ai",
|
||||
"version": "3.1.0",
|
||||
"version": "3.1.1",
|
||||
"description": "The Memory Layer For Your AI Apps",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
@@ -151,6 +151,42 @@
|
||||
"@aws-sdk/client-bedrock-runtime": ">=3.0.0 <3.968.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@qdrant/js-client-rest": {
|
||||
"optional": true
|
||||
},
|
||||
"redis": {
|
||||
"optional": true
|
||||
},
|
||||
"@supabase/supabase-js": {
|
||||
"optional": true
|
||||
},
|
||||
"cloudflare": {
|
||||
"optional": true
|
||||
},
|
||||
"@azure/search-documents": {
|
||||
"optional": true
|
||||
},
|
||||
"@azure/identity": {
|
||||
"optional": true
|
||||
},
|
||||
"@langchain/core": {
|
||||
"optional": true
|
||||
},
|
||||
"@anthropic-ai/sdk": {
|
||||
"optional": true
|
||||
},
|
||||
"@google/genai": {
|
||||
"optional": true
|
||||
},
|
||||
"groq-sdk": {
|
||||
"optional": true
|
||||
},
|
||||
"@mistralai/mistralai": {
|
||||
"optional": true
|
||||
},
|
||||
"ollama": {
|
||||
"optional": true
|
||||
},
|
||||
"mysql2": {
|
||||
"optional": true
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { FlagEmbedding } from "fastembed";
|
||||
import { Embedder } from "./base";
|
||||
import { EmbeddingConfig } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
// FastEmbed only ships a fixed set of ONNX models (fastembed's `EmbeddingModel`
|
||||
// enum, minus CUSTOM). Mirrored here as literals so an invalid model name can
|
||||
@@ -54,14 +55,11 @@ export class FastEmbedEmbedder implements Embedder {
|
||||
* consumers that never touch FastEmbed don't need it installed.
|
||||
*/
|
||||
private async initEmbeddingModel(): Promise<FlagEmbedding> {
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("fastembed");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The 'fastembed' package is required to use the FastEmbed embedder. Install it with: npm install fastembed",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"fastembed",
|
||||
"FastEmbed embedder",
|
||||
() => import("fastembed"),
|
||||
);
|
||||
|
||||
return sdk.FlagEmbedding.init({ model: this.modelName });
|
||||
}
|
||||
|
||||
@@ -1,21 +1,32 @@
|
||||
import { GoogleGenAI } from "@google/genai";
|
||||
import type { GoogleGenAI } from "@google/genai";
|
||||
import { Embedder } from "./base";
|
||||
import { EmbeddingConfig } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
export class GoogleEmbedder implements Embedder {
|
||||
private google: GoogleGenAI;
|
||||
private google!: GoogleGenAI;
|
||||
private model: string;
|
||||
private embeddingDims: number | undefined;
|
||||
private readonly apiKey: string | undefined;
|
||||
|
||||
constructor(config: EmbeddingConfig) {
|
||||
this.google = new GoogleGenAI({
|
||||
apiKey: config.apiKey || process.env.GOOGLE_API_KEY,
|
||||
});
|
||||
this.apiKey = config.apiKey || process.env.GOOGLE_API_KEY;
|
||||
this.model = config.model || "gemini-embedding-001";
|
||||
this.embeddingDims = config.embeddingDims;
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.google) return;
|
||||
const sdk = await loadPeer(
|
||||
"@google/genai",
|
||||
"Google embedder",
|
||||
() => import("@google/genai"),
|
||||
);
|
||||
this.google = new sdk.GoogleGenAI({ apiKey: this.apiKey });
|
||||
}
|
||||
|
||||
async embed(text: string): Promise<number[]> {
|
||||
await this.ensureClient();
|
||||
const response = await this.google.models.embedContent({
|
||||
model: this.model,
|
||||
contents: text,
|
||||
@@ -27,6 +38,7 @@ export class GoogleEmbedder implements Embedder {
|
||||
}
|
||||
|
||||
async embedBatch(texts: string[]): Promise<number[][]> {
|
||||
await this.ensureClient();
|
||||
const response = await this.google.models.embedContent({
|
||||
model: this.model,
|
||||
contents: texts,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Embeddings } from "@langchain/core/embeddings";
|
||||
import type { Embeddings } from "@langchain/core/embeddings";
|
||||
import { Embedder } from "./base";
|
||||
import { EmbeddingConfig } from "../types";
|
||||
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { Ollama } from "ollama";
|
||||
import type { Ollama } from "ollama";
|
||||
import { Embedder } from "./base";
|
||||
import { EmbeddingConfig } from "../types";
|
||||
import { logger } from "../utils/logger";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
export class OllamaEmbedder implements Embedder {
|
||||
private ollama: Ollama;
|
||||
private ollama!: Ollama;
|
||||
private model: string;
|
||||
private embeddingDims?: number;
|
||||
private readonly host: string;
|
||||
// Using this variable to avoid calling the Ollama server multiple times
|
||||
private initialized: boolean = false;
|
||||
|
||||
constructor(config: EmbeddingConfig) {
|
||||
this.ollama = new Ollama({
|
||||
host: config.url || config.baseURL || "http://localhost:11434",
|
||||
});
|
||||
this.host = config.url || config.baseURL || "http://localhost:11434";
|
||||
this.model = config.model || "nomic-embed-text:latest";
|
||||
this.embeddingDims = config.embeddingDims || 768;
|
||||
this.ensureModelExists().catch((err) => {
|
||||
@@ -21,7 +21,18 @@ export class OllamaEmbedder implements Embedder {
|
||||
});
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.ollama) return;
|
||||
const sdk = await loadPeer(
|
||||
"ollama",
|
||||
"Ollama embedder",
|
||||
() => import("ollama"),
|
||||
);
|
||||
this.ollama = new sdk.Ollama({ host: this.host });
|
||||
}
|
||||
|
||||
async embed(text: string): Promise<number[]> {
|
||||
await this.ensureClient();
|
||||
try {
|
||||
await this.ensureModelExists();
|
||||
} catch (err) {
|
||||
@@ -54,6 +65,7 @@ export class OllamaEmbedder implements Embedder {
|
||||
if (this.initialized) {
|
||||
return true;
|
||||
}
|
||||
await this.ensureClient();
|
||||
const local_models = await this.ollama.list();
|
||||
const target = OllamaEmbedder.normalizeModelName(this.model);
|
||||
if (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { PredictionServiceClient } from "@google-cloud/aiplatform";
|
||||
import { Embedder } from "./base";
|
||||
import { VertexAIConfig } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
type AIPlatform = typeof import("@google-cloud/aiplatform");
|
||||
type ClientOptions = NonNullable<
|
||||
@@ -105,15 +106,11 @@ export class VertexAIEmbedder implements Embedder {
|
||||
}
|
||||
|
||||
private async createClient(): Promise<void> {
|
||||
let aiplatform: AIPlatform;
|
||||
try {
|
||||
aiplatform = await import("@google-cloud/aiplatform");
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
"Failed to import '@google-cloud/aiplatform'. Please install it to use the Vertex AI embedding provider: " +
|
||||
(err as Error).message,
|
||||
);
|
||||
}
|
||||
const aiplatform: AIPlatform = await loadPeer(
|
||||
"@google-cloud/aiplatform",
|
||||
"Vertex AI embedding provider",
|
||||
() => import("@google-cloud/aiplatform"),
|
||||
);
|
||||
|
||||
const client = new aiplatform.PredictionServiceClient(this.clientOptions);
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
import type Anthropic from "@anthropic-ai/sdk";
|
||||
import { LLM, LLMResponse } from "./base";
|
||||
import { LLMConfig, Message } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
export class AnthropicLLM implements LLM {
|
||||
private client: Anthropic;
|
||||
private client!: Anthropic;
|
||||
private readonly clientArgs: { apiKey: string; baseURL?: string };
|
||||
private model: string;
|
||||
private maxTokens: number;
|
||||
private temperature?: number;
|
||||
@@ -20,7 +22,7 @@ export class AnthropicLLM implements LLM {
|
||||
if (config.baseURL) {
|
||||
clientArgs.baseURL = config.baseURL;
|
||||
}
|
||||
this.client = new Anthropic(clientArgs);
|
||||
this.clientArgs = clientArgs;
|
||||
this.model = config.model || "claude-sonnet-4-6";
|
||||
// Defaults mirror the Python provider's AnthropicConfig
|
||||
// (max_tokens=2000, temperature=0.1, top_p omitted).
|
||||
@@ -29,11 +31,22 @@ export class AnthropicLLM implements LLM {
|
||||
this.topP = config.topP;
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.client) return;
|
||||
const sdk = await loadPeer(
|
||||
"@anthropic-ai/sdk",
|
||||
"Anthropic LLM",
|
||||
() => import("@anthropic-ai/sdk"),
|
||||
);
|
||||
this.client = new sdk.default(this.clientArgs);
|
||||
}
|
||||
|
||||
async generateResponse(
|
||||
messages: Message[],
|
||||
responseFormat?: { type: string },
|
||||
tools?: any[],
|
||||
): Promise<string | LLMResponse> {
|
||||
await this.ensureClient();
|
||||
// Extract system message if present
|
||||
const systemMessage = messages.find((msg) => msg.role === "system");
|
||||
const otherMessages = messages.filter((msg) => msg.role !== "system");
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { GoogleGenAI } from "@google/genai";
|
||||
import type { GoogleGenAI } from "@google/genai";
|
||||
import { LLM, LLMResponse } from "./base";
|
||||
import { LLMConfig, Message } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
export class GoogleLLM implements LLM {
|
||||
private google: GoogleGenAI;
|
||||
private google!: GoogleGenAI;
|
||||
private model: string;
|
||||
private readonly apiKey: string | undefined;
|
||||
|
||||
constructor(config: LLMConfig) {
|
||||
this.google = new GoogleGenAI({ apiKey: config.apiKey });
|
||||
this.apiKey = config.apiKey;
|
||||
this.model = config.model || "gemini-2.0-flash";
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.google) return;
|
||||
const sdk = await loadPeer(
|
||||
"@google/genai",
|
||||
"Google LLM",
|
||||
() => import("@google/genai"),
|
||||
);
|
||||
this.google = new sdk.GoogleGenAI({ apiKey: this.apiKey });
|
||||
}
|
||||
|
||||
private formatContents(messages: Message[]) {
|
||||
return messages.map((msg) => ({
|
||||
parts: [
|
||||
@@ -30,6 +42,7 @@ export class GoogleLLM implements LLM {
|
||||
responseFormat?: { type: string },
|
||||
tools?: any[],
|
||||
): Promise<string | LLMResponse> {
|
||||
await this.ensureClient();
|
||||
const contents = this.formatContents(messages);
|
||||
|
||||
// Build config with tools if provided
|
||||
@@ -72,6 +85,7 @@ export class GoogleLLM implements LLM {
|
||||
}
|
||||
|
||||
async generateChat(messages: Message[]): Promise<LLMResponse> {
|
||||
await this.ensureClient();
|
||||
const completion = await this.google.models.generateContent({
|
||||
contents: this.formatContents(messages),
|
||||
model: this.model,
|
||||
|
||||
@@ -1,24 +1,37 @@
|
||||
import { Groq } from "groq-sdk";
|
||||
import type { Groq } from "groq-sdk";
|
||||
import { LLM, LLMResponse } from "./base";
|
||||
import { LLMConfig, Message } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
export class GroqLLM implements LLM {
|
||||
private client: Groq;
|
||||
private client!: Groq;
|
||||
private model: string;
|
||||
private readonly apiKey: string;
|
||||
|
||||
constructor(config: LLMConfig) {
|
||||
const apiKey = config.apiKey || process.env.GROQ_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error("Groq API key is required");
|
||||
}
|
||||
this.client = new Groq({ apiKey });
|
||||
this.apiKey = apiKey;
|
||||
this.model = config.model || "llama3-70b-8192";
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.client) return;
|
||||
const sdk = await loadPeer(
|
||||
"groq-sdk",
|
||||
"Groq LLM",
|
||||
() => import("groq-sdk"),
|
||||
);
|
||||
this.client = new sdk.Groq({ apiKey: this.apiKey });
|
||||
}
|
||||
|
||||
async generateResponse(
|
||||
messages: Message[],
|
||||
responseFormat?: { type: string },
|
||||
): Promise<string> {
|
||||
await this.ensureClient();
|
||||
const response = await this.client.chat.completions.create({
|
||||
model: this.model,
|
||||
messages: messages.map((msg) => ({
|
||||
@@ -35,6 +48,7 @@ export class GroqLLM implements LLM {
|
||||
}
|
||||
|
||||
async generateChat(messages: Message[]): Promise<LLMResponse> {
|
||||
await this.ensureClient();
|
||||
const response = await this.client.chat.completions.create({
|
||||
model: this.model,
|
||||
messages: messages.map((msg) => ({
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
||||
import {
|
||||
AIMessage,
|
||||
HumanMessage,
|
||||
SystemMessage,
|
||||
BaseMessage,
|
||||
} from "@langchain/core/messages";
|
||||
import type { BaseLanguageModel } from "@langchain/core/language_models/base";
|
||||
import type { BaseMessage } from "@langchain/core/messages";
|
||||
import { z } from "zod";
|
||||
import { LLM, LLMResponse } from "./base";
|
||||
import { LLMConfig, Message } from "../types/index";
|
||||
// Import the schemas directly into LangchainLLM
|
||||
import { FactRetrievalSchema, MemoryUpdateSchema } from "../prompts";
|
||||
|
||||
const convertToLangchainMessages = (messages: Message[]): BaseMessage[] => {
|
||||
const convertToLangchainMessages = async (
|
||||
messages: Message[],
|
||||
): Promise<BaseMessage[]> => {
|
||||
const { AIMessage, HumanMessage, SystemMessage } =
|
||||
await import("@langchain/core/messages");
|
||||
return messages.map((msg) => {
|
||||
const content =
|
||||
typeof msg.content === "string"
|
||||
@@ -62,7 +61,7 @@ export class LangchainLLM implements LLM {
|
||||
response_format?: { type: string },
|
||||
tools?: any[],
|
||||
): Promise<string | LLMResponse> {
|
||||
const langchainMessages = convertToLangchainMessages(messages);
|
||||
const langchainMessages = await convertToLangchainMessages(messages);
|
||||
let runnable: any = this.llmInstance;
|
||||
const invokeOptions: Record<string, any> = {};
|
||||
let isStructuredOutput = false;
|
||||
@@ -170,7 +169,7 @@ export class LangchainLLM implements LLM {
|
||||
}
|
||||
|
||||
async generateChat(messages: Message[]): Promise<LLMResponse> {
|
||||
const langchainMessages = convertToLangchainMessages(messages);
|
||||
const langchainMessages = await convertToLangchainMessages(messages);
|
||||
try {
|
||||
const response = await this.llmInstance.invoke(langchainMessages);
|
||||
if (response && typeof response.content === "string") {
|
||||
|
||||
@@ -1,21 +1,31 @@
|
||||
import { Mistral } from "@mistralai/mistralai";
|
||||
import type { Mistral } from "@mistralai/mistralai";
|
||||
import { LLM, LLMResponse } from "./base";
|
||||
import { LLMConfig, Message } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
export class MistralLLM implements LLM {
|
||||
private client: Mistral;
|
||||
private client!: Mistral;
|
||||
private model: string;
|
||||
private readonly apiKey: string;
|
||||
|
||||
constructor(config: LLMConfig) {
|
||||
if (!config.apiKey) {
|
||||
throw new Error("Mistral API key is required");
|
||||
}
|
||||
this.client = new Mistral({
|
||||
apiKey: config.apiKey,
|
||||
});
|
||||
this.apiKey = config.apiKey;
|
||||
this.model = config.model || "mistral-tiny-latest";
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.client) return;
|
||||
const sdk = await loadPeer(
|
||||
"@mistralai/mistralai",
|
||||
"Mistral LLM",
|
||||
() => import("@mistralai/mistralai"),
|
||||
);
|
||||
this.client = new sdk.Mistral({ apiKey: this.apiKey });
|
||||
}
|
||||
|
||||
// Helper function to convert content to string
|
||||
private contentToString(content: any): string {
|
||||
if (typeof content === "string") {
|
||||
@@ -41,6 +51,7 @@ export class MistralLLM implements LLM {
|
||||
responseFormat?: { type: string },
|
||||
tools?: any[],
|
||||
): Promise<string | LLMResponse> {
|
||||
await this.ensureClient();
|
||||
const response = await this.client.chat.complete({
|
||||
model: this.model,
|
||||
messages: messages.map((msg) => ({
|
||||
@@ -82,6 +93,7 @@ export class MistralLLM implements LLM {
|
||||
}
|
||||
|
||||
async generateChat(messages: Message[]): Promise<LLMResponse> {
|
||||
await this.ensureClient();
|
||||
const formattedMessages = messages.map((msg) => ({
|
||||
role: msg.role as "system" | "user" | "assistant",
|
||||
content:
|
||||
|
||||
@@ -1,29 +1,36 @@
|
||||
import { Ollama } from "ollama";
|
||||
import type { Ollama } from "ollama";
|
||||
import { LLM, LLMResponse } from "./base";
|
||||
import { LLMConfig, Message } from "../types";
|
||||
import { logger } from "../utils/logger";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
export class OllamaLLM implements LLM {
|
||||
private ollama: Ollama;
|
||||
private ollama!: Ollama;
|
||||
private model: string;
|
||||
private readonly host: string;
|
||||
// Using this variable to avoid calling the Ollama server multiple times
|
||||
private initialized: boolean = false;
|
||||
|
||||
constructor(config: LLMConfig) {
|
||||
this.ollama = new Ollama({
|
||||
host: config.url || config.baseURL || "http://localhost:11434",
|
||||
});
|
||||
this.host = config.url || config.baseURL || "http://localhost:11434";
|
||||
this.model = config.model || "llama3.1:8b";
|
||||
this.ensureModelExists().catch((err) => {
|
||||
logger.error(`Error ensuring model exists: ${err}`);
|
||||
});
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.ollama) return;
|
||||
const sdk = await loadPeer("ollama", "Ollama LLM", () => import("ollama"));
|
||||
this.ollama = new sdk.Ollama({ host: this.host });
|
||||
}
|
||||
|
||||
async generateResponse(
|
||||
messages: Message[],
|
||||
responseFormat?: { type: string },
|
||||
tools?: any[],
|
||||
): Promise<string | LLMResponse> {
|
||||
await this.ensureClient();
|
||||
try {
|
||||
await this.ensureModelExists();
|
||||
} catch (err) {
|
||||
@@ -63,6 +70,7 @@ export class OllamaLLM implements LLM {
|
||||
}
|
||||
|
||||
async generateChat(messages: Message[]): Promise<LLMResponse> {
|
||||
await this.ensureClient();
|
||||
try {
|
||||
await this.ensureModelExists();
|
||||
} catch (err) {
|
||||
@@ -93,6 +101,7 @@ export class OllamaLLM implements LLM {
|
||||
if (this.initialized) {
|
||||
return true;
|
||||
}
|
||||
await this.ensureClient();
|
||||
const local_models = await this.ollama.list();
|
||||
if (!local_models.models.find((m: any) => m.name === this.model)) {
|
||||
logger.info(`Pulling model ${this.model}...`);
|
||||
|
||||
@@ -101,6 +101,10 @@ const ENTITY_PARAMS = [
|
||||
"runId",
|
||||
];
|
||||
|
||||
// Identity keys stripped from update() metadata: ENTITY_PARAMS covers user_id/agent_id/run_id
|
||||
// in both casings (the default store promotes camelCase on read); actor_id has no camelCase alias.
|
||||
const IDENTITY_KEYS = [...ENTITY_PARAMS, "actor_id"];
|
||||
|
||||
/**
|
||||
* Validates that no top-level entity parameters are passed in config.
|
||||
* @throws Error if entity params are found at top level
|
||||
@@ -122,18 +126,19 @@ function rejectTopLevelEntityParams(
|
||||
|
||||
/**
|
||||
* Validates and normalizes an entity ID.
|
||||
* - Coerces non-string ids (e.g. numeric database keys) to string
|
||||
* - Trims leading/trailing whitespace
|
||||
* - Rejects empty or whitespace-only strings
|
||||
* - Rejects strings containing internal whitespace
|
||||
* @returns The trimmed entity ID, or undefined if input is undefined
|
||||
* @returns The trimmed entity ID, or undefined if input is undefined/null
|
||||
* @throws Error if entity ID is invalid
|
||||
*/
|
||||
function validateAndTrimEntityId(
|
||||
value: string | undefined,
|
||||
value: string | number | undefined | null,
|
||||
name: string,
|
||||
): string | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const trimmed = value.trim();
|
||||
if (value == null) return undefined;
|
||||
const trimmed = String(value).trim();
|
||||
if (trimmed === "") {
|
||||
throw new Error(
|
||||
`Invalid ${name}: cannot be empty or whitespace-only. Provide a valid identifier.`,
|
||||
@@ -1941,9 +1946,14 @@ export class Memory {
|
||||
existingEmbeddings[newData] ||
|
||||
(await this.embedder.embed(newData, "update"));
|
||||
|
||||
// Caller metadata must not overwrite or inject an identity scope (#6342 / #6367).
|
||||
const sanitizedMetadata = Object.fromEntries(
|
||||
Object.entries(metadata).filter(([k]) => !IDENTITY_KEYS.includes(k)),
|
||||
);
|
||||
|
||||
const newMetadata = {
|
||||
...existingMemory.payload,
|
||||
...metadata,
|
||||
...sanitizedMetadata,
|
||||
data: newData,
|
||||
hash: createHash("md5").update(newData).digest("hex"),
|
||||
textLemmatized: lemmatizeForBm25(newData),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { RerankerConfig } from "../types";
|
||||
import { Reranker, RerankResult } from "./base";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
const DEFAULT_MODEL = "rerank-v3.5";
|
||||
|
||||
@@ -41,14 +42,11 @@ export class CohereReranker implements Reranker {
|
||||
}
|
||||
|
||||
private async createClient(): Promise<any> {
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("cohere-ai");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The 'cohere-ai' package is required to use the Cohere reranker. Install it with: npm install cohere-ai",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"cohere-ai",
|
||||
"Cohere reranker",
|
||||
() => import("cohere-ai"),
|
||||
);
|
||||
return new sdk.CohereClient({ token: this.apiKey });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { RerankerConfig } from "../types";
|
||||
import { Reranker, RerankResult } from "./base";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
const DEFAULT_MODEL = "zerank-1";
|
||||
|
||||
@@ -37,14 +38,11 @@ export class ZeroEntropyReranker implements Reranker {
|
||||
}
|
||||
|
||||
private async createClient(): Promise<any> {
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("zeroentropy");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The 'zeroentropy' package is required to use the ZeroEntropy reranker. Install it with: npm install zeroentropy",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"zeroentropy",
|
||||
"ZeroEntropy reranker",
|
||||
() => import("zeroentropy"),
|
||||
);
|
||||
return new sdk.ZeroEntropy({ apiKey: this.apiKey });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createClient, SupabaseClient } from "@supabase/supabase-js";
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { HistoryManager } from "./base";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface HistoryEntry {
|
||||
id: string;
|
||||
@@ -20,16 +21,32 @@ interface SupabaseHistoryConfig {
|
||||
}
|
||||
|
||||
export class SupabaseHistoryManager implements HistoryManager {
|
||||
private supabase: SupabaseClient;
|
||||
// ponytail: benign double-construct race — two concurrent first-calls may each
|
||||
// build a client; createClient opens no connection, so last-write-wins is fine.
|
||||
private supabase!: SupabaseClient;
|
||||
private readonly supabaseUrl: string;
|
||||
private readonly supabaseKey: string;
|
||||
private readonly tableName: string;
|
||||
|
||||
constructor(config: SupabaseHistoryConfig) {
|
||||
this.tableName = config.tableName || "memory_history";
|
||||
this.supabase = createClient(config.supabaseUrl, config.supabaseKey);
|
||||
this.supabaseUrl = config.supabaseUrl;
|
||||
this.supabaseKey = config.supabaseKey;
|
||||
this.initializeSupabase().catch(console.error);
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.supabase) return;
|
||||
const sdk = await loadPeer(
|
||||
"@supabase/supabase-js",
|
||||
"Supabase history manager",
|
||||
() => import("@supabase/supabase-js"),
|
||||
);
|
||||
this.supabase = sdk.createClient(this.supabaseUrl, this.supabaseKey);
|
||||
}
|
||||
|
||||
private async initializeSupabase(): Promise<void> {
|
||||
await this.ensureClient();
|
||||
// Check if table exists
|
||||
const { error } = await this.supabase
|
||||
.from(this.tableName)
|
||||
@@ -65,6 +82,7 @@ create table ${this.tableName} (
|
||||
updatedAt?: string,
|
||||
isDeleted: number = 0,
|
||||
): Promise<void> {
|
||||
await this.ensureClient();
|
||||
const historyEntry: HistoryEntry = {
|
||||
id: uuidv4(),
|
||||
memory_id: memoryId,
|
||||
@@ -87,6 +105,7 @@ create table ${this.tableName} (
|
||||
}
|
||||
|
||||
async getHistory(memoryId: string): Promise<any[]> {
|
||||
await this.ensureClient();
|
||||
const { data, error } = await this.supabase
|
||||
.from(this.tableName)
|
||||
.select("*")
|
||||
@@ -103,6 +122,7 @@ create table ${this.tableName} (
|
||||
}
|
||||
|
||||
async reset(): Promise<void> {
|
||||
await this.ensureClient();
|
||||
const { error } = await this.supabase
|
||||
.from(this.tableName)
|
||||
.delete()
|
||||
|
||||
@@ -12,8 +12,9 @@ const upsert = jest.fn().mockResolvedValue(undefined);
|
||||
const query = jest.fn().mockResolvedValue({ matches: [] });
|
||||
const fetch = jest.fn().mockResolvedValue({ records: {} });
|
||||
const deleteOne = jest.fn().mockResolvedValue(undefined);
|
||||
const deleteAll = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
const nsHandle = { upsert, query, fetch, deleteOne };
|
||||
const nsHandle = { upsert, query, fetch, deleteOne, deleteAll };
|
||||
const namespace = jest.fn().mockReturnValue(nsHandle);
|
||||
|
||||
const describeIndexStats = jest
|
||||
@@ -47,6 +48,7 @@ const __mocks__ = {
|
||||
query,
|
||||
fetch,
|
||||
deleteOne,
|
||||
deleteAll,
|
||||
namespace,
|
||||
describeIndexStats,
|
||||
index,
|
||||
@@ -94,6 +96,7 @@ beforeEach(() => {
|
||||
__mocks__.query.mockResolvedValue({ matches: [] });
|
||||
__mocks__.fetch.mockResolvedValue({ records: {} });
|
||||
__mocks__.deleteOne.mockResolvedValue(undefined);
|
||||
__mocks__.deleteAll.mockResolvedValue(undefined);
|
||||
__mocks__.describeIndexStats.mockResolvedValue({
|
||||
totalRecordCount: 0,
|
||||
namespaces: {},
|
||||
@@ -104,6 +107,7 @@ beforeEach(() => {
|
||||
query: __mocks__.query,
|
||||
fetch: __mocks__.fetch,
|
||||
deleteOne: __mocks__.deleteOne,
|
||||
deleteAll: __mocks__.deleteAll,
|
||||
};
|
||||
__mocks__.namespace.mockReturnValue(nsHandle);
|
||||
__mocks__.index.mockReturnValue({
|
||||
@@ -424,6 +428,14 @@ describe("deleteCol", () => {
|
||||
await db.initialize();
|
||||
expect(__mocks__.createIndex).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("clears only the namespace and never drops the shared index", async () => {
|
||||
const db = await initDb({ namespace: "tenant-a" });
|
||||
await db.deleteCol();
|
||||
expect(__mocks__.namespace).toHaveBeenCalledWith("tenant-a");
|
||||
expect(__mocks__.deleteAll).toHaveBeenCalled();
|
||||
expect(__mocks__.deleteIndex).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("list", () => {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export async function loadPeer(
|
||||
pkg: string,
|
||||
label: string,
|
||||
load: () => Promise<any>,
|
||||
): Promise<any> {
|
||||
try {
|
||||
return await load();
|
||||
} catch {
|
||||
throw new Error(
|
||||
`The '${pkg}' package is required to use the ${label}. Install it with: npm install ${pkg}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
import type {
|
||||
SearchClient,
|
||||
SearchIndexClient,
|
||||
AzureKeyCredential,
|
||||
SearchIndex,
|
||||
SearchField,
|
||||
SearchFieldDataType,
|
||||
@@ -13,9 +12,9 @@ import {
|
||||
BinaryQuantizationCompression,
|
||||
VectorizedQuery,
|
||||
} from "@azure/search-documents";
|
||||
import { DefaultAzureCredential } from "@azure/identity";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
/**
|
||||
* Configuration interface for Azure AI Search vector store
|
||||
@@ -71,8 +70,8 @@ interface AzureAISearchConfig extends VectorStoreConfig {
|
||||
* Supports vector search with hybrid search, compression, and filtering
|
||||
*/
|
||||
export class AzureAISearch implements VectorStore {
|
||||
private searchClient: SearchClient<any>;
|
||||
private indexClient: SearchIndexClient;
|
||||
private searchClient!: SearchClient<any>;
|
||||
private indexClient!: SearchIndexClient;
|
||||
private readonly serviceName: string;
|
||||
private readonly indexName: string;
|
||||
private readonly embeddingModelDims: number;
|
||||
@@ -93,25 +92,42 @@ export class AzureAISearch implements VectorStore {
|
||||
this.vectorFilterMode = config.vectorFilterMode || "preFilter";
|
||||
this.apiKey = config.apiKey;
|
||||
|
||||
// Initialize the index
|
||||
this.initialize().catch(console.error);
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.searchClient) return;
|
||||
const searchSdk = await loadPeer(
|
||||
"@azure/search-documents",
|
||||
"Azure AI Search vector store",
|
||||
() => import("@azure/search-documents"),
|
||||
);
|
||||
|
||||
const serviceEndpoint = `https://${this.serviceName}.search.windows.net`;
|
||||
|
||||
// Determine authentication: API key or DefaultAzureCredential
|
||||
const credential =
|
||||
this.apiKey && this.apiKey !== "" && this.apiKey !== "your-api-key"
|
||||
? new AzureKeyCredential(this.apiKey)
|
||||
: new DefaultAzureCredential();
|
||||
let credential: any;
|
||||
if (this.apiKey && this.apiKey !== "" && this.apiKey !== "your-api-key") {
|
||||
credential = new searchSdk.AzureKeyCredential(this.apiKey);
|
||||
} else {
|
||||
const identitySdk = await loadPeer(
|
||||
"@azure/identity",
|
||||
"Azure AI Search without an apiKey",
|
||||
() => import("@azure/identity"),
|
||||
);
|
||||
credential = new identitySdk.DefaultAzureCredential();
|
||||
}
|
||||
|
||||
// Initialize clients
|
||||
this.searchClient = new SearchClient(
|
||||
this.searchClient = new searchSdk.SearchClient(
|
||||
serviceEndpoint,
|
||||
this.indexName,
|
||||
credential,
|
||||
);
|
||||
|
||||
this.indexClient = new SearchIndexClient(serviceEndpoint, credential);
|
||||
|
||||
// Initialize the index
|
||||
this.initialize().catch(console.error);
|
||||
this.indexClient = new searchSdk.SearchIndexClient(
|
||||
serviceEndpoint,
|
||||
credential,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,6 +141,7 @@ export class AzureAISearch implements VectorStore {
|
||||
}
|
||||
|
||||
private async _doInitialize(): Promise<void> {
|
||||
await this.ensureClient();
|
||||
try {
|
||||
const collections = await this.listCols();
|
||||
if (!collections.includes(this.indexName)) {
|
||||
@@ -262,6 +279,7 @@ export class AzureAISearch implements VectorStore {
|
||||
ids: string[],
|
||||
payloads: Record<string, any>[],
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
console.log(
|
||||
`Inserting ${vectors.length} vectors into index ${this.indexName}`,
|
||||
);
|
||||
@@ -334,6 +352,7 @@ export class AzureAISearch implements VectorStore {
|
||||
topK: number = 5,
|
||||
filters?: SearchFilters,
|
||||
): Promise<VectorStoreResult[] | null> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const filterExpression = filters
|
||||
? this.buildFilterExpression(filters)
|
||||
@@ -373,6 +392,7 @@ export class AzureAISearch implements VectorStore {
|
||||
topK: number = 5,
|
||||
filters?: SearchFilters,
|
||||
): Promise<VectorStoreResult[]> {
|
||||
await this.initialize();
|
||||
const filterExpression = filters
|
||||
? this.buildFilterExpression(filters)
|
||||
: undefined;
|
||||
@@ -429,6 +449,7 @@ export class AzureAISearch implements VectorStore {
|
||||
* Delete a vector by ID
|
||||
*/
|
||||
async delete(vectorId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
const response = await this.searchClient.deleteDocuments([
|
||||
{ id: vectorId },
|
||||
]);
|
||||
@@ -454,6 +475,7 @@ export class AzureAISearch implements VectorStore {
|
||||
vector: number[],
|
||||
payload: Record<string, any>,
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
const document: Record<string, any> = { id: vectorId };
|
||||
|
||||
if (vector) {
|
||||
@@ -486,6 +508,7 @@ export class AzureAISearch implements VectorStore {
|
||||
* Retrieve a vector by ID
|
||||
*/
|
||||
async get(vectorId: string): Promise<VectorStoreResult | null> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const result = await this.searchClient.getDocument(vectorId);
|
||||
const payloadStr = result.payload as string;
|
||||
@@ -521,6 +544,7 @@ export class AzureAISearch implements VectorStore {
|
||||
* Delete the index
|
||||
*/
|
||||
async deleteCol(): Promise<void> {
|
||||
await this.initialize();
|
||||
await this.indexClient.deleteIndex(this.indexName);
|
||||
}
|
||||
|
||||
@@ -542,6 +566,7 @@ export class AzureAISearch implements VectorStore {
|
||||
filters?: SearchFilters,
|
||||
topK: number = 100,
|
||||
): Promise<[VectorStoreResult[], number]> {
|
||||
await this.initialize();
|
||||
const filterExpression = filters
|
||||
? this.buildFilterExpression(filters)
|
||||
: undefined;
|
||||
@@ -586,6 +611,7 @@ export class AzureAISearch implements VectorStore {
|
||||
* Required by VectorStore interface
|
||||
*/
|
||||
async getUserId(): Promise<string> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// Check if memory_migrations index exists
|
||||
const collections = await this.listCols();
|
||||
@@ -648,6 +674,7 @@ export class AzureAISearch implements VectorStore {
|
||||
* Required by VectorStore interface
|
||||
*/
|
||||
async setUserId(userId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// Get existing point ID or generate new one
|
||||
const searchResults = await this.searchClient.search("*", {
|
||||
@@ -677,6 +704,7 @@ export class AzureAISearch implements VectorStore {
|
||||
* Reset the index by deleting and recreating it
|
||||
*/
|
||||
async reset(): Promise<void> {
|
||||
await this.initialize();
|
||||
console.log(`Resetting index ${this.indexName}...`);
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Pool, RowDataPacket } from "mysql2/promise";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
const SAFE_IDENTIFIER_RE = /^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/;
|
||||
|
||||
@@ -94,14 +95,11 @@ export class AzureMySQLDB implements VectorStore {
|
||||
|
||||
// Loaded dynamically: mysql2 is an optional peer dependency, so a static value import
|
||||
// would break `import { Memory } from "mem0ai/oss"` for everyone else.
|
||||
let createPool: typeof import("mysql2/promise").createPool;
|
||||
try {
|
||||
({ createPool } = await import("mysql2/promise"));
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The Azure MySQL vector store requires the 'mysql2' package. Install it with: npm install mysql2",
|
||||
);
|
||||
}
|
||||
const { createPool }: typeof import("mysql2/promise") = await loadPeer(
|
||||
"mysql2",
|
||||
"Azure MySQL vector store",
|
||||
() => import("mysql2/promise"),
|
||||
);
|
||||
|
||||
this.pool = createPool({
|
||||
host: this.config.host,
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
} from "@mochow/mochow-sdk-node";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
type MochowSdk = typeof import("@mochow/mochow-sdk-node");
|
||||
|
||||
@@ -156,14 +157,11 @@ export class BaiduDB implements VectorStore {
|
||||
// value import would break `import { Memory } from "mem0ai/oss"` for everyone else.
|
||||
private async loadSdk(): Promise<MochowSdk> {
|
||||
if (!this.sdk) {
|
||||
let module: MochowSdk & { default?: MochowSdk };
|
||||
try {
|
||||
module = await import("@mochow/mochow-sdk-node");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The Baidu vector store requires the '@mochow/mochow-sdk-node' package. Install it with: npm install @mochow/mochow-sdk-node",
|
||||
);
|
||||
}
|
||||
const module: MochowSdk & { default?: MochowSdk } = await loadPeer(
|
||||
"@mochow/mochow-sdk-node",
|
||||
"Baidu vector store",
|
||||
() => import("@mochow/mochow-sdk-node"),
|
||||
);
|
||||
this.sdk = module.default ?? module;
|
||||
}
|
||||
return this.sdk;
|
||||
@@ -455,7 +453,13 @@ export class BaiduDB implements VectorStore {
|
||||
return (response.rows ?? []).map((result) => ({
|
||||
id: String(result.row.id),
|
||||
payload: resultPayload(result.row),
|
||||
score: result.score,
|
||||
// L2 is a distance (lower = closer); the VectorStore contract wants higher = better.
|
||||
score:
|
||||
this.metricType === "L2"
|
||||
? result.score != null
|
||||
? 1 / (1 + result.score)
|
||||
: undefined
|
||||
: result.score,
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
const MIGRATION_ROW_ID = "mem0-user";
|
||||
const SAFE_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
||||
@@ -377,14 +378,11 @@ export class CassandraDB implements VectorStore {
|
||||
// Loaded dynamically: cassandra-driver is an optional peer dependency, so a static
|
||||
// value import would break `import { Memory } from "mem0ai/oss"` for everyone else.
|
||||
private async loadDriver(): Promise<any> {
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("cassandra-driver");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The 'cassandra-driver' package is required to use the Cassandra vector store. Install it with: npm install cassandra-driver",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"cassandra-driver",
|
||||
"Cassandra vector store",
|
||||
() => import("cassandra-driver"),
|
||||
);
|
||||
return sdk.default ?? sdk;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ChromaClient, CloudClient } from "chromadb";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface ChromaConfig extends VectorStoreConfig {
|
||||
/** Pre-configured ChromaDB client instance. */
|
||||
@@ -65,14 +66,11 @@ export class ChromaDB implements VectorStore {
|
||||
return config.client;
|
||||
}
|
||||
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("chromadb");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The 'chromadb' package is required to use the Chroma vector store. Install it with: npm install chromadb",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"chromadb",
|
||||
"Chroma vector store",
|
||||
() => import("chromadb"),
|
||||
);
|
||||
|
||||
if (config.apiKey && config.tenant) {
|
||||
return new sdk.CloudClient({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Client } from "@elastic/elasticsearch";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface ElasticsearchConfig extends VectorStoreConfig {
|
||||
/** Pre-configured Elasticsearch client instance (typed as `any` to keep the
|
||||
@@ -100,14 +101,11 @@ export class ElasticsearchDB implements VectorStore {
|
||||
params.headers = config.headers;
|
||||
}
|
||||
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("@elastic/elasticsearch");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The '@elastic/elasticsearch' package is required to use the Elasticsearch vector store. Install it with: npm install @elastic/elasticsearch",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"@elastic/elasticsearch",
|
||||
"Elasticsearch vector store",
|
||||
() => import("@elastic/elasticsearch"),
|
||||
);
|
||||
|
||||
this.client = new sdk.Client(params);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { VectorStore as LangchainVectorStoreInterface } from "@langchain/core/vectorstores";
|
||||
import { Document } from "@langchain/core/documents";
|
||||
import type { VectorStore as LangchainVectorStoreInterface } from "@langchain/core/vectorstores";
|
||||
import { VectorStore } from "./base"; // mem0's VectorStore interface
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
|
||||
@@ -77,6 +76,7 @@ export class LangchainVectorStore implements VectorStore {
|
||||
}
|
||||
|
||||
// Convert payloads to Langchain Document metadata format
|
||||
const { Document } = await import("@langchain/core/documents");
|
||||
const documents = payloads.map((payload, i) => {
|
||||
// Provide empty pageContent, store mem0 id and other data in metadata
|
||||
return new Document({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { MongoClient, Collection, Db } from "mongodb";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
export interface MongoDBConfig extends VectorStoreConfig {
|
||||
url?: string;
|
||||
@@ -42,14 +43,11 @@ export class MongoDB implements VectorStore {
|
||||
if (config.client) {
|
||||
this.client = config.client;
|
||||
} else {
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("mongodb");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The 'mongodb' package is required to use the MongoDB vector store. Install it with: npm install mongodb",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"mongodb",
|
||||
"MongoDB vector store",
|
||||
() => import("mongodb"),
|
||||
);
|
||||
const url = config.url || "mongodb://localhost:27017";
|
||||
this.client = new sdk.MongoClient(url, { appName: "Mem0" });
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Client } from "@opensearch-project/opensearch";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
type OpenSearchAuth =
|
||||
| {
|
||||
@@ -98,14 +99,11 @@ export class OpenSearchDB implements VectorStore {
|
||||
? { username: config.user, password: config.password }
|
||||
: undefined);
|
||||
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("@opensearch-project/opensearch");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The '@opensearch-project/opensearch' package is required to use the OpenSearch vector store. Install it with: npm install @opensearch-project/opensearch",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"@opensearch-project/opensearch",
|
||||
"OpenSearch vector store",
|
||||
() => import("@opensearch-project/opensearch"),
|
||||
);
|
||||
|
||||
this.client = new sdk.Client({
|
||||
node: `${useSSL ? "https" : "http"}://${host}:${port}`,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Pinecone, Index } from "@pinecone-database/pinecone";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
const MIGRATIONS_NAMESPACE = "__mem0_migrations__";
|
||||
const MIGRATIONS_RECORD_ID = "mem0-user-id";
|
||||
@@ -82,14 +83,11 @@ export class PineconeDB implements VectorStore {
|
||||
this.client = config.client;
|
||||
} else {
|
||||
const apiKey = config.apiKey || process.env.PINECONE_API_KEY;
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("@pinecone-database/pinecone");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The '@pinecone-database/pinecone' package is required to use the Pinecone vector store. Install it with: npm install @pinecone-database/pinecone",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"@pinecone-database/pinecone",
|
||||
"Pinecone vector store",
|
||||
() => import("@pinecone-database/pinecone"),
|
||||
);
|
||||
this.client = new sdk.Pinecone({ apiKey });
|
||||
}
|
||||
}
|
||||
@@ -318,6 +316,11 @@ export class PineconeDB implements VectorStore {
|
||||
}
|
||||
|
||||
async deleteCol(): Promise<void> {
|
||||
if (this.namespace) {
|
||||
await this.initialize();
|
||||
await this.namespacedIndex().deleteAll();
|
||||
return;
|
||||
}
|
||||
if (this._initPromise) {
|
||||
await this._initPromise.catch(() => {});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { QdrantClient } from "@qdrant/js-client-rest";
|
||||
import type { QdrantClient } from "@qdrant/js-client-rest";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
import * as fs from "fs";
|
||||
|
||||
interface QdrantConfig extends VectorStoreConfig {
|
||||
@@ -55,53 +56,64 @@ const KEY_MAP: Record<string, string> = {
|
||||
};
|
||||
|
||||
export class Qdrant implements VectorStore {
|
||||
private client: QdrantClient;
|
||||
private client!: QdrantClient;
|
||||
private readonly config: QdrantConfig;
|
||||
private readonly collectionName: string;
|
||||
private dimension: number;
|
||||
private _initPromise?: Promise<void>;
|
||||
|
||||
constructor(config: QdrantConfig) {
|
||||
if (config.client) {
|
||||
this.client = config.client;
|
||||
} else {
|
||||
const params: Record<string, any> = {};
|
||||
if (config.apiKey) {
|
||||
params.apiKey = config.apiKey;
|
||||
}
|
||||
if (config.url) {
|
||||
params.url = config.url;
|
||||
// Workaround for qdrant/qdrant-js#59: explicitly pass port to avoid "Illegal host" error
|
||||
try {
|
||||
const parsedUrl = new URL(config.url);
|
||||
params.port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : 6333;
|
||||
} catch (_) {
|
||||
params.port = 6333;
|
||||
}
|
||||
}
|
||||
if (config.host && config.port) {
|
||||
params.host = config.host;
|
||||
params.port = config.port;
|
||||
}
|
||||
if (!Object.keys(params).length) {
|
||||
params.path = config.path;
|
||||
if (!config.onDisk && config.path) {
|
||||
if (
|
||||
fs.existsSync(config.path) &&
|
||||
fs.statSync(config.path).isDirectory()
|
||||
) {
|
||||
fs.rmSync(config.path, { recursive: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.client = new QdrantClient(params);
|
||||
}
|
||||
|
||||
this.config = config;
|
||||
this.collectionName = config.collectionName;
|
||||
this.dimension = config.dimension || 1536; // Default OpenAI dimension
|
||||
this.initialize().catch(console.error);
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.client) return;
|
||||
const config = this.config;
|
||||
if (config.client) {
|
||||
this.client = config.client;
|
||||
return;
|
||||
}
|
||||
const params: Record<string, any> = {};
|
||||
if (config.apiKey) {
|
||||
params.apiKey = config.apiKey;
|
||||
}
|
||||
if (config.url) {
|
||||
params.url = config.url;
|
||||
// Workaround for qdrant/qdrant-js#59: explicitly pass port to avoid "Illegal host" error
|
||||
try {
|
||||
const parsedUrl = new URL(config.url);
|
||||
params.port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : 6333;
|
||||
} catch (_) {
|
||||
params.port = 6333;
|
||||
}
|
||||
}
|
||||
if (config.host && config.port) {
|
||||
params.host = config.host;
|
||||
params.port = config.port;
|
||||
}
|
||||
if (!Object.keys(params).length) {
|
||||
params.path = config.path;
|
||||
if (!config.onDisk && config.path) {
|
||||
if (
|
||||
fs.existsSync(config.path) &&
|
||||
fs.statSync(config.path).isDirectory()
|
||||
) {
|
||||
fs.rmSync(config.path, { recursive: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sdk = await loadPeer(
|
||||
"@qdrant/js-client-rest",
|
||||
"Qdrant vector store",
|
||||
() => import("@qdrant/js-client-rest"),
|
||||
);
|
||||
this.client = new sdk.QdrantClient(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a single field condition from a key-value filter pair.
|
||||
* Supports enhanced filter syntax with comparison operators.
|
||||
@@ -270,6 +282,7 @@ export class Qdrant implements VectorStore {
|
||||
ids: string[],
|
||||
payloads: Record<string, any>[],
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
const points = vectors.map((vector, idx) => ({
|
||||
id: ids[idx],
|
||||
vector: vector,
|
||||
@@ -290,6 +303,7 @@ export class Qdrant implements VectorStore {
|
||||
topK: number = 5,
|
||||
filters?: SearchFilters,
|
||||
): Promise<VectorStoreResult[]> {
|
||||
await this.initialize();
|
||||
const queryFilter = this.createFilter(filters);
|
||||
const results = await this.client.search(this.collectionName, {
|
||||
vector: query,
|
||||
@@ -305,6 +319,7 @@ export class Qdrant implements VectorStore {
|
||||
}
|
||||
|
||||
async get(vectorId: string): Promise<VectorStoreResult | null> {
|
||||
await this.initialize();
|
||||
const results = await this.client.retrieve(this.collectionName, {
|
||||
ids: [vectorId],
|
||||
with_payload: true,
|
||||
@@ -323,6 +338,7 @@ export class Qdrant implements VectorStore {
|
||||
vector: number[],
|
||||
payload: Record<string, any>,
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
const point = {
|
||||
id: vectorId,
|
||||
vector: vector,
|
||||
@@ -335,12 +351,14 @@ export class Qdrant implements VectorStore {
|
||||
}
|
||||
|
||||
async delete(vectorId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
await this.client.delete(this.collectionName, {
|
||||
points: [vectorId],
|
||||
});
|
||||
}
|
||||
|
||||
async deleteCol(): Promise<void> {
|
||||
await this.initialize();
|
||||
await this.client.deleteCollection(this.collectionName);
|
||||
}
|
||||
|
||||
@@ -348,6 +366,7 @@ export class Qdrant implements VectorStore {
|
||||
filters?: SearchFilters,
|
||||
topK: number = 100,
|
||||
): Promise<[VectorStoreResult[], number]> {
|
||||
await this.initialize();
|
||||
const scrollRequest = {
|
||||
limit: topK,
|
||||
filter: this.createFilter(filters),
|
||||
@@ -380,6 +399,7 @@ export class Qdrant implements VectorStore {
|
||||
}
|
||||
|
||||
async getUserId(): Promise<string> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// Ensure collection exists (idempotent — handles race conditions)
|
||||
await this.ensureCollection("memory_migrations", 1);
|
||||
@@ -417,6 +437,7 @@ export class Qdrant implements VectorStore {
|
||||
}
|
||||
|
||||
async setUserId(userId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// Get existing point ID
|
||||
const result = await this.client.scroll("memory_migrations", {
|
||||
@@ -496,6 +517,7 @@ export class Qdrant implements VectorStore {
|
||||
|
||||
private async _doInitialize(): Promise<void> {
|
||||
try {
|
||||
await this.ensureClient();
|
||||
await this.ensureCollection(this.collectionName, this.dimension);
|
||||
await this.ensureCollection("memory_migrations", 1);
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { createClient } from "redis";
|
||||
import type {
|
||||
RedisClientType,
|
||||
RedisDefaultModules,
|
||||
@@ -8,6 +7,7 @@ import type {
|
||||
} from "redis";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
/**
|
||||
* Escape RediSearch TAG filter special characters. Any punctuation in the
|
||||
@@ -146,15 +146,21 @@ function toCamelCase(obj: Record<string, any>): Record<string, any> {
|
||||
}
|
||||
|
||||
export class RedisDB implements VectorStore {
|
||||
private client: RedisClientType<
|
||||
private client!: RedisClientType<
|
||||
RedisDefaultModules & RedisModules & RedisFunctions & RedisScripts
|
||||
>;
|
||||
private readonly redisUrl: string;
|
||||
private readonly username?: string;
|
||||
private readonly password?: string;
|
||||
private readonly indexName: string;
|
||||
private readonly indexPrefix: string;
|
||||
private readonly schema: RedisSchema;
|
||||
private _initPromise?: Promise<void>;
|
||||
|
||||
constructor(config: RedisConfig) {
|
||||
this.redisUrl = config.redisUrl;
|
||||
this.username = config.username;
|
||||
this.password = config.password;
|
||||
this.indexName = config.collectionName;
|
||||
this.indexPrefix = `mem0:${config.collectionName}`;
|
||||
|
||||
@@ -177,12 +183,24 @@ export class RedisDB implements VectorStore {
|
||||
}),
|
||||
};
|
||||
|
||||
this.client = createClient({
|
||||
url: config.redisUrl,
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
this.initialize().catch((err) => {
|
||||
console.error("Failed to initialize Redis:", err);
|
||||
});
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.client) return;
|
||||
const sdk = await loadPeer(
|
||||
"redis",
|
||||
"Redis vector store",
|
||||
() => import("redis"),
|
||||
);
|
||||
this.client = sdk.createClient({
|
||||
url: this.redisUrl,
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
socket: {
|
||||
reconnectStrategy: (retries) => {
|
||||
reconnectStrategy: (retries: number) => {
|
||||
if (retries > 10) {
|
||||
console.error("Max reconnection attempts reached");
|
||||
return new Error("Max reconnection attempts reached");
|
||||
@@ -194,10 +212,6 @@ export class RedisDB implements VectorStore {
|
||||
|
||||
this.client.on("error", (err) => console.error("Redis Client Error:", err));
|
||||
this.client.on("connect", () => console.log("Redis Client Connected"));
|
||||
|
||||
this.initialize().catch((err) => {
|
||||
console.error("Failed to initialize Redis:", err);
|
||||
});
|
||||
}
|
||||
|
||||
private async createIndex(): Promise<void> {
|
||||
@@ -260,6 +274,7 @@ export class RedisDB implements VectorStore {
|
||||
}
|
||||
|
||||
private async _doInitialize(): Promise<void> {
|
||||
await this.ensureClient();
|
||||
try {
|
||||
await this.client.connect();
|
||||
console.log("Connected to Redis");
|
||||
@@ -331,6 +346,7 @@ export class RedisDB implements VectorStore {
|
||||
ids: string[],
|
||||
payloads: Record<string, any>[],
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
const data = vectors.map((vector, idx) => {
|
||||
const payload = toSnakeCase(payloads[idx]);
|
||||
const id = ids[idx];
|
||||
@@ -389,6 +405,7 @@ export class RedisDB implements VectorStore {
|
||||
topK: number = 5,
|
||||
filters?: SearchFilters,
|
||||
): Promise<VectorStoreResult[]> {
|
||||
await this.initialize();
|
||||
const snakeFilters = filters ? toSnakeCase(filters) : undefined;
|
||||
const filterExpr = snakeFilters
|
||||
? Object.entries(snakeFilters)
|
||||
@@ -456,6 +473,7 @@ export class RedisDB implements VectorStore {
|
||||
}
|
||||
|
||||
async get(vectorId: string): Promise<VectorStoreResult | null> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// Check if the memory exists first
|
||||
const exists = await this.client.exists(
|
||||
@@ -562,6 +580,7 @@ export class RedisDB implements VectorStore {
|
||||
vector: number[],
|
||||
payload: Record<string, any>,
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
const snakePayload = toSnakeCase(payload);
|
||||
const createdAt = snakePayload.created_at
|
||||
? new Date(snakePayload.created_at).getTime()
|
||||
@@ -601,6 +620,7 @@ export class RedisDB implements VectorStore {
|
||||
}
|
||||
|
||||
async delete(vectorId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// Check if memory exists first
|
||||
const key = `${this.indexPrefix}:${vectorId}`;
|
||||
@@ -626,6 +646,7 @@ export class RedisDB implements VectorStore {
|
||||
}
|
||||
|
||||
async deleteCol(): Promise<void> {
|
||||
await this.initialize();
|
||||
await this.client.ft.dropIndex(this.indexName);
|
||||
}
|
||||
|
||||
@@ -633,6 +654,7 @@ export class RedisDB implements VectorStore {
|
||||
filters?: SearchFilters,
|
||||
topK: number = 100,
|
||||
): Promise<[VectorStoreResult[], number]> {
|
||||
await this.initialize();
|
||||
const snakeFilters = filters ? toSnakeCase(filters) : undefined;
|
||||
const filterExpr = snakeFilters
|
||||
? Object.entries(snakeFilters)
|
||||
@@ -676,10 +698,11 @@ export class RedisDB implements VectorStore {
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
await this.client.quit();
|
||||
if (this.client) await this.client.quit();
|
||||
}
|
||||
|
||||
async getUserId(): Promise<string> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// Check if the user ID exists in Redis
|
||||
const userId = await this.client.get("memory_migrations:1");
|
||||
@@ -702,6 +725,7 @@ export class RedisDB implements VectorStore {
|
||||
}
|
||||
|
||||
async setUserId(userId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
await this.client.set("memory_migrations:1", userId);
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createClient, SupabaseClient } from "@supabase/supabase-js";
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface VectorData {
|
||||
id: string;
|
||||
@@ -82,14 +83,17 @@ $$;
|
||||
*/
|
||||
|
||||
export class SupabaseDB implements VectorStore {
|
||||
private client: SupabaseClient;
|
||||
private client!: SupabaseClient;
|
||||
private readonly supabaseUrl: string;
|
||||
private readonly supabaseKey: string;
|
||||
private readonly tableName: string;
|
||||
private readonly embeddingColumnName: string;
|
||||
private readonly metadataColumnName: string;
|
||||
private _initPromise?: Promise<void>;
|
||||
|
||||
constructor(config: SupabaseConfig) {
|
||||
this.client = createClient(config.supabaseUrl, config.supabaseKey);
|
||||
this.supabaseUrl = config.supabaseUrl;
|
||||
this.supabaseKey = config.supabaseKey;
|
||||
this.tableName = config.tableName;
|
||||
this.embeddingColumnName = config.embeddingColumnName || "embedding";
|
||||
this.metadataColumnName = config.metadataColumnName || "metadata";
|
||||
@@ -99,6 +103,16 @@ export class SupabaseDB implements VectorStore {
|
||||
});
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.client) return;
|
||||
const sdk = await loadPeer(
|
||||
"@supabase/supabase-js",
|
||||
"Supabase vector store",
|
||||
() => import("@supabase/supabase-js"),
|
||||
);
|
||||
this.client = sdk.createClient(this.supabaseUrl, this.supabaseKey);
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
if (!this._initPromise) {
|
||||
this._initPromise = this._doInitialize();
|
||||
@@ -107,6 +121,7 @@ export class SupabaseDB implements VectorStore {
|
||||
}
|
||||
|
||||
private async _doInitialize(): Promise<void> {
|
||||
await this.ensureClient();
|
||||
try {
|
||||
// Verify table exists and vector operations work by attempting a test insert
|
||||
const testVector = Array(1536).fill(0);
|
||||
@@ -209,6 +224,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
ids: string[],
|
||||
payloads: Record<string, any>[],
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const data = vectors.map((vector, idx) => ({
|
||||
id: ids[idx],
|
||||
@@ -237,6 +253,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
topK: number = 5,
|
||||
filters?: SearchFilters,
|
||||
): Promise<VectorStoreResult[]> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const rpcQuery: VectorQueryParams = {
|
||||
query_embedding: query,
|
||||
@@ -265,6 +282,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
}
|
||||
|
||||
async get(vectorId: string): Promise<VectorStoreResult | null> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const { data, error } = await this.client
|
||||
.from(this.tableName)
|
||||
@@ -290,6 +308,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
vector: number[],
|
||||
payload: Record<string, any>,
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const { error } = await this.client
|
||||
.from(this.tableName)
|
||||
@@ -310,6 +329,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
}
|
||||
|
||||
async delete(vectorId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const { error } = await this.client
|
||||
.from(this.tableName)
|
||||
@@ -324,6 +344,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
}
|
||||
|
||||
async deleteCol(): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const { error } = await this.client
|
||||
.from(this.tableName)
|
||||
@@ -341,6 +362,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
filters?: SearchFilters,
|
||||
topK: number = 100,
|
||||
): Promise<[VectorStoreResult[], number]> {
|
||||
await this.initialize();
|
||||
try {
|
||||
let query = this.client
|
||||
.from(this.tableName)
|
||||
@@ -370,6 +392,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
}
|
||||
|
||||
async getUserId(): Promise<string> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// First check if the table exists
|
||||
const { data: tableExists } = await this.client
|
||||
@@ -421,6 +444,7 @@ See the SQL migration instructions in the code comments.`,
|
||||
}
|
||||
|
||||
async setUserId(userId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const { error: deleteError } = await this.client
|
||||
.from("memory_migrations")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface TurbopufferConfig extends VectorStoreConfig {
|
||||
apiKey?: string;
|
||||
@@ -48,14 +49,11 @@ export class TurbopufferDB implements VectorStore {
|
||||
}
|
||||
|
||||
private async createClient(): Promise<any> {
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("@turbopuffer/turbopuffer");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The '@turbopuffer/turbopuffer' package is required to use the Turbopuffer vector store. Install it with: npm install @turbopuffer/turbopuffer",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"@turbopuffer/turbopuffer",
|
||||
"Turbopuffer vector store",
|
||||
() => import("@turbopuffer/turbopuffer"),
|
||||
);
|
||||
|
||||
// @turbopuffer/turbopuffer ships `Turbopuffer` as both the default export
|
||||
// and a named export pointing at the same class. Use `.default` since
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Index, QueryResult, Vector } from "@upstash/vector";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface UpstashVectorConfig extends VectorStoreConfig {
|
||||
collectionName: string;
|
||||
@@ -42,14 +43,11 @@ export class UpstashVector implements VectorStore {
|
||||
if (config.client) {
|
||||
this.client = config.client;
|
||||
} else {
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("@upstash/vector");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The '@upstash/vector' package is required to use the Upstash Vector store. Install it with: npm install @upstash/vector",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"@upstash/vector",
|
||||
"Upstash Vector store",
|
||||
() => import("@upstash/vector"),
|
||||
);
|
||||
this.client = new sdk.Index({
|
||||
url: config.url,
|
||||
token: config.token,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreResult } from "../types";
|
||||
import { ValkeyConfig } from "../types/valkey";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface ValkeyClient {
|
||||
call: (...args: (string | number | Buffer)[]) => Promise<unknown>;
|
||||
@@ -142,14 +143,8 @@ function formatTimestamp(timestamp: number, timezone: string = "UTC"): string {
|
||||
return `${yyyy}-${MM}-${dd}T${HH}:${mm}:${ss}${sign}${offHH}:${offMM}`;
|
||||
}
|
||||
|
||||
async function loadIovalkey(): Promise<typeof import("iovalkey")> {
|
||||
try {
|
||||
return await import("iovalkey");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"iovalkey is required for the Valkey vector store. Install it with: npm install iovalkey",
|
||||
);
|
||||
}
|
||||
function loadIovalkey(): Promise<typeof import("iovalkey")> {
|
||||
return loadPeer("iovalkey", "Valkey vector store", () => import("iovalkey"));
|
||||
}
|
||||
|
||||
export class ValkeyDB implements VectorStore {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Cloudflare from "cloudflare";
|
||||
import type Cloudflare from "cloudflare";
|
||||
import type { Vectorize, VectorizeVector } from "@cloudflare/workers-types";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface VectorizeConfig extends VectorStoreConfig {
|
||||
apiKey?: string;
|
||||
@@ -17,24 +18,36 @@ interface CloudflareVector {
|
||||
|
||||
export class VectorizeDB implements VectorStore {
|
||||
private client: Cloudflare | null = null;
|
||||
private apiKey?: string;
|
||||
private dimensions: number;
|
||||
private indexName: string;
|
||||
private accountId: string;
|
||||
private _initPromise?: Promise<void>;
|
||||
|
||||
constructor(config: VectorizeConfig) {
|
||||
this.client = new Cloudflare({ apiToken: config.apiKey });
|
||||
this.apiKey = config.apiKey;
|
||||
this.dimensions = config.dimension || 1536;
|
||||
this.indexName = config.indexName;
|
||||
this.accountId = config.accountId;
|
||||
this.initialize().catch(console.error);
|
||||
}
|
||||
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this.client) return;
|
||||
const sdk = await loadPeer(
|
||||
"cloudflare",
|
||||
"Vectorize vector store",
|
||||
() => import("cloudflare"),
|
||||
);
|
||||
this.client = new sdk.default({ apiToken: this.apiKey });
|
||||
}
|
||||
|
||||
async insert(
|
||||
vectors: number[][],
|
||||
ids: string[],
|
||||
payloads: Record<string, any>[],
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const vectorObjects: CloudflareVector[] = vectors.map(
|
||||
(vector, index) => ({
|
||||
@@ -83,6 +96,7 @@ export class VectorizeDB implements VectorStore {
|
||||
topK: number = 5,
|
||||
filters?: SearchFilters,
|
||||
): Promise<VectorStoreResult[]> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const result = await this.client?.vectorize.indexes.query(
|
||||
this.indexName,
|
||||
@@ -111,6 +125,7 @@ export class VectorizeDB implements VectorStore {
|
||||
}
|
||||
|
||||
async get(vectorId: string): Promise<VectorStoreResult | null> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const result = (await this.client?.vectorize.indexes.getByIds(
|
||||
this.indexName,
|
||||
@@ -139,6 +154,7 @@ export class VectorizeDB implements VectorStore {
|
||||
vector: number[],
|
||||
payload: Record<string, any>,
|
||||
): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const data: VectorizeVector = {
|
||||
id: vectorId,
|
||||
@@ -173,6 +189,7 @@ export class VectorizeDB implements VectorStore {
|
||||
}
|
||||
|
||||
async delete(vectorId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
await this.client?.vectorize.indexes.deleteByIds(this.indexName, {
|
||||
account_id: this.accountId,
|
||||
@@ -187,6 +204,7 @@ export class VectorizeDB implements VectorStore {
|
||||
}
|
||||
|
||||
async deleteCol(): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
await this.client?.vectorize.indexes.delete(this.indexName, {
|
||||
account_id: this.accountId,
|
||||
@@ -203,6 +221,7 @@ export class VectorizeDB implements VectorStore {
|
||||
filters?: SearchFilters,
|
||||
topK: number = 20,
|
||||
): Promise<[VectorStoreResult[], number]> {
|
||||
await this.initialize();
|
||||
try {
|
||||
const result = await this.client?.vectorize.indexes.query(
|
||||
this.indexName,
|
||||
@@ -243,6 +262,7 @@ export class VectorizeDB implements VectorStore {
|
||||
}
|
||||
|
||||
async getUserId(): Promise<string> {
|
||||
await this.initialize();
|
||||
try {
|
||||
let found = false;
|
||||
for await (const index of this.client!.vectorize.indexes.list({
|
||||
@@ -309,6 +329,7 @@ export class VectorizeDB implements VectorStore {
|
||||
}
|
||||
|
||||
async setUserId(userId: string): Promise<void> {
|
||||
await this.initialize();
|
||||
try {
|
||||
// Get existing point ID
|
||||
const result: any = await this.client?.vectorize.indexes.query(
|
||||
@@ -355,6 +376,7 @@ export class VectorizeDB implements VectorStore {
|
||||
}
|
||||
|
||||
private async _doInitialize(): Promise<void> {
|
||||
await this.ensureClient();
|
||||
try {
|
||||
// Check if the index already exists
|
||||
let indexFound = false;
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { WeaviateClient } from "weaviate-client";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { VectorStore } from "./base";
|
||||
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
|
||||
import { loadPeer } from "../utils/load_peer";
|
||||
|
||||
interface WeaviateConfig extends VectorStoreConfig {
|
||||
/** Pre-configured Weaviate client instance (typed as `any` to keep the
|
||||
@@ -50,14 +51,11 @@ export class WeaviateDB implements VectorStore {
|
||||
private async ensureClient(): Promise<void> {
|
||||
if (this._client) return;
|
||||
|
||||
let sdk: any;
|
||||
try {
|
||||
sdk = await import("weaviate-client");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"The 'weaviate-client' package is required to use the Weaviate vector store. Install it with: npm install weaviate-client",
|
||||
);
|
||||
}
|
||||
const sdk = await loadPeer(
|
||||
"weaviate-client",
|
||||
"Weaviate vector store",
|
||||
() => import("weaviate-client"),
|
||||
);
|
||||
this._sdk = sdk;
|
||||
|
||||
const { client, clusterUrl, apiKey, additionalHeaders } = this._config;
|
||||
|
||||
@@ -23,11 +23,16 @@ describe("AnthropicLLM (unit)", () => {
|
||||
|
||||
// Regression #5665: a configured baseURL must reach the Anthropic client so
|
||||
// proxy/gateway users are not silently bypassed (TS parity with #5626).
|
||||
it("forwards baseURL to the Anthropic client when set", () => {
|
||||
new AnthropicLLM({
|
||||
// The client is constructed lazily on first use, so drive generateResponse.
|
||||
it("forwards baseURL to the Anthropic client when set", async () => {
|
||||
mockCreate.mockResolvedValueOnce({
|
||||
content: [{ type: "text", text: "ok" }],
|
||||
});
|
||||
const llm = new AnthropicLLM({
|
||||
apiKey: "test-key",
|
||||
baseURL: "https://proxy.example/v1",
|
||||
});
|
||||
await llm.generateResponse([{ role: "user", content: "Hi" }]);
|
||||
|
||||
expect(mockConstructor).toHaveBeenCalledTimes(1);
|
||||
const ctorArgs = mockConstructor.mock.calls[0][0];
|
||||
@@ -37,8 +42,12 @@ describe("AnthropicLLM (unit)", () => {
|
||||
|
||||
// When no baseURL is configured the client must not receive a baseURL key
|
||||
// (so the SDK default endpoint is used).
|
||||
it("does NOT set baseURL when none is configured", () => {
|
||||
new AnthropicLLM({ apiKey: "test-key" });
|
||||
it("does NOT set baseURL when none is configured", async () => {
|
||||
mockCreate.mockResolvedValueOnce({
|
||||
content: [{ type: "text", text: "ok" }],
|
||||
});
|
||||
const llm = new AnthropicLLM({ apiKey: "test-key" });
|
||||
await llm.generateResponse([{ role: "user", content: "Hi" }]);
|
||||
|
||||
expect(mockConstructor).toHaveBeenCalledTimes(1);
|
||||
const ctorArgs = mockConstructor.mock.calls[0][0];
|
||||
|
||||
@@ -431,9 +431,12 @@ describe("BaiduDB reads", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const results = await makeStore(client).search([1, 2, 3], 5, {
|
||||
userId: "alice",
|
||||
});
|
||||
// Non-L2 metrics already return a higher-is-better score and pass through untouched.
|
||||
const results = await makeStore(client, { metricType: "COSINE" }).search(
|
||||
[1, 2, 3],
|
||||
5,
|
||||
{ userId: "alice" },
|
||||
);
|
||||
expect(results).toEqual([{ id: "m1", payload: { data: "x" }, score: 0.8 }]);
|
||||
|
||||
const { request } = client.vectorSearch.mock.calls[0][0];
|
||||
@@ -445,6 +448,35 @@ describe("BaiduDB reads", () => {
|
||||
expect(request.config.params).toEqual({ ef: 200 });
|
||||
});
|
||||
|
||||
it("converts an L2 distance into a similarity score (higher = better)", async () => {
|
||||
// Mirrors the Python provider (#6435): 1 / (1 + distance), so closer scores higher.
|
||||
const client = fakeClient();
|
||||
client.vectorSearch.mockResolvedValue({
|
||||
...OK,
|
||||
rows: [
|
||||
{ row: { id: "near", metadata: {} }, score: 0.5 },
|
||||
{ row: { id: "far", metadata: {} }, score: 2.0 },
|
||||
],
|
||||
});
|
||||
|
||||
const results = await makeStore(client).search([1, 2, 3], 2);
|
||||
|
||||
expect(results[0].score).toBeCloseTo(1 / 1.5, 10);
|
||||
expect(results[1].score).toBeCloseTo(1 / 3.0, 10);
|
||||
});
|
||||
|
||||
it("leaves an unscored L2 row's score undefined instead of treating it as the closest match", async () => {
|
||||
const client = fakeClient();
|
||||
client.vectorSearch.mockResolvedValue({
|
||||
...OK,
|
||||
rows: [{ row: { id: "unscored", metadata: {} } }],
|
||||
});
|
||||
|
||||
const results = await makeStore(client).search([1, 2, 3], 1);
|
||||
|
||||
expect(results[0].score).toBeUndefined();
|
||||
});
|
||||
|
||||
it("omits the filter when no filters are supplied", async () => {
|
||||
const client = fakeClient();
|
||||
client.vectorSearch.mockResolvedValue({ ...OK, rows: [] });
|
||||
|
||||
@@ -207,6 +207,79 @@ describe("Memory - update()", () => {
|
||||
expect.objectContaining({ category: "hobbies", priority: "high" }),
|
||||
);
|
||||
});
|
||||
|
||||
// Regression: metadata passed to update() must never overwrite a memory's
|
||||
// identity fields (issues #6277 / #6278).
|
||||
test("metadata cannot overwrite identity fields (tenant isolation)", async () => {
|
||||
const tenantA = `tenant_a_${Date.now()}`;
|
||||
const tenantB = `tenant_b_${Date.now()}`;
|
||||
const addResult: SearchResult = await memory.add("Tenant A secret", {
|
||||
userId: tenantA,
|
||||
infer: false,
|
||||
});
|
||||
const id = addResult.results[0].id;
|
||||
|
||||
// Caller metadata attempts to re-scope the memory to tenant B.
|
||||
await memory.update(id, {
|
||||
text: "Updated text",
|
||||
metadata: { user_id: tenantB, agent_id: "attacker", run_id: "attacker" },
|
||||
});
|
||||
|
||||
// The memory must remain in tenant A's scope...
|
||||
const aList: SearchResult = await memory.getAll({
|
||||
filters: { user_id: tenantA },
|
||||
});
|
||||
expect(aList.results.map((m) => m.id)).toContain(id);
|
||||
|
||||
// ...and must never leak into tenant B's scope.
|
||||
const bList: SearchResult = await memory.getAll({
|
||||
filters: { user_id: tenantB },
|
||||
});
|
||||
expect(bList.results.map((m) => m.id)).not.toContain(id);
|
||||
});
|
||||
|
||||
// A memory created with only some identity fields (e.g. run_id only) must not
|
||||
// let update() metadata inject a brand-new identity key. The default vector
|
||||
// store promotes camelCase aliases to snake_case on read, so both casings must be covered.
|
||||
test("metadata cannot inject an identity field on update (snake_case or camelCase)", async () => {
|
||||
const runId = `run_only_${Date.now()}`;
|
||||
const attacker = `attacker_${Date.now()}`;
|
||||
const addResult: SearchResult = await memory.add("Run-scoped secret", {
|
||||
runId,
|
||||
infer: false,
|
||||
});
|
||||
const id = addResult.results[0].id;
|
||||
|
||||
// Memory has no user_id/agent_id/actor_id — metadata tries to inject them,
|
||||
// in both snake_case and camelCase.
|
||||
await memory.update(id, {
|
||||
text: "Updated text",
|
||||
metadata: {
|
||||
user_id: attacker,
|
||||
agent_id: attacker,
|
||||
actor_id: attacker,
|
||||
userId: attacker,
|
||||
agentId: attacker,
|
||||
},
|
||||
});
|
||||
|
||||
// Still reachable under its original run_id scope...
|
||||
const runList: SearchResult = await memory.getAll({
|
||||
filters: { run_id: runId },
|
||||
});
|
||||
expect(runList.results.map((m) => m.id)).toContain(id);
|
||||
|
||||
// ...and the injected identity scopes must not resolve to it.
|
||||
const userList: SearchResult = await memory.getAll({
|
||||
filters: { user_id: attacker },
|
||||
});
|
||||
expect(userList.results.map((m) => m.id)).not.toContain(id);
|
||||
|
||||
const agentList: SearchResult = await memory.getAll({
|
||||
filters: { agent_id: attacker },
|
||||
});
|
||||
expect(agentList.results.map((m) => m.id)).not.toContain(id);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── update() options: text / data / metadata / expirationDate ───
|
||||
|
||||
@@ -253,6 +253,34 @@ describe("Memory Input Validation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("non-string entity ID coercion", () => {
|
||||
it("coerces an integer user_id in getAll filters to its string form", async () => {
|
||||
const listSpy = jest
|
||||
.spyOn((memory as any).vectorStore, "list")
|
||||
.mockResolvedValue([[], 0]);
|
||||
|
||||
await memory.getAll({ filters: { user_id: 42 as any } });
|
||||
|
||||
const passedFilters = listSpy.mock.calls[0][0] as Record<string, any>;
|
||||
expect(passedFilters.user_id).toBe("42");
|
||||
|
||||
listSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("coerces an integer user_id in search filters to its string form", async () => {
|
||||
const searchSpy = jest
|
||||
.spyOn((memory as any).vectorStore, "search")
|
||||
.mockResolvedValue([]);
|
||||
|
||||
await memory.search("q", { filters: { user_id: 42 as any } });
|
||||
|
||||
const passedFilters = searchSpy.mock.calls[0][2] as Record<string, any>;
|
||||
expect(passedFilters.user_id).toBe("42");
|
||||
|
||||
searchSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("search() filter entity ID validation", () => {
|
||||
it("should throw error when user_id in filters is whitespace-only", async () => {
|
||||
await expect(
|
||||
|
||||
@@ -22,7 +22,16 @@ function sourceFiles(dir: string, acc: string[] = []): string[] {
|
||||
for (const entry of readdirSync(dir)) {
|
||||
const full = join(dir, entry);
|
||||
if (statSync(full).isDirectory()) {
|
||||
if (entry !== "tests" && entry !== "__tests__") sourceFiles(full, acc);
|
||||
// examples/ are dev scripts and community/ is the separate @mem0/community
|
||||
// package — neither ships in files:["dist"] nor is reachable via the mem0ai/oss
|
||||
// barrel, so a static import there cannot crash a Memory() consumer.
|
||||
if (
|
||||
entry !== "tests" &&
|
||||
entry !== "__tests__" &&
|
||||
entry !== "examples" &&
|
||||
entry !== "community"
|
||||
)
|
||||
sourceFiles(full, acc);
|
||||
} else if (entry.endsWith(".ts") && !entry.endsWith(".test.ts")) {
|
||||
acc.push(full);
|
||||
}
|
||||
|
||||
@@ -40,14 +40,15 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("Qdrant URL port extraction (qdrant/qdrant-js#59 workaround)", () => {
|
||||
it("extracts port from HTTPS URL with explicit port", () => {
|
||||
new Qdrant({
|
||||
it("extracts port from HTTPS URL with explicit port", async () => {
|
||||
const store = new Qdrant({
|
||||
url: "https://my-cluster.us-west-1-0.aws.cloud.qdrant.io:6333",
|
||||
apiKey: "test-key",
|
||||
collectionName: "test",
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
await store.initialize();
|
||||
|
||||
expect(capturedParams).toBeDefined();
|
||||
expect(capturedParams!.url).toBe(
|
||||
@@ -57,47 +58,50 @@ describe("Qdrant URL port extraction (qdrant/qdrant-js#59 workaround)", () => {
|
||||
expect(capturedParams!.apiKey).toBe("test-key");
|
||||
});
|
||||
|
||||
it("extracts port from HTTP URL with explicit port", () => {
|
||||
new Qdrant({
|
||||
it("extracts port from HTTP URL with explicit port", async () => {
|
||||
const store = new Qdrant({
|
||||
url: "http://localhost:6333",
|
||||
collectionName: "test",
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
await store.initialize();
|
||||
|
||||
expect(capturedParams).toBeDefined();
|
||||
expect(capturedParams!.url).toBe("http://localhost:6333");
|
||||
expect(capturedParams!.port).toBe(6333);
|
||||
});
|
||||
|
||||
it("defaults to port 6333 when HTTPS URL has no explicit port", () => {
|
||||
new Qdrant({
|
||||
it("defaults to port 6333 when HTTPS URL has no explicit port", async () => {
|
||||
const store = new Qdrant({
|
||||
url: "https://my-cluster.cloud.qdrant.io",
|
||||
apiKey: "test-key",
|
||||
collectionName: "test",
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
await store.initialize();
|
||||
|
||||
expect(capturedParams).toBeDefined();
|
||||
expect(capturedParams!.url).toBe("https://my-cluster.cloud.qdrant.io");
|
||||
expect(capturedParams!.port).toBe(6333);
|
||||
});
|
||||
|
||||
it("defaults to port 6333 when HTTP URL has no explicit port", () => {
|
||||
new Qdrant({
|
||||
it("defaults to port 6333 when HTTP URL has no explicit port", async () => {
|
||||
const store = new Qdrant({
|
||||
url: "http://localhost",
|
||||
collectionName: "test",
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
await store.initialize();
|
||||
|
||||
expect(capturedParams).toBeDefined();
|
||||
expect(capturedParams!.port).toBe(6333);
|
||||
});
|
||||
|
||||
it("host+port config overrides URL-extracted port", () => {
|
||||
new Qdrant({
|
||||
it("host+port config overrides URL-extracted port", async () => {
|
||||
const store = new Qdrant({
|
||||
url: "https://my-cluster.cloud.qdrant.io:6333",
|
||||
host: "custom-host",
|
||||
port: 9999,
|
||||
@@ -106,28 +110,28 @@ describe("Qdrant URL port extraction (qdrant/qdrant-js#59 workaround)", () => {
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
await store.initialize();
|
||||
|
||||
expect(capturedParams).toBeDefined();
|
||||
expect(capturedParams!.host).toBe("custom-host");
|
||||
expect(capturedParams!.port).toBe(9999);
|
||||
});
|
||||
|
||||
it("handles invalid URL gracefully without crashing", () => {
|
||||
expect(() => {
|
||||
new Qdrant({
|
||||
url: "not-a-valid-url",
|
||||
collectionName: "test",
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
}).not.toThrow();
|
||||
it("handles invalid URL gracefully without crashing", async () => {
|
||||
const store = new Qdrant({
|
||||
url: "not-a-valid-url",
|
||||
collectionName: "test",
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
await expect(store.initialize()).resolves.not.toThrow();
|
||||
|
||||
expect(capturedParams).toBeDefined();
|
||||
expect(capturedParams!.url).toBe("not-a-valid-url");
|
||||
expect(capturedParams!.port).toBe(6333);
|
||||
});
|
||||
|
||||
it("does not pass port when using pre-configured client", () => {
|
||||
it("does not pass port when using pre-configured client", async () => {
|
||||
const mockClient: any = {
|
||||
createCollection: jest.fn().mockResolvedValue(undefined),
|
||||
getCollection: jest.fn().mockResolvedValue({
|
||||
@@ -141,12 +145,13 @@ describe("Qdrant URL port extraction (qdrant/qdrant-js#59 workaround)", () => {
|
||||
deleteCollection: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
new Qdrant({
|
||||
const store = new Qdrant({
|
||||
client: mockClient,
|
||||
collectionName: "test",
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
await store.initialize();
|
||||
|
||||
// QdrantClient constructor should NOT have been called
|
||||
expect(
|
||||
@@ -154,14 +159,15 @@ describe("Qdrant URL port extraction (qdrant/qdrant-js#59 workaround)", () => {
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("defaults to 6333 when HTTPS URL uses default port 443", () => {
|
||||
new Qdrant({
|
||||
it("defaults to 6333 when HTTPS URL uses default port 443", async () => {
|
||||
const store = new Qdrant({
|
||||
url: "https://my-cluster.cloud.qdrant.io:443",
|
||||
apiKey: "test-key",
|
||||
collectionName: "test",
|
||||
embeddingModelDims: 768,
|
||||
dimension: 768,
|
||||
});
|
||||
await store.initialize();
|
||||
|
||||
// 443 is default for HTTPS, so URL.port returns empty string — we default to 6333
|
||||
expect(capturedParams).toBeDefined();
|
||||
|
||||
@@ -149,4 +149,11 @@ class AnthropicLLM(LLMBase):
|
||||
elif block.type == "tool_use":
|
||||
result["tool_calls"].append({"name": block.name, "arguments": block.input})
|
||||
return result
|
||||
return response.content[0].text
|
||||
|
||||
# Thinking-enabled responses put a thinking block before the text
|
||||
# block, and a response can carry no text block at all, so find the
|
||||
# text block like the tools branch above instead of indexing content[0].
|
||||
for block in response.content:
|
||||
if block.type == "text":
|
||||
return block.text
|
||||
return ""
|
||||
|
||||
@@ -35,11 +35,6 @@ class LLMBase(ABC):
|
||||
if not hasattr(self.config, "model"):
|
||||
raise ValueError("Configuration must have a 'model' attribute")
|
||||
|
||||
if not hasattr(self.config, "api_key") and not hasattr(self.config, "api_key"):
|
||||
# Check if API key is available via environment variable
|
||||
# This will be handled by individual providers
|
||||
pass
|
||||
|
||||
def _is_reasoning_model(self, model: str) -> bool:
|
||||
"""
|
||||
Check if the model is a reasoning model or GPT-5 series that doesn't support certain parameters.
|
||||
|
||||
+20
-10
@@ -134,6 +134,20 @@ _SENSITIVE_SUFFIXES = (
|
||||
# Entity parameters that must be passed via filters, not top-level kwargs
|
||||
ENTITY_PARAMS = frozenset({"user_id", "agent_id", "run_id"})
|
||||
|
||||
# Tenant-scoping fields that update() must never let caller-supplied metadata overwrite (issues #4490, #6277).
|
||||
_IDENTITY_KEYS = ENTITY_PARAMS | {"actor_id"}
|
||||
|
||||
|
||||
def _strip_identity_keys(metadata: Dict[str, Any], existing_payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Drop identity keys from caller metadata; they are immutable after creation (issues #4490, #6277)."""
|
||||
clean = {}
|
||||
for key, value in metadata.items():
|
||||
if key not in _IDENTITY_KEYS:
|
||||
clean[key] = value
|
||||
elif value != existing_payload.get(key):
|
||||
logger.warning(f"update(): ignoring metadata['{key}'] - identity fields are immutable after creation")
|
||||
return clean
|
||||
|
||||
|
||||
def _reject_top_level_entity_params(kwargs: Dict[str, Any], method_name: str) -> None:
|
||||
"""Reject top-level entity parameters - must use filters instead."""
|
||||
@@ -1783,6 +1797,8 @@ class Memory(MemoryBase):
|
||||
memory_id (str): ID of the memory to update.
|
||||
text (str, optional): New content to update the memory with.
|
||||
metadata (dict, optional): Metadata to update with the memory. Defaults to None.
|
||||
``user_id``/``agent_id``/``run_id``/``actor_id`` are ignored here - they are
|
||||
immutable after creation.
|
||||
expiration_date (Any, optional): Date in YYYY-MM-DD format, or None to clear it.
|
||||
data (str, optional): Deprecated alias for ``text``. Will be removed in the next
|
||||
major release; use ``text`` instead.
|
||||
@@ -1991,7 +2007,7 @@ class Memory(MemoryBase):
|
||||
|
||||
new_metadata = deepcopy(existing_memory.payload)
|
||||
if metadata is not None:
|
||||
new_metadata.update(metadata)
|
||||
new_metadata.update(_strip_identity_keys(metadata, existing_memory.payload))
|
||||
|
||||
new_metadata["data"] = data
|
||||
new_metadata["hash"] = hashlib.md5(data.encode()).hexdigest()
|
||||
@@ -1999,10 +2015,6 @@ class Memory(MemoryBase):
|
||||
new_metadata["created_at"] = existing_memory.payload.get("created_at")
|
||||
new_metadata["updated_at"] = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
# actor_id is immutable after creation (issue #4490)
|
||||
if "actor_id" in existing_memory.payload:
|
||||
new_metadata["actor_id"] = existing_memory.payload["actor_id"]
|
||||
|
||||
if data in existing_embeddings:
|
||||
embeddings = existing_embeddings[data]
|
||||
else:
|
||||
@@ -3414,6 +3426,8 @@ class AsyncMemory(MemoryBase):
|
||||
memory_id (str): ID of the memory to update.
|
||||
text (str, optional): New content to update the memory with.
|
||||
metadata (dict, optional): Metadata to update with the memory. Defaults to None.
|
||||
``user_id``/``agent_id``/``run_id``/``actor_id`` are ignored here - they are
|
||||
immutable after creation.
|
||||
expiration_date (Any, optional): Date in YYYY-MM-DD format, or None to clear it.
|
||||
data (str, optional): Deprecated alias for ``text``. Will be removed in the next
|
||||
major release; use ``text`` instead.
|
||||
@@ -3657,7 +3671,7 @@ class AsyncMemory(MemoryBase):
|
||||
|
||||
new_metadata = deepcopy(existing_memory.payload)
|
||||
if metadata is not None:
|
||||
new_metadata.update(metadata)
|
||||
new_metadata.update(_strip_identity_keys(metadata, existing_memory.payload))
|
||||
|
||||
new_metadata["data"] = data
|
||||
new_metadata["hash"] = hashlib.md5(data.encode()).hexdigest()
|
||||
@@ -3665,10 +3679,6 @@ class AsyncMemory(MemoryBase):
|
||||
new_metadata["created_at"] = existing_memory.payload.get("created_at")
|
||||
new_metadata["updated_at"] = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
# actor_id is immutable after creation (issue #4490)
|
||||
if "actor_id" in existing_memory.payload:
|
||||
new_metadata["actor_id"] = existing_memory.payload["actor_id"]
|
||||
|
||||
if data in existing_embeddings:
|
||||
embeddings = existing_embeddings[data]
|
||||
else:
|
||||
|
||||
@@ -224,8 +224,15 @@ class BaiduDB(VectorStoreBase):
|
||||
output = []
|
||||
for row in res.rows:
|
||||
row_data = row.get("row", {})
|
||||
# Mochow returns the raw L2 distance (lower = closer). Convert it to a
|
||||
# similarity score (higher = better) to satisfy the VectorStoreBase
|
||||
# contract, mirroring the milvus provider. Non-L2 metrics already
|
||||
# return a higher-is-better score.
|
||||
raw_score = row.get("score", 0.0)
|
||||
if self.metric_type in (MetricType.L2, "L2"):
|
||||
raw_score = 1.0 / (1.0 + raw_score)
|
||||
output_data = OutputData(
|
||||
id=row_data.get("id"), score=row.get("score", 0.0), payload=row_data.get("metadata", {})
|
||||
id=row_data.get("id"), score=raw_score, payload=row_data.get("metadata", {})
|
||||
)
|
||||
output.append(output_data)
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user