### MenteDB Python SDK Quick Start Source: https://github.com/nambok/mentedb/blob/main/sdks/python/README.md A quick start guide demonstrating basic MenteDB operations using the Python SDK. This includes storing, recalling, searching, relating, and forgetting memories. ```python from mentedb import MenteDB, MemoryType, EdgeType with MenteDB("./agent-memory") as db: # Store a memory mid = db.store( "The deployment failed because the config was missing", memory_type=MemoryType.EPISODIC, tags=["deployment", "config"], ) # Recall memories with MQL result = db.recall("RECALL tag:deployment LIMIT 5") print(result.text) # Vector similarity search hits = db.search(embedding=[0.1] * 384, k=5) for hit in hits: print(f"{hit.id}: {hit.score:.4f}") # Relate memories mid2 = db.store("Always validate config before deploy", memory_type=MemoryType.PROCEDURAL) db.relate(mid, mid2, edge_type=EdgeType.CAUSED) # Forget a memory db.forget(mid) ``` -------------------------------- ### Install Rust Toolchain Source: https://github.com/nambok/mentedb/blob/main/CONTRIBUTING.md Commands to install the required Rust stable toolchain and necessary components. ```bash rustup toolchain install stable rustup component add rustfmt clippy ``` -------------------------------- ### Install MenteDB Python SDK from source Source: https://github.com/nambok/mentedb/blob/main/sdks/python/README.md Install the MenteDB Python SDK for development purposes by building from source. Ensure you have maturin installed. ```bash cd sdks/python pip install maturin maturin develop ``` -------------------------------- ### Install Dependencies and Build SDK Source: https://github.com/nambok/mentedb/blob/main/benchmarks/longmemeval/README.md Installs necessary Python packages and builds the MenteDB Python SDK. Ensure you are in the root directory of the project. ```bash pip install -r benchmarks/longmemeval/requirements.txt cd sdks/python && maturin develop --release && cd ../.. ``` -------------------------------- ### Install Python SDK and Run Benchmarks Source: https://github.com/nambok/mentedb/blob/main/benchmarks/README.md Installs the MenteDB Python SDK and runs engine tests. Use `--no-llm` for tests not requiring an LLM, or set an API key for full evaluation. ```bash cd sdks/python && maturin develop && cd ../.. python benchmarks/run_all.py --no-llm export ANTHROPIC_API_KEY="sk-ant-..." # or OPENAI_API_KEY python benchmarks/run_all.py ``` -------------------------------- ### Install mentedb-langchain Source: https://github.com/nambok/mentedb/blob/main/sdks/python/integrations/langchain/README.md Install the package via pip. ```bash pip install mentedb-langchain ``` -------------------------------- ### Start MenteDB Server with Arguments Source: https://context7.com/nambok/mentedb/llms.txt Command to start the MenteDB server with specified data directory, ports, and optional features like authentication and auto-extraction. ```bash # Start the server mentedb-server \ --data-dir /var/mentedb/data \ --port 6677 \ --grpc-port 6678 \ --require-auth \ --auto-extract ``` -------------------------------- ### Install mentedb-mcp CLI Source: https://github.com/nambok/mentedb/blob/main/README.md Installs the mentedb-mcp command-line interface. Requires Rust to be installed. ```bash # Requires Rust: https://rustup.rs cargo install mentedb-mcp ``` -------------------------------- ### Install Requirements Source: https://github.com/nambok/mentedb/blob/main/benchmarks/README.md Installs necessary Python packages for the benchmarks. The `openai` package is optional and only needed for specific tests. ```bash pip install -r benchmarks/requirements.txt ``` -------------------------------- ### Install MenteDB SDK Source: https://github.com/nambok/mentedb/blob/main/sdks/typescript/README.md Install the MenteDB package using npm. This command fetches the prebuilt native binary for your platform. ```bash npm install mentedb ``` -------------------------------- ### Install MenteDB Python SDK from PyPI Source: https://github.com/nambok/mentedb/blob/main/sdks/python/README.md Install the MenteDB Python SDK using pip once it is published to PyPI. ```bash pip install mentedb ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/nambok/mentedb/blob/main/CONTRIBUTING.md Examples of commit messages following the project's conventional commit standards. ```text feat: add phantom memory priority scoring fix: correct HNSW distance calculation for zero vectors chore: update uuid dependency to 1.12 docs: add context assembly section to ARCHITECTURE.md test: add integration tests for WAL crash recovery refactor: extract common traversal logic into helper ``` -------------------------------- ### Install MCP Server Source: https://context7.com/nambok/mentedb/llms.txt Command to install the mentedb-mcp server, which enables AI clients to interact with MenteDB via the MCP protocol. ```bash # Install MCP server cargo install mentedb-mcp ``` -------------------------------- ### Start MenteDB REST Server Source: https://github.com/nambok/mentedb/blob/main/README.md Starts the MenteDB server with specified data directory and JWT secret file. ```bash # Start the server cargo run -p mentedb-server -- --data-dir ./data --jwt-secret-file ./secret.key ``` -------------------------------- ### Initialize MenteDB Python SDK Source: https://context7.com/nambok/mentedb/llms.txt Basic import statement for starting with the MenteDB Python SDK. ```python from mentedb import MenteDB, MemoryType, EdgeType ``` -------------------------------- ### Install mentedb-crewai Source: https://github.com/nambok/mentedb/blob/main/sdks/python/integrations/crewai/README.md Install the mentedb-crewai package using pip. ```bash pip install mentedb-crewai ``` -------------------------------- ### Register Cognitive Module Source: https://github.com/nambok/mentedb/blob/main/CONTRIBUTING.md Example of how to declare and re-export a new module in lib.rs. ```rust pub mod my_feature; pub use my_feature::{MyFeature, MyFeatureConfig, MyResult}; ``` -------------------------------- ### Quick Start: MenteDB SDK Usage Source: https://github.com/nambok/mentedb/blob/main/sdks/typescript/README.md Initialize MenteDB, store memories with content and embeddings, perform vector similarity searches, recall memories using MQL with token budgeting, relate memories, and close the database connection. ```typescript import { MenteDB, MemoryType, EdgeType } from 'mentedb'; const db = new MenteDB('./my-agent-memory'); // Store a memory const id = db.store({ content: 'The deploy key rotates every 90 days', memoryType: MemoryType.Semantic, embedding: embeddingFromYourModel, tags: ['infra', 'security'], }); // Vector similarity search const hits = db.search(queryEmbedding, 5); // MQL recall with token budget const ctx = db.recall('RECALL similar("deploy key rotation") LIMIT 10'); // Relate memories db.relate(id, otherId, EdgeType.Supersedes); // Forget a memory db.forget(id); // Close the database db.close(); ``` -------------------------------- ### MenteDB Production Deployment Configuration Source: https://github.com/nambok/mentedb/blob/main/README.md Example of setting environment variables for production deployment of MenteDB, including JWT secrets, LLM provider, and API keys. ```bash # Production deployment export MENTEDB_JWT_SECRET="your-secret-here" export MENTEDB_ADMIN_KEY="your-admin-key" export MENTEDB_LLM_PROVIDER="openai" export MENTEDB_LLM_API_KEY="sk-..." mentedb-server --require-auth --data-dir /var/mentedb/data ``` -------------------------------- ### Run MenteDB with Docker Compose Source: https://github.com/nambok/mentedb/blob/main/README.md Start MenteDB in detached mode using Docker Compose. Ensure a docker-compose.yml file is present in the current directory. ```bash docker-compose up -d ``` -------------------------------- ### GET /v1/stats Source: https://context7.com/nambok/mentedb/llms.txt Retrieves database statistics including memory count and uptime. ```APIDOC ## GET /v1/stats ### Description Monitor database statistics. ### Method GET ### Endpoint /v1/stats ### Response #### Success Response (200) - **memory_count** (integer) - Total number of memories stored - **uptime_seconds** (integer) - Server uptime in seconds #### Response Example { "memory_count": 1523, "uptime_seconds": 3600 } ``` -------------------------------- ### MenteDB Test Output Example Source: https://github.com/nambok/mentedb/blob/main/benchmarks/README.md This output shows the results of MenteDB's internal tests, including verdicts like PASS/FAIL and specific metrics for memory storage, query performance, and belief propagation. It is generated during test runs. ```text ============================================================ Stale Belief Test: PASS ============================================================ Total memories stored: 9 Query: user prefers PostgreSQL SQLite database SQLite rank: 0 PostgreSQL rank: NOT FOUND (superseded) Belief propagation: Working Top results: 5 Result 1 (score=0.516): The user has switched to SQLite. They no longer use PostgreSQL... ============================================================ Delta Savings Test: PASS ============================================================ Turns simulated: 20 Total tokens (full retrieval): 2,660 Total tokens (delta): 247 Token savings: 90.7% ============================================================ Sustained Conversation Test (100 turns, 3 projects): PASS ============================================================ Total memories ingested: 100 Belief changes tracked: 6 Avg insert time: 0.29ms Avg search time: 77us Stale beliefs returned: 0% (0/6) Delta token savings (20 checkpoints): 90.1% ``` ```text ============================================================ SUMMARY ============================================================ Stale Belief................................ PASS Delta Savings............................... PASS Sustained Conversation...................... PASS Attention Budget............................ PASS Noise Ratio................................. PASS ``` -------------------------------- ### Build and Test Commands Source: https://github.com/nambok/mentedb/blob/main/CLAUDE.md Standard commands for linting, testing, running the server, and building SDKs. ```bash # Check, lint, format (always run before committing) cargo fmt --all cargo clippy --workspace -- -D warnings cargo test --workspace # Run the server cargo run --bin mentedb-server -- --port 8080 # Build Python SDK (requires maturin) cd sdks/python && maturin develop && pytest tests/ # Build TypeScript SDK (requires napi-rs CLI) cd sdks/typescript && npm run build ``` -------------------------------- ### Server Configuration - Environment Variables Source: https://context7.com/nambok/mentedb/llms.txt Configure the server via environment variables or command-line arguments. ```APIDOC ## Server Configuration ### Environment Variables Configure the server via environment variables or command-line arguments. #### LLM Extraction Configuration - `MENTEDB_LLM_PROVIDER`: LLM provider (e.g., `openai`, `anthropic`, `ollama`, `none`). - `MENTEDB_LLM_API_KEY`: API key for the LLM provider. - `MENTEDB_LLM_MODEL`: The specific LLM model to use. - `MENTEDB_LLM_BASE_URL`: Optional base URL for LLM API proxies. #### Extraction Thresholds - `MENTEDB_EXTRACTION_QUALITY_THRESHOLD`: Minimum confidence score (0.0-1.0) to store extracted information. - `MENTEDB_EXTRACTION_DEDUP_THRESHOLD`: Similarity threshold for deduplication of memories. #### Security - `MENTEDB_JWT_SECRET`: Secret key for JWT authentication. - `MENTEDB_ADMIN_KEY`: Admin key for authentication. #### Server Startup Example ```bash mentedb-server \ --data-dir /var/mentedb/data \ --port 6677 \ --grpc-port 6678 \ --require-auth \ --auto-extract ``` ``` -------------------------------- ### Run and Evaluate All Benchmark Questions Source: https://github.com/nambok/mentedb/blob/main/benchmarks/longmemeval/README.md Executes the benchmark in pages and then combines all results for a comprehensive evaluation. This is useful for running the full 500-question benchmark. ```bash python benchmarks/longmemeval/run_benchmark.py --offset 0 --limit 50 --workers 3 python benchmarks/longmemeval/run_benchmark.py --offset 50 --limit 50 --workers 3 # ... repeat for offsets 100, 150, 200, 250, 300, 350, 400, 450 python benchmarks/longmemeval/evaluate_all.py ``` -------------------------------- ### Build the Workspace Source: https://github.com/nambok/mentedb/blob/main/CONTRIBUTING.md Commands to clone the repository and build the entire workspace. ```bash git clone https://github.com/nambok/mentedb.git cd mentedb cargo build --workspace ``` -------------------------------- ### Initialize MenteDBRetriever Source: https://github.com/nambok/mentedb/blob/main/sdks/python/integrations/langchain/README.md Set up a RetrievalQA chain using MenteDBRetriever with tag filtering and agent scoping. ```python from mentedb_langchain import MenteDBRetriever from langchain.chains import RetrievalQA from langchain_openai import ChatOpenAI retriever = MenteDBRetriever( data_dir="./agent-memory", k=10, tags=["backend", "architecture"], ) chain = RetrievalQA.from_chain_type( llm=ChatOpenAI(), retriever=retriever, ) chain.invoke("What were the key decisions about our database migration?") ``` -------------------------------- ### Run Benchmarks Source: https://github.com/nambok/mentedb/blob/main/CONTRIBUTING.md Commands to execute performance benchmarks using the criterion framework. ```bash cargo bench --workspace ``` ```bash cargo bench -p mentedb --bench storage_bench ``` -------------------------------- ### GET /v1/health Source: https://context7.com/nambok/mentedb/llms.txt Checks the server health and returns version and uptime information. ```APIDOC ## GET /v1/health ### Description Monitor server health. ### Method GET ### Endpoint /v1/health ### Response #### Success Response (200) - **status** (string) - Server status - **version** (string) - API version - **uptime_seconds** (integer) - Server uptime in seconds #### Response Example { "status": "ok", "version": "0.1.0", "uptime_seconds": 3600 } ``` -------------------------------- ### MQL Graph Traversal Source: https://github.com/nambok/mentedb/blob/main/README.md Traverse the memory graph based on edge types and depth. Requires a starting node ID. ```sql -- Graph traversal TRAVERSE 550e8400-e29b-41d4-a716-446655440000 DEPTH 3 WHERE edge_type = caused ``` -------------------------------- ### Run MenteDB Benchmarks Source: https://github.com/nambok/mentedb/blob/main/README.md Commands to execute engine tests, full benchmark suites, and performance comparisons. ```bash # Engine tests (no LLM required) python3 benchmarks/run_all.py --no-llm # Full suite (requires ANTHROPIC_API_KEY or OPENAI_API_KEY) python3 benchmarks/run_all.py # Mem0 comparison (requires OPENAI_API_KEY) python3 benchmarks/mem0_comparison.py # Criterion performance benchmarks cargo bench ``` -------------------------------- ### Initialize MenteDBMemory Source: https://github.com/nambok/mentedb/blob/main/sdks/python/integrations/langchain/README.md Configure a LangChain ConversationChain with MenteDBMemory for persistent, hybrid-search based context. ```python from mentedb_langchain import MenteDBMemory from langchain.chains import ConversationChain from langchain_openai import ChatOpenAI memory = MenteDBMemory( data_dir="./agent-memory", agent_id="my-agent", token_budget=4096, ) chain = ConversationChain( llm=ChatOpenAI(), memory=memory, ) chain.predict(input="What database should I use for time series data?") chain.predict(input="Tell me more about that recommendation") ``` -------------------------------- ### Build MenteDB from Source Source: https://github.com/nambok/mentedb/blob/main/sdks/typescript/README.md Steps to build the MenteDB native addon from source. This involves checking Rust compilation, building the addon with npm, and running tests. ```bash cd sdks/typescript cargo check # verify Rust compiles npm run build # build the native addon npm test # run tests ``` -------------------------------- ### CognitionStream: Monitor LLM Token Stream Source: https://github.com/nambok/mentedb/blob/main/sdks/typescript/README.md Use CognitionStream to monitor an LLM token stream for contradictions and reinforcements against stored facts. Feed tokens and drain the buffer to get accumulated text. ```typescript import { CognitionStream } from 'mentedb'; const stream = new CognitionStream(1000); for (const token of llmTokens) { stream.feedToken(token); } const text = stream.drainBuffer(); ``` -------------------------------- ### TrajectoryTracker: Track Conversation Reasoning Source: https://github.com/nambok/mentedb/blob/main/sdks/typescript/README.md Employ TrajectoryTracker to follow the reasoning arc of a conversation and predict upcoming topics. Record turns with topic, decision state, and questions, then get resume context or predict next topics. ```typescript import { TrajectoryTracker } from 'mentedb'; const tracker = new TrajectoryTracker(); tracker.recordTurn('JWT auth design', 'investigating', [ 'Which algorithm?', 'Token lifetime?', ]); tracker.recordTurn('Token lifetime', 'decided:15 minutes'); const resume = tracker.getResumeContext(); const next = tracker.predictNextTopics(); ``` -------------------------------- ### Create Memory Relationships Source: https://context7.com/nambok/mentedb/llms.txt Establish typed, weighted edges between memory nodes to build a knowledge graph. ```bash # Create a "supersedes" edge (marks old belief as obsolete) curl -X POST http://localhost:6677/v1/edges \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{ "source": "7f8e9d0c-1a2b-3c4d-5e6f-7a8b9c0d1e2f", "target": "a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d", "edge_type": "supersedes", "weight": 1.0 }' ``` -------------------------------- ### Run Candle vs OpenAI Benchmark Source: https://github.com/nambok/mentedb/blob/main/README.md Execute a Python script to perform a head-to-head comparison between Candle (local) and OpenAI embeddings. Requires setting the OPENAI_API_KEY environment variable. ```bash python3 benchmarks/candle_vs_openai.py ``` -------------------------------- ### Run Tests Source: https://github.com/nambok/mentedb/blob/main/CONTRIBUTING.md Commands to execute tests for the entire workspace or specific crates. ```bash cargo test --workspace ``` ```bash cargo test -p mentedb-core cargo test -p mentedb-storage cargo test -p mentedb-cognitive ``` -------------------------------- ### Build MenteDB Docker Image Source: https://github.com/nambok/mentedb/blob/main/README.md Build the MenteDB Docker image using the provided Dockerfile. Tag the image for easy reference. ```bash docker build -t mentedb . ``` -------------------------------- ### Manage MenteDB with Python Source: https://context7.com/nambok/mentedb/llms.txt Use the context manager to handle database lifecycle, store memories, perform MQL recalls, and execute vector searches. ```python with MenteDB("./agent-memory") as db: # Store a memory memory_id = db.store( content="The deployment failed because the config was missing", memory_type=MemoryType.EPISODIC, embedding=[0.1, 0.2, 0.3, 0.4] * 96, # 384-dim embedding tags=["deployment", "config", "failure"], ) print(f"Stored memory: {memory_id}") # Recall memories with MQL result = db.recall("RECALL memories WHERE tag = 'deployment' LIMIT 5") print(f"Context ({result.total_tokens} tokens):\n{result.text}") # Vector similarity search query_embedding = [0.15, 0.25, 0.35, 0.45] * 96 hits = db.search(embedding=query_embedding, k=5) for hit in hits: print(f" {hit.id}: score {hit.score:.4f}") # Create relationships procedural_id = db.store( content="Always validate config before deploy", memory_type=MemoryType.PROCEDURAL, tags=["deployment", "best-practices"], ) db.relate(memory_id, procedural_id, edge_type=EdgeType.CAUSED) # Forget a memory db.forget(memory_id) ``` -------------------------------- ### Configure MCP Server Source: https://github.com/nambok/mentedb/blob/main/README.md Configuration for integrating MenteDB as an MCP server in Claude Desktop. ```json // claude_desktop_config.json { "mcpServers": { "mentedb": { "command": "mentedb-mcp", "args": ["--data-dir", "~/.mentedb"] } } } ``` -------------------------------- ### POST /v1/recall Source: https://context7.com/nambok/mentedb/llms.txt Query memories using MQL (Mente Query Language) with boolean filters, vector similarity, and graph traversal. ```APIDOC ## POST /v1/recall ### Description Query memories using MQL (Mente Query Language) with boolean filters, vector similarity, and graph traversal. ### Method POST ### Endpoint /v1/recall ### Request Body - **query** (string) - Required - MQL query string. ### Request Example { "query": "RECALL memories WHERE tag = \"preferences\" ORDER BY salience DESC LIMIT 10" } ### Response #### Success Response (200) - **context** (string) - Assembled context window. - **total_tokens** (integer) - Total token count. - **memory_count** (integer) - Number of memories retrieved. #### Response Example { "context": "## Critical Context\n- User prefers dark mode...", "total_tokens": 245, "memory_count": 3 } ``` -------------------------------- ### Python SDK for MenteDB Operations Source: https://github.com/nambok/mentedb/blob/main/README.md Demonstrates basic MenteDB operations including initialization, storing content, ingesting data, and recalling memories using the Python SDK. ```python from mentedb import MenteDb db = MenteDb("./agent-memory") db.store(content="User prefers Python", memory_type="semantic", agent_id="my-agent") db.ingest("User: I switched to Vim\nAssistant: Got it!") results = db.recall("RECALL memories WHERE tag = 'preferences' LIMIT 5") ``` -------------------------------- ### Build and Maintain MenteDB Source: https://github.com/nambok/mentedb/blob/main/README.md Standard Cargo commands for building, testing, linting, and documenting the project. ```bash cargo build # Build all crates cargo test # Run 427+ tests cargo clippy # Lint cargo bench # Benchmarks cargo doc --open # Documentation ``` -------------------------------- ### Key MCP Tools for AI Clients Source: https://context7.com/nambok/mentedb/llms.txt Lists the available tools for AI clients when integrated with MenteDB via MCP. These tools cover memory management, context assembly, and cognitive inference. ```bash # Key MCP tools available to AI clients: # - store_memory: Store a new memory # - search_memories: Vector similarity search # - ingest_conversation: Extract memories from conversation # - assemble_context: Build token-budget-aware context # - relate_memories: Create graph edges # - write_inference: Run cognitive inference on new data # - get_cognitive_state: Get pain signals, phantoms, trajectory # - forget_all: Clear all memories for an agent ``` -------------------------------- ### Run Full LongMemEval Benchmark Source: https://github.com/nambok/mentedb/blob/main/README.md Execute the complete LongMemEval benchmark suite. This involves navigating to the benchmark directory and running a bash script. ```bash # Run it yourself cd benchmarks/longmemeval bash run_full_benchmark.sh 0 ``` -------------------------------- ### Open and Close MenteDB Database in Rust Source: https://context7.com/nambok/mentedb/llms.txt Demonstrates how to open a MenteDB instance in Rust, either with default settings or a custom local embedding provider. Includes flushing to disk and properly closing the database to release resources. ```rust use mentedb::prelude::*; use mentedb::MenteDb; use mentedb_embedding::candle::CandleProvider; use std::path::Path; fn main() -> MenteResult<()> { // Basic open let mut db = MenteDb::open(Path::new("./my-agent-memory"))?; // Or open with a local embedding provider (no API key required) let embedder = Box::new(CandleProvider::new()?); let mut db = MenteDb::open_with_embedder(Path::new("./my-agent-memory"), embedder)?; // ... use the database ... // Flush to disk without closing (for periodic checkpoints) db.flush()?; // Close the database (flushes and releases resources) db.close()?; Ok(()) } ``` -------------------------------- ### Docker Deployment for MenteDB Source: https://context7.com/nambok/mentedb/llms.txt Build and run MenteDB using Docker for production. Includes options for docker-compose. ```bash # Build and run with Docker docker build -t mentedb . docker run -p 6677:6677 -p 6678:6678 \ -e MENTEDB_JWT_SECRET=your-secret \ -e MENTEDB_LLM_PROVIDER=openai \ -e MENTEDB_LLM_API_KEY=sk-... \ -v mentedb-data:/data \ mentedb # Or with docker-compose docker-compose up -d ``` -------------------------------- ### Download LongMemEval Dataset Source: https://github.com/nambok/mentedb/blob/main/benchmarks/longmemeval/README.md Downloads the LongMemEval dataset required for the benchmark. This script fetches the evaluation data. ```bash python benchmarks/longmemeval/download_data.py ``` -------------------------------- ### Project Directory Structure Source: https://github.com/nambok/mentedb/blob/main/CLAUDE.md Overview of the MenteDB repository layout, including core crates and SDKs. ```text crates/ mentedb-core/ Core types, config, error, MVCC, multi agent mentedb-storage/ Page manager, WAL, buffer pool, backup/restore mentedb-index/ HNSW vector index, bitmap, temporal, salience mentedb-graph/ CSR/CSC graph, traversal, belief propagation mentedb-query/ MQL lexer, parser, planner mentedb-context/ U curve attention layout, delta tracker, serializers mentedb-cognitive/ Stream cognition, write inference, trajectory, phantoms, interference, pain, speculative mentedb-consolidation/ Decay, archival, extraction, compression, GDPR forget mentedb-embedding/ Provider trait, hash/HTTP providers, LRU cache mentedb-server/ Axum REST API, JWT auth, rate limiting, WebSocket mentedb/ Unified facade (MenteDb struct) sdks/ python/ PyO3 bindings + pure Python client typescript/ napi-rs bindings + TypeScript client python/integrations/langchain/ LangChain memory, retriever, chat history python/integrations/crewai/ CrewAI memory and tool adapter ``` -------------------------------- ### Recall Memories with MQL Source: https://context7.com/nambok/mentedb/llms.txt Query memories using MQL (Mente Query Language) to filter by tags, vector similarity, or graph traversal. ```bash # Recall with tag filter and ordering curl -X POST http://localhost:6677/v1/recall \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{ "query": "RECALL memories WHERE tag = \"preferences\" ORDER BY salience DESC LIMIT 10" }' ``` -------------------------------- ### Format Code Source: https://github.com/nambok/mentedb/blob/main/CONTRIBUTING.md Commands to format the codebase or verify formatting without applying changes. ```bash cargo fmt --all ``` ```bash cargo fmt --all -- --check ``` -------------------------------- ### MenteDBMemory Initialization Source: https://github.com/nambok/mentedb/blob/main/sdks/python/integrations/langchain/README.md Initializes a LangChain compatible memory backend using MenteDB for conversation context. ```APIDOC ## MenteDBMemory Initialization ### Description Initializes the MenteDBMemory component to store and retrieve conversation context using hybrid search. ### Parameters - **data_dir** (string) - Required - Path to the MenteDB data directory. - **agent_id** (string) - Optional - Identifier for memory isolation in multi-agent setups. - **token_budget** (int) - Optional - Maximum tokens for assembled context (Default: 4096). ``` -------------------------------- ### Server Configuration - Docker Deployment Source: https://context7.com/nambok/mentedb/llms.txt Deploy MenteDB with Docker for production use. ```APIDOC ## Server Configuration ### Docker Deployment Deploy MenteDB with Docker for production use. #### Build and Run ```bash docker build -t mentedb . docker run -p 6677:6677 -p 6678:6678 \ -e MENTEDB_JWT_SECRET=your-secret \ -e MENTEDB_LLM_PROVIDER=openai \ -e MENTEDB_LLM_API_KEY=sk-... \ -v mentedb-data:/data \ mentedb ``` #### Docker Compose ```bash docker-compose up -d ``` ``` -------------------------------- ### Server Environment Variables Configuration Source: https://context7.com/nambok/mentedb/llms.txt Configure MenteDB server settings using environment variables. This includes LLM provider, API keys, model details, and extraction thresholds. ```bash # LLM extraction configuration export MENTEDB_LLM_PROVIDER="anthropic" # openai, anthropic, ollama, none export MENTEDB_LLM_API_KEY="sk-ant-..." export MENTEDB_LLM_MODEL="claude-sonnet-4-20250514" export MENTEDB_LLM_BASE_URL="https://api.anthropic.com" # optional, for proxies # Extraction thresholds export MENTEDB_EXTRACTION_QUALITY_THRESHOLD="0.7" # min confidence to store (0.0-1.0) export MENTEDB_EXTRACTION_DEDUP_THRESHOLD="0.85" # similarity threshold for dedup # Security export MENTEDB_JWT_SECRET="your-secret-here" export MENTEDB_ADMIN_KEY="your-admin-key" ``` -------------------------------- ### MenteDB Server Configuration Source: https://github.com/nambok/mentedb/blob/main/ARCHITECTURE.md Runs a Tokio async TCP server, wrapping MenteDB for concurrent access. Accepts data directory and port arguments, and handles graceful shutdown. ```rust Runs a Tokio async TCP server on port 6677 (configurable). Wraps `MenteDb` in `Arc>` for concurrent access. Accepts `--data-dir` and `--port` command line arguments. Handles graceful shutdown on Ctrl+C. ``` -------------------------------- ### Recall Memories with MQL and Vector Search in Rust Source: https://context7.com/nambok/mentedb/llms.txt This Rust code demonstrates various memory recall methods in MenteDB, including MQL queries, vector similarity searches, filtered searches with tags and time ranges, and point-in-time queries. ```rust use mentedb::prelude::*; use mentedb::MenteDb; use std::path::Path; fn main() -> MenteResult<()> { let mut db = MenteDb::open(Path::new("./data"))?; // Recall with MQL query let window = db.recall("RECALL memories WHERE tag = \"rust\" ORDER BY salience DESC LIMIT 5")?; println!("Token count: {}", window.total_tokens); println!("Memories included: {}", window.metadata.included_count); println!("Context:\n{}", window.format); // Vector similarity search let query_embedding = vec![0.7, 0.2, 0.6, 0.3, 0.1, 0.8]; let results = db.recall_similar(&query_embedding, 10)?; for (id, score) in &results { println!("Memory {}: score {:.4}", id, score); } // Filtered search with tags and time range let tags = ["rust", "concurrency"]; let time_range = (1704067200000000, 1735689600000000); // 2024 timestamps let filtered = db.recall_similar_filtered(&query_embedding, 5, Some(&tags), Some(time_range))?; // Point-in-time query (bi-temporal) let historical_results = db.recall_similar_at(&query_embedding, 5, 1704067200000000)?; db.close() } ``` -------------------------------- ### Basic Usage with TypeScript SDK Source: https://context7.com/nambok/mentedb/llms.txt Perform standard database operations including storage, search, MQL recall, and relationship management in Node.js. ```typescript import { MenteDB, MemoryType, EdgeType } from 'mentedb'; const db = new MenteDB('./my-agent-memory'); // Store a memory const id = db.store({ content: 'The deploy key rotates every 90 days', memoryType: MemoryType.Semantic, embedding: Array(384).fill(0).map(() => Math.random()), // your embedding tags: ['infra', 'security'], }); // Vector similarity search const hits = db.search(queryEmbedding, 5); hits.forEach(hit => { console.log(`${hit.id}: score ${hit.score.toFixed(4)}`); }); // MQL recall with token budget const ctx = db.recall('RECALL memories WHERE tag = "security" ORDER BY salience DESC LIMIT 10'); console.log(`Context (${ctx.totalTokens} tokens):\n${ctx.text}`); // Create relationships db.relate(id, otherId, EdgeType.Supports, 0.8); // Forget a memory db.forget(id); // Close the database db.close(); ``` -------------------------------- ### MCP Integration - AI Client Configuration Source: https://context7.com/nambok/mentedb/llms.txt Connect MenteDB to Claude CLI, Copilot CLI, Cursor, or any MCP-compatible client. ```APIDOC ## MCP Integration ### Configuration for AI Clients Connect MenteDB to Claude CLI, Copilot CLI, Cursor, or any MCP-compatible client. #### Example Configuration (`~/.config/claude/claude_desktop_config.json`) ```json { "mcpServers": { "mentedb": { "command": "mentedb-mcp", "args": ["--data-dir", "~/.mentedb"] } } } ``` #### Install MCP Server ```bash carp install mentedb-mcp ``` #### Key MCP Tools - `store_memory`: Store a new memory. - `search_memories`: Vector similarity search. - `ingest_conversation`: Extract memories from conversation. - `assemble_context`: Build token-budget-aware context. - `relate_memories`: Create graph edges. - `write_inference`: Run cognitive inference on new data. - `get_cognitive_state`: Get pain signals, phantoms, trajectory. - `forget_all`: Clear all memories for an agent. ``` -------------------------------- ### Run LLM Accuracy Benchmark Source: https://github.com/nambok/mentedb/blob/main/README.md Execute the LLM accuracy benchmark tests. This command requires the 'mentedb-extraction' package and specific environment variables for LLM configuration. ```bash # Run the accuracy benchmark yourself LLM_PROVIDER=anthropic LLM_API_KEY=sk-ant- \ cargo test -p mentedb-extraction --test llm_accuracy -- --ignored --nocapture ``` -------------------------------- ### Initialize MenteDBTool for CrewAI Agents Source: https://github.com/nambok/mentedb/blob/main/sdks/python/integrations/crewai/README.md Attach MenteDBTool to a CrewAI agent to allow direct querying of MenteDB using MQL for data retrieval and analysis. ```python from crewai import Agent from mentedb_crewai import MenteDBTool memory_tool = MenteDBTool(data_dir="./crew-memory") agent = Agent( role="Analyst", goal="Analyze data using historical context", tools=[memory_tool], ) ``` -------------------------------- ### Run LongMemEval Benchmark Source: https://github.com/nambok/mentedb/blob/main/benchmarks/longmemeval/README.md Executes the LongMemEval benchmark for a specified range of questions and number of workers. Requires API keys for LLM access. ```bash python benchmarks/longmemeval/run_benchmark.py --offset 0 --limit 50 --workers 3 ``` -------------------------------- ### Recall Memories via REST API Source: https://github.com/nambok/mentedb/blob/main/README.md Recalls memories based on a MQL query using the REST API. Requires an Authorization header. ```bash # Recall memories curl -X POST http://localhost:6677/v1/query \ -H "Authorization: Bearer $TOKEN" \ -d '{"mql": "RECALL memories WHERE tag = \"preferences\" LIMIT 10"}' ``` -------------------------------- ### MenteDB Criterion Performance Benchmarks Source: https://github.com/nambok/mentedb/blob/main/benchmarks/README.md These benchmarks, run with `cargo bench`, measure MenteDB's performance in terms of insert throughput and context assembly speed. They demonstrate sub-millisecond context assembly even at high memory volumes. ```text insert_throughput/memories/100 time: [13.08 ms 13.34 ms 13.41 ms] insert_throughput/memories/1000 time: [244.1 ms 244.4 ms 245.5 ms] insert_throughput/memories/10000 time: [2.644 s 2.655 s 2.701 s ] context_assembly/100 time: [216.0 µs 217.3 µs 222.6 µs] context_assembly/1000 time: [340.8 µs 342.1 µs 342.4 µs] context_assembly/10000 time: [690.1 µs 693.5 µs 694.4 µs] ``` -------------------------------- ### Embed MenteDB in Rust Source: https://github.com/nambok/mentedb/blob/main/README.md Initialize the database and perform memory operations within a Rust application. ```rust use mentedb::MenteDb; let db = MenteDb::open("./my-agent-memory")?; db.store(&memory_node)?; let context = db.assemble_context(agent_id, space_id, 4096)?; ``` -------------------------------- ### Initialize MenteDBCrewMemory for CrewAI Agents Source: https://github.com/nambok/mentedb/blob/main/sdks/python/integrations/crewai/README.md Set up persistent memory for CrewAI agents using MenteDBCrewMemory. Agents can share a memory space or have individual ones. ```python from crewai import Agent, Crew, Task from mentedb_crewai import MenteDBCrewMemory memory = MenteDBCrewMemory( data_dir="./crew-memory", space="research-team", ) researcher = Agent( role="Senior Researcher", goal="Find comprehensive information on the topic", memory=memory, ) writer = Agent( role="Technical Writer", goal="Write clear documentation from research", memory=MenteDBCrewMemory( data_dir="./crew-memory", space="research-team", agent_name="writer", ), ) task = Task( description="Research and document the latest trends in vector databases", agent=researcher, ) crew = Crew(agents=[researcher, writer], tasks=[task]) crew.kickoff() ``` -------------------------------- ### Evaluate Benchmark Results Source: https://github.com/nambok/mentedb/blob/main/benchmarks/longmemeval/README.md Evaluates the generated hypotheses using a specified judge model. This step assesses the quality of MenteDB's answers. ```bash python benchmarks/longmemeval/evaluate.py results/hypotheses_q0-50.jsonl ``` -------------------------------- ### Re-export Subsystem Crates Source: https://github.com/nambok/mentedb/blob/main/ARCHITECTURE.md The facade entry point for library consumers to access core subsystems. ```rust pub use mentedb_core as core; pub use mentedb_storage as storage; pub use mentedb_index as index; pub use mentedb_graph as graph; pub use mentedb_query as query; pub use mentedb_context as context; ``` -------------------------------- ### Configure MenteDB with MenteConfig Source: https://github.com/nambok/mentedb/blob/main/ARCHITECTURE.md Defines the structure for subsystem configurations including storage, indexing, context, cognitive, consolidation, and server settings. ```rust MenteConfig { storage: StorageConfig { data_dir: PathBuf, buffer_pool_size: 1024, // pages page_size: 16384, // bytes }, index: IndexConfig { hnsw_m: 16, hnsw_ef_construction: 200, hnsw_ef_search: 50, }, context: ContextConfig { default_token_budget: 4096, token_multiplier: 1.3, // zone percentages... }, cognitive: CognitiveConfig { contradiction_threshold: 0.95, // related thresholds, cache size, etc. }, consolidation: ConsolidationConfig { decay_half_life_hours: 168, // 7 days min_salience: 0.01, // archival settings... }, server: ServerConfig { host: "0.0.0.0", port: 6677, }, } ```