### Quickstart: Basic memvid-sdk Usage
Source: https://docs.memvid.com/installation/python
A Python quickstart example demonstrating how to use the memvid-sdk to open a memory file, put a new memory, check statistics, verify the file integrity, and seal it. It covers basic import and usage patterns.
```python
from memvid_sdk import LockedError, Memvid, use
mv = use("basic", "notes.mv2")
mv.put(text="hello world", kind="text/plain")
print(mv.stats())
report = Memvid.verify("notes.mv2", deep=True)
print(report["overall_status"])
mv.seal()
```
--------------------------------
### Pinecone Setup and Initialization (Python)
Source: https://docs.memvid.com/comparisons/vector-databases
Guides through the setup process for Pinecone, a vector database. Involves signing up, creating a project, obtaining an API key, installing the client library, initializing the connection, creating an index, and waiting for it to become ready. Data must be embedded before insertion.
```python
# 1. Sign up at pinecone.io
# 2. Create a project
# 3. Get API key
# 4. Install SDK
pip install pinecone-client
# 5. Initialize
import pinecone
pinecone.init(api_key="your-api-key", environment="us-west1-gcp")
# 6. Create index (wait for provisioning...)
pinecone.create_index("my-index", dimension=1536, metric="cosine")
# 7. Wait for index to be ready
import time
while not pinecone.describe_index("my-index").status["ready"]:
time.sleep(1)
# 8. Connect to index
index = pinecone.Index("my-index")
# 9. Now you need to embed your data before inserting...
```
--------------------------------
### Quick Start
Source: https://docs.memvid.com/python-sdk/overview
A concise guide to get started with the Memvid Python SDK, demonstrating memory creation, data ingestion, searching, and querying.
```APIDOC
## Quick Start
```python
from memvid_sdk import create
# Create a new memory
mem = create('knowledge.mv2')
# Enable lexical search (BM25)
mem.enable_lex()
# Add documents
mem.put(
title='Meeting Notes',
label='notes',
metadata={'source': 'slack'},
text='Alice mentioned she works at Anthropic...'
)
# Search
results = mem.find('who works at AI companies?', k=5)
print(results['hits'])
# Ask questions
answer = mem.ask('What does Alice do?')
print(answer['text'])
# Seal when done
mem.seal()
```
**Note:** No embeddings required for BM25 lexical search. Embeddings can be added later for semantic search.
```
--------------------------------
### Install Memvid Node.js SDK
Source: https://docs.memvid.com/quickstart/five-minute-guide
Installs the Memvid SDK for Node.js applications.
```bash
npm install @memvid/sdk
```
--------------------------------
### Installation and Quick Start (Python)
Source: https://docs.memvid.com/frameworks/langchain
Install the necessary packages and get started with Memvid in Python for LangChain applications.
```APIDOC
## Installation (Python)
```bash
pip install memvid-sdk langchain langchain-openai
```
## Quick Start (Python)
```python
from memvid_sdk import use
# Open with LangChain adapter
mem = use('langchain', 'knowledge.mv2')
# Access LangChain tools
tools = mem.tools # Returns LangChain StructuredTool objects
```
```
--------------------------------
### Install Memvid Python SDK
Source: https://docs.memvid.com/quickstart/five-minute-guide
Installs the Memvid SDK for Python applications using pip.
```bash
pip install memvid-sdk
```
--------------------------------
### Memvid CLI Quick Start Commands
Source: https://docs.memvid.com/installation/cli
Demonstrates basic Memvid CLI operations including creating a memory, adding documents, performing immediate searches, and asking questions. These commands help you quickly start building AI memories.
```bash
# Create your first memory
memvid create my-memory.mv2
# Add some documents
memvid put my-memory.mv2 --input ./documents/
# Search immediately (no embedding wait!)
memvid find my-memory.mv2 --query "your search term"
# Ask questions
memvid ask my-memory.mv2 --question "What is this about?"
```
--------------------------------
### Installation and Quick Start (Node.js)
Source: https://docs.memvid.com/frameworks/langchain
Install the necessary packages and get started with Memvid in Node.js for LangChain applications.
```APIDOC
## Installation (Node.js)
```bash
npm install @memvid/sdk @langchain/core @langchain/openai @langchain/langgraph zod
```
## Quick Start (Node.js)
```typescript
import { use } from '@memvid/sdk';
// Open with LangChain adapter
const mem = await use('langchain', 'knowledge.mv2');
// Access LangChain tools (compatible with createReactAgent)
const tools = mem.tools; // Array of tool() objects
```
```
--------------------------------
### ChromaDB Setup and Initialization (Python)
Source: https://docs.memvid.com/comparisons/vector-databases
Details the setup for ChromaDB, an open-source vector database. Covers installation, client initialization, creating a collection, and adding documents. Note that ChromaDB embeds documents automatically, which can take significant time for large datasets.
```python
# 1. Install
pip install chromadb
# 2. Initialize
import chromadb
client = chromadb.Client()
# 3. Create collection
collection = client.create_collection("my-collection")
# 4. Add documents (ChromaDB embeds automatically, but still takes time)
collection.add(
documents=["doc1", "doc2", "doc3"],
ids=["id1", "id2", "id3"]
)
# This step embeds all documents - can take minutes for large datasets
```
--------------------------------
### Memvid SDK: LangChain Integration Example
Source: https://docs.memvid.com/introduction/welcome
Demonstrates how to integrate Memvid with LangChain in Python. It shows how to open a memory file with the LangChain adapter, create a retriever, and set up a RetrievalQA chain for question answering.
```python
from memvid_sdk import use
from langchain_openai import ChatOpenAI
from langchain.chains import RetrievalQA
# Open with LangChain adapter
mem = use('langchain', 'my-knowledge.mv2', read_only=True)
retriever = mem.as_retriever(k=5)
# Create QA chain
qa = RetrievalQA.from_chain_type(
llm=ChatOpenAI(model="gpt-4o"),
retriever=retriever
)
result = qa.run("What are the main concepts?")
print(result)
```
--------------------------------
### Memvid CLI Installation and Usage
Source: https://docs.memvid.com/introduction/welcome
Provides commands to install the Memvid CLI globally using npm and then create a new memory file, ingest documents with vector compression, and perform a basic search.
```bash
npm install -g memvid-cli
# Create a new memory file (1 GB capacity by default)
memvid create my-knowledge.mv2
# Ingest documents with vector compression
memvid put my-knowledge.mv2 --input ./documents/ --vector-compression
# Search your knowledge
memvid find my-knowledge.mv2 --query "your search query"
```
--------------------------------
### Install Memvid CLI
Source: https://docs.memvid.com/quickstart/five-minute-guide
Installs the Memvid command-line interface globally. Requires Node.js version 14 or higher and works on macOS, Linux, and Windows.
```bash
npm install -g memvid-cli
```
--------------------------------
### Install @memvid/sdk using npm or pnpm
Source: https://docs.memvid.com/installation/node
This snippet shows how to install the Node.js SDK using package managers npm or pnpm. Ensure you have Node.js version 18 or later installed. Prebuilt binaries are available for common platforms; otherwise, you may need to build from source.
```bash
npm install @memvid/sdk
# or: pnpm add @memvid/sdk
```
--------------------------------
### Install and Verify Memvid CLI
Source: https://docs.memvid.com/installation/cli
Installs the Memvid CLI globally using npm and then verifies the installation by checking the CLI version. Ensure Node.js and npm are installed and configured correctly.
```bash
npm install -g memvid-cli
memvid --version
```
--------------------------------
### Install Memvid CLI
Source: https://docs.memvid.com/quickstart/cli-to-dashboard
Installs the Memvid command-line interface using package managers like Homebrew for macOS, a script for Linux, Winget for Windows, or Cargo for Rust projects. After installation, verify the CLI is operational by checking its version.
```bash
brew install memvid/tap/memvid
```
```bash
curl -sSL https://get.memvid.com | sh
```
```powershell
winget install memvid
```
```bash
cargo install memvid-cli
```
```bash
memvid --version
```
--------------------------------
### Node.js SDK Quick Start: Create, Open, and Use Memory
Source: https://docs.memvid.com/installation/node
Demonstrates the basic usage of the Node.js SDK to create a new memory file, add data, commit changes, open an existing memory file for read-only access, perform searches, and integrate with framework adapters like Langchain. This code requires Node.js 18+.
```typescript
import { create, open, use } from "@memvid/sdk";
// Create new memory
const mem = await create("notes.mv2");
await mem.put({
title: "Hello Memvid",
label: "demo",
text: "Hello from Node.js",
enableEmbedding: true,
});
await mem.seal(); // commits writes
// Open existing memory (read-only)
const ro = await open("notes.mv2", "basic", { readOnly: true });
const results = await ro.find("hello", { k: 5, mode: "auto" });
console.log(results.hits.map((h: any) => h.title));
// Framework adapters (tools/functions)
const lc = await use("langchain", "notes.mv2", { readOnly: true });
console.log(Object.keys(lc.tools ?? {}));
```
--------------------------------
### Memvid SDK: Python Example
Source: https://docs.memvid.com/introduction/welcome
Illustrates the usage of the Memvid SDK in Python for opening a memory file, conducting searches, and performing AI-powered question answering. Includes a reminder to close the memory instance when finished.
```python
from memvid_sdk import use
# Open your memory
mem = use('basic', 'my-knowledge.mv2', read_only=True)
# Search
results = mem.find('machine learning', k=10)
for hit in results.get('hits', []):
print(f"{hit['score']:.2f}: {hit['title']}")
# Ask questions with AI synthesis
answer = mem.ask('What are the key concepts?')
print(answer.get('answer'))
# Always close when done
mem.close()
```
--------------------------------
### Install Memvid CLI and Create Memory
Source: https://docs.memvid.com/introduction/the-memvid-approach
Provides instructions for installing the Memvid command-line interface globally using npm and then creating a new Memvid memory file. This is the initial setup step for using Memvid locally.
```bash
# Install
npm install -g memvid-cli
# Create memory
memvid create my-memory.mv2
```
--------------------------------
### Initial Memvid Setup Steps
Source: https://docs.memvid.com/cli/tickets-and-capacity
Guides through the initial setup process for a new Memvid memory, including creating a memory file, syncing it with the dashboard, and verifying the binding.
```bash
# 1. Create memory file
memvid create project.mv2
# 2. Sync with dashboard (binds and applies ticket)
MEMVID_API_KEY=mv_live_xxx memvid tickets sync project.mv2 --memory-id mem_abc123
# 3. Verify binding
memvid binding project.mv2
```
--------------------------------
### Install memvid-sdk Python Package
Source: https://docs.memvid.com/installation/python
Install the memvid-sdk package using pip. Optional adapters for integrations with libraries like LangChain and OpenAI can be installed using package extras.
```bash
pip install memvid-sdk
# optional adapters
pip install "memvid-sdk[langchain]" "memvid-sdk[openai]"
```
--------------------------------
### Memvid Python SDK Quick Start
Source: https://docs.memvid.com/python-sdk/overview
A quick start guide to using the Memvid Python SDK. Demonstrates creating a memory, enabling lexical search, adding documents, performing searches, asking questions, and sealing the memory.
```python
from memvid_sdk import create
# Create a new memory
mem = create('knowledge.mv2')
# Enable lexical search (BM25)
mem.enable_lex()
# Add documents (no embeddings needed!)
mem.put(
title='Meeting Notes',
label='notes',
metadata={'source': 'slack'},
text='Alice mentioned she works at Anthropic...'
)
# Search works immediately
results = mem.find('who works at AI companies?', k=5)
print(results['hits'])
# Ask questions
answer = mem.ask('What does Alice do?')
print(answer['text'])
# Seal when done
mem.seal()
```
--------------------------------
### Memvid SDK: Node.js Example
Source: https://docs.memvid.com/introduction/welcome
Shows how to use the Memvid SDK in Node.js to open a memory file, perform semantic search, and ask questions. It demonstrates opening a memory in read-only mode and iterating through search results.
```typescript
import { use } from '@memvid/sdk';
// Open your memory
const mem = await use('basic', 'my-knowledge.mv2', { readOnly: true });
// Search
const results = await mem.find('machine learning', { k: 10 });
results.hits.forEach(hit => {
console.log(`${hit.score.toFixed(2)}: ${hit.title}`);
});
// Ask questions
const answer = await mem.ask('What are the key concepts?');
console.log(answer.answer);
```
--------------------------------
### MemVid Model Comparison Example
Source: https://docs.memvid.com/concepts/time-travel-replay
Shows how to use MemVid to compare different LLM models. The example involves starting a session, performing an 'ask' command with a specific model (e.g., GPT-4o), and ending the session. This allows for subsequent analysis or replaying with different models.
```bash
# Ask with GPT-4o
memvid session start knowledge.mv2 --name "Model Comparison"
memvid ask knowledge.mv2 --question "Summarize the key findings" --use-model openai:gpt-4o
memvid session end knowledge.mv2
```
--------------------------------
### Memvid Node.js SDK Quick Start Example
Source: https://docs.memvid.com/sdks/node
A basic example demonstrating how to create a new memory file, add documents, perform searches, ask questions using an AI model, and close the memory file. This requires Node.js 18+.
```typescript
import { create, open } from '@memvid/sdk';
// Create a new memory file
const mem = await create('knowledge.mv2');
// Add documents
await mem.put({
title: 'Meeting Notes',
text: 'Alice mentioned she works at Anthropic...',
enableEmbedding: true
});
// Search
const results = await mem.find('who works at AI companies?');
console.log(results.hits);
// Ask questions with AI
const answer = await mem.ask('What does Alice do?', {
model: 'gpt-4o-mini',
modelApiKey: process.env.OPENAI_API_KEY
});
console.log(answer.text);
// Close when done
await mem.close();
```
--------------------------------
### Python SDK: Interact with Memvid Memory Databases
Source: https://docs.memvid.com/quickstart/cli-to-dashboard
This Python code demonstrates how to use the memvid SDK to interact with memory databases. It shows how to install the SDK, open a database in read-only mode, perform searches using keywords, and ask natural language questions, specifying an OpenAI model for processing.
```bash
pip install memvid-sdk
```
```python
from memvid_sdk import use
# Open read-only (for queries)
mem = use('basic', 'docs.mv2', read_only=True)
# Search
results = mem.find('authentication', k=5)
for hit in results['hits']:
print(f"{hit['score']:.2f}: {hit['title']}")
# Ask questions
answer = mem.ask('How do I configure OAuth?', model='openai:gpt-4o')
print(answer['answer'])
```
--------------------------------
### Run Memvid CLI without Global Installation
Source: https://docs.memvid.com/installation/cli
Executes Memvid CLI commands using npx, allowing you to run the tool without a global npm installation. This is useful for testing or when global installations are restricted.
```bash
npx memvid-cli --help
npx memvid-cli create test.mv2
```
--------------------------------
### Quick Start: Use Memvid with LangChain Adapter (Python)
Source: https://docs.memvid.com/frameworks/langchain
Provides a Python example for initializing Memvid with the 'langchain' adapter. It illustrates how to load Memvid data and access the tools it exposes for LangChain integration.
```python
from memvid_sdk import use
# Open with LangChain adapter
mem = use('langchain', 'knowledge.mv2')
# Access LangChain tools
tools = mem.tools # Returns LangChain StructuredTool objects
```
--------------------------------
### Node.js SDK: Interact with Memvid Memory Databases
Source: https://docs.memvid.com/quickstart/cli-to-dashboard
This Node.js code illustrates how to use the memvid SDK for interacting with memory databases. It covers installing the SDK via npm, opening a database in read-only mode, executing searches with a specified number of results (k), and posing natural language questions, including specifying different OpenAI models.
```bash
npm install @memvid/sdk
```
```typescript
import { use } from '@memvid/sdk';
// Open read-only
const mem = await use('basic', 'docs.mv2', { readOnly: true });
// Search
const results = await mem.find('authentication', { k: 5 });
results.hits.forEach(hit => {
console.log(`${hit.score.toFixed(2)}: ${hit.title}`);
});
// Ask questions
const answer = await mem.ask('How do I configure OAuth?', {
model: 'openai:gpt-4o-mini'
});
console.log(answer.answer);
```
--------------------------------
### Troubleshoot 'Command Not Found'
Source: https://docs.memvid.com/installation/cli
Provides commands to check your npm global bin directory and add it to your PATH environment variable if the Memvid CLI commands are not recognized. This ensures your system can locate the installed CLI.
```bash
# Check npm global bin location
npm root -g
# Add to PATH if needed
export PATH="$PATH:$(npm root -g)/../bin"
```
--------------------------------
### Agent Setup and Chat Initiation (Python)
Source: https://docs.memvid.com/frameworks/autogen
Initializes a UserProxyAgent, an AssistantAgent for research with tool access, and another AssistantAgent for writing. It then sets up a GroupChat and GroupChatManager to orchestrate a conversation between these agents, starting with a specific research and writing task.
```python
from autogen import UserProxyAgent, AssistantAgent, GroupChat, GroupChatManager
# Assume search_tool is defined elsewhere and imported
# from your_module import search_tool
# Mock search_tool for demonstration purposes
class MockSearchTool:
def __init__(self):
self.schema = {"name": "search", "parameters": {"query": "string"}}
self.name = "search"
self.func = self.search_func
def search_func(self, query: str):
print(f"Searching for: {query}")
return f"Mock results for {query}"
search_tool = MockSearchTool()
user_proxy = UserProxyAgent(name="user", human_input_mode="NEVER")
researcher = AssistantAgent(
name="researcher",
llm_config={
"model": "gpt-4o",
"functions": [search_tool.schema]
},
system_message="You research topics using the knowledge base."
)
researcher.register_function(function_map={search_tool.name: search_tool.func})
writer = AssistantAgent(
name="writer",
llm_config={"model": "gpt-4o"},
system_message="You write summaries based on research findings."
)
group_chat = GroupChat(
agents=[user_proxy, researcher, writer],
messages=[],
max_round=10
)
manager = GroupChatManager(groupchat=group_chat, llm_config={"model": "gpt-4o"})
user_proxy.initiate_chat(
manager,
message="Research deployment best practices and write a summary"
)
```
--------------------------------
### OpenAI CLIP Provider Setup and Usage (Python)
Source: https://docs.memvid.com/concepts/visual-embeddings
Shows how to set up and use OpenAI's CLIP embedding models with the Memvid SDK. It includes setting the API key via an environment variable and provides examples of initializing the provider using a factory function with default or specific models, or direct instantiation.
--------------------------------
### Quick Start: Use Memvid with LangChain Adapter (Node.js)
Source: https://docs.memvid.com/frameworks/langchain
Demonstrates the basic setup for using Memvid within a LangChain application using the Node.js adapter. It shows how to initialize Memvid with the 'langchain' adapter and access its compatible tools.
```typescript
import { use } from '@memvid/sdk';
// Open with LangChain adapter
const mem = await use('langchain', 'knowledge.mv2');
// Access LangChain tools (compatible with createReactAgent)
const tools = mem.tools; // Array of tool() objects
```
--------------------------------
### Installation
Source: https://docs.memvid.com/cli
Instructions for installing the Memvid CLI using npm and verifying the installation.
```APIDOC
## Installation
```bash
# npm (recommended)
npm install -g memvid-cli
# Verify installation
memvid --version
```
See [Installation Guide](/installation/cli) for platform-specific instructions and troubleshooting.
```
--------------------------------
### Quick Start with Haystack Adapter
Source: https://docs.memvid.com/frameworks/haystack
Initializes Memvid with the Haystack adapter and accesses its retriever component. This is a basic setup to get started with Memvid's search capabilities within Haystack.
```python
from memvid_sdk import use
# Open with Haystack adapter
mem = use('haystack', 'knowledge.mv2')
# Access Haystack components
retriever = mem.as_retriever(top_k=5)
```
--------------------------------
### Memvid Google ADK Integration
Source: https://docs.memvid.com/frameworks/google-adk
This section details the integration of Memvid with Google ADK, including installation, setup, and usage examples for building Gemini-powered agents.
```APIDOC
## Installation
```bash
npm install @memvid/sdk @google/generative-ai
```
## Quick Start
```typescript
import { use } from '@memvid/sdk';
// Open with Google ADK adapter
const mem = await use('google-adk', 'knowledge.mv2');
// Access ADK function declarations
const tools = mem.tools; // FunctionDeclaration[] for Gemini API
const executors = mem.functions; // Function executors by name
```
## Available Functions
The Google ADK adapter provides three function declarations:
| Function | Description |
| ------------- | ----------------------------------------------------- |
| `memvid_put` | Store documents in memory with title, label, and text |
| `memvid_find` | Search for relevant documents by query |
| `memvid_ask` | Ask questions with RAG-style answer synthesis |
## Basic Usage with Gemini
```typescript
import { use } from '@memvid/sdk';
import { GoogleGenerativeAI } from '@google/generative-ai';
// Initialize Memvid with Google ADK adapter
const mem = await use('google-adk', 'knowledge.mv2');
// Get function declarations and executors
const tools = mem.tools as any[];
const executors = mem.functions as Record Promise>;
// Create Gemini client
const geminiKey = process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;
if (!geminiKey) throw new Error("Set GEMINI_API_KEY (or legacy GOOGLE_API_KEY)");
const genAI = new GoogleGenerativeAI(geminiKey);
// Create model with Memvid tools
const model = genAI.getGenerativeModel({
model: 'gemini-2.0-flash',
tools: [{ functionDeclarations: tools }],
});
// Start a chat
const chat = model.startChat();
const result = await chat.sendMessage('Search for authentication information');
// Handle function calls
const response = result.response;
const parts = response.candidates?.[0]?.content?.parts || [];
for (const part of parts) {
if (part.functionCall) {
const { name, args } = part.functionCall;
console.log(`Function call: ${name}`);
// Execute the function
if (executors[name]) {
const funcResult = await executors[name](args as Record);
console.log(`Result: ${funcResult}`);
// Send result back to model
const followUp = await chat.sendMessage([{ functionResponse: { name, response: { result: funcResult } } }]);
console.log(`Model response: ${followUp.response.text()}`);
}
} else if (part.text) {
console.log(`Response: ${part.text}`);
}
}
```
## Direct Tool Execution
Use the function executors directly without Gemini:
```typescript
import { use } from '@memvid/sdk';
const mem = await use('google-adk', 'knowledge.mv2', { mode: 'create' });
const executors = mem.functions as Record Promise>;
// Store documents
const putResult = await executors.memvid_put({
title: 'API Documentation',
label: 'docs',
text: 'Authentication uses JWT tokens with refresh capability.',
});
console.log(putResult);
// Output: Document stored with frame_id: 2
// Search documents
const findResult = await executors.memvid_find({
query: 'authentication',
top_k: 5,
});
console.log(findResult);
// Output: Found 1 results:
// 1. [API Documentation] (score: 2.34): Authentication uses JWT tokens...
// Ask questions
const askResult = await executors.memvid_ask({
question: 'How does authentication work?',
mode: 'auto',
});
console.log(askResult);
// Output: Answer: Authentication uses JWT tokens with refresh capability.
// Sources: API Documentation
```
## Complete Agentic Example
```typescript
import { use } from '@memvid/sdk';
import { GoogleGenerativeAI } from '@google/generative-ai';
async function runGeminiAgent() {
// Initialize
const mem = await use('google-adk', 'knowledge.mv2');
const tools = mem.tools as any[];
const executors = mem.functions as Record Promise>;
// Store some knowledge first
await executors.memvid_put({
title: 'Gemini Overview',
label: 'google-ai',
text: 'Gemini is Google\'s most capable AI model family.',
});
// ... rest of the agent logic
}
```
```
--------------------------------
### Create and Ingest Data with Memvid CLI
Source: https://docs.memvid.com/quickstart/five-minute-guide
Demonstrates creating a new memory file and adding documents to it using the Memvid CLI. Data can be ingested directly from standard input and is immediately searchable.
```bash
# Create a new memory
memvid create knowledge.mv2
# Add documents (no embeddings needed!)
echo "Alice works at Anthropic as a Senior Engineer in San Francisco." | \
memvid put knowledge.mv2 --title "Team Info"
echo "Bob joined OpenAI last month as a Research Scientist." | \
memvid put knowledge.mv2 --title "New Hires"
echo "Project Alpha has a budget of $500k and is led by Alice." | \
memvid put knowledge.mv2 --title "Projects"
```
--------------------------------
### Session Management: Start, Checkpoint, End, List, Replay, Delete
Source: https://docs.memvid.com/python-sdk/overview
Provides a comprehensive guide to managing user sessions, including starting a session with a name, performing operations, adding checkpoints, ending the session to get a summary, listing all existing sessions, replaying a session with modified parameters, and deleting a session.
```python
# Start recording
session_id = mem.session_start('qa-test')
# Perform operations
mem.find('test query')
mem.ask('What happened?')
# Add checkpoint
mem.session_checkpoint()
# End session
summary = mem.session_end()
# List sessions
sessions = mem.session_list()
# Replay session with different params
replay = mem.session_replay(session_id, top_k=10, adaptive=True)
print(replay['match_rate'])
# Delete session
mem.session_delete(session_id)
```
--------------------------------
### Memvid CLI: Create, Ingest, and Search Memory Databases
Source: https://docs.memvid.com/quickstart/cli-to-dashboard
This snippet demonstrates the core command-line interface (CLI) operations for the memvid tool. It covers creating a new memory file, ingesting data with vector compression, checking database statistics, performing keyword searches, asking natural language questions, and verifying data integrity. The `--vector-compression` flag is used for efficient data storage.
```bash
memvid create docs.mv2
memvid put docs.mv2 \
--input ./docs/ \
--vector-compression \
--track "documentation"
memvid put docs.mv2 \
--input ./api-reference/ \
--vector-compression \
--track "api"
memvid stats docs.mv2
memvid find docs.mv2 --query "authentication setup" --mode auto
export OPENAI_API_KEY=your-key
memvid ask docs.mv2 \
--question "How do I configure OAuth?" \
--use-model openai
memvid verify docs.mv2 --deep
```
--------------------------------
### Create and Ingest Data with Memvid Python SDK
Source: https://docs.memvid.com/quickstart/five-minute-guide
Demonstrates creating a new memory and ingesting documents using the Memvid Python SDK. Documents require a title, label, metadata, and text.
```python
from memvid_sdk import create
mem = create('knowledge.mv2')
mem.enable_lex()
# Add documents (no embeddings needed!)
mem.put(
title='Team Info',
label='team',
metadata={},
text='Alice works at Anthropic as a Senior Engineer in San Francisco.'
)
mem.put(
title='New Hires',
label='team',
metadata={},
text='Bob joined OpenAI last month as a Research Scientist.'
)
mem.put(
title='Projects',
label='project',
metadata={},
text='Project Alpha has a budget of $500k and is led by Alice.'
)
```
--------------------------------
### Ask Questions with Memvid CLI
Source: https://docs.memvid.com/quickstart/five-minute-guide
Demonstrates using LLM-powered Q&A with Memvid CLI. Requires an OpenAI API key to be set as an environment variable.
```bash
# Ask with LLM synthesis (requires OPENAI_API_KEY)
export OPENAI_API_KEY=sk-...
memvid ask knowledge.mv2 --question "What is Alice's role?" --use-model openai
```
--------------------------------
### Verify memvid Installation
Source: https://docs.memvid.com/sdks/cli
Checks if the memvid CLI has been installed correctly by displaying its current version. This command should be run after installation to confirm successful setup.
```bash
memvid --version
```
--------------------------------
### Ask Questions with Memvid
Source: https://docs.memvid.com/quickstart/cli-to-dashboard
Utilize AI models to ask questions and receive synthesized answers based on the content of your Memvid memory. Supports local models like 'tinyllama' and external services like OpenAI and Anthropic by providing API keys.
```bash
# Using local model (tinyllama)
memvid ask my-knowledge.mv2 --question "What is Memvid and how does it work?"
```
```bash
# Using OpenAI (requires API key)
export OPENAI_API_KEY=your-key
memvid ask my-knowledge.mv2 --question "What is Memvid?" --use-model openai
```
```bash
# Using Anthropic
export ANTHROPIC_API_KEY=your-key
memvid ask my-knowledge.mv2 --question "What is Memvid?" --use-model claude
```
--------------------------------
### Ask Questions with Memvid Python SDK
Source: https://docs.memvid.com/quickstart/five-minute-guide
Illustrates using LLM-powered Q&A with the Memvid Python SDK. Requires an OpenAI API key to be set in the environment variables.
```python
# Ask with LLM synthesis
answer = mem.ask(
"What is Alice's role?",
model='gpt-4o-mini',
api_key=os.environ['OPENAI_API_KEY']
)
print(answer['text'])
# "Alice is a Senior Engineer at Anthropic in San Francisco."
```
--------------------------------
### Install Memvid Framework Dependencies
Source: https://docs.memvid.com/errors/troubleshooting
These bash commands show how to install necessary dependencies for different frameworks (LangChain, LlamaIndex, CrewAI) to ensure proper integration with Memvid. Make sure to install the correct package for your chosen framework.
```bash
# For LangChain
pip install langchain langchain-openai
# For LlamaIndex
pip install llama-index
# For CrewAI
pip install crewai
```
--------------------------------
### Create and Manage Memvid Memory
Source: https://docs.memvid.com/quickstart/cli-to-dashboard
Create a new Memvid memory file (`.mv2`) and add various types of content, including text, files, and directories, with options for metadata like tracks and tags. Vector compression can be enabled during document addition for optimized storage.
```bash
memvid create my-knowledge.mv2
memvid stats my-knowledge.mv2
```
```bash
echo "Memvid is a portable AI memory system. It stores embeddings, indices, and data in a single .mv2 file." | memvid put my-knowledge.mv2 --input - --title "What is Memvid"
```
```bash
# Add a single file with vector compression
memvid put my-knowledge.mv2 --input document.pdf --vector-compression
# Add all files in a directory
memvid put my-knowledge.mv2 --input ./documents/ --vector-compression
```
```bash
memvid put my-knowledge.mv2 \
--input notes.md \
--track "notes" \
--tag "category=meeting" \
--vector-compression
```
--------------------------------
### Update Memvid CLI
Source: https://docs.memvid.com/installation/cli
Updates the globally installed Memvid CLI to the latest version using npm. Regular updates ensure you have the latest features and bug fixes.
```bash
npm update -g memvid-cli
```
--------------------------------
### Get CLI Version
Source: https://docs.memvid.com/cli/maintenance-and-tickets
Displays the current version of the Memvid CLI. This is a basic command for verifying the installed version.
```bash
memvid version
```
--------------------------------
### Manage Documents and Query via CLI
Source: https://docs.memvid.com/examples/document-qa
This example provides command-line interface commands for managing a document Q&A system. It covers creating a new document store, ingesting all documents from a directory, and asking questions against the store.
```bash
# Create and ingest
memvid create documents.mv2
memvid put documents.mv2 --input ./docs/
# Ask questions
memvid ask documents.mv2 --question "What is the refund policy?"
```
--------------------------------
### Diagnose Python Import Errors with Bash
Source: https://docs.memvid.com/errors/troubleshooting
This snippet provides bash commands to diagnose Python import errors related to the memvid SDK. It includes checking the installation, Python version, and installed packages.
```bash
pip show memvid-sdk
python --version
pip list | grep memvid
```
--------------------------------
### Install and Use NER Models for Logic-Mesh
Source: https://docs.memvid.com/installation/models
Guides on installing NER models and enabling Logic-Mesh during data ingestion with `memvid put`. Also demonstrates how to use `memvid follow` with extracted entities.
```bash
# Install NER model
memvid models install --ner distilbert-ner
# Enable Logic-Mesh during ingestion and traversal
memvid put graph.mv2 --input docs/ --logic-mesh
memvid follow graph.mv2 traverse --start "Microsoft" --hops 2
```
--------------------------------
### Memvid CLI: Create, Put, and Find Knowledge
Source: https://docs.memvid.com/comparisons/vector-databases
This snippet shows basic Memvid CLI commands for creating a knowledge base file, adding content to it, and searching for specific information. It requires the memvid-cli to be installed globally.
```bash
npm install -g memvid-cli
memvid create knowledge.mv2
echo "Your document content" | memvid put knowledge.mv2
memvid find knowledge.mv2 --query "document"
```
--------------------------------
### Get Memory Statistics and List Entities
Source: https://docs.memvid.com/python-sdk/overview
Provides examples for retrieving statistics about memories, such as the count of entities and cards, and for listing all available entities within the system.
```python
stats = mem.memories_stats()
print(stats['entityCount'], stats['cardCount'])
entities = mem.memory_entities()
```
--------------------------------
### Ask Command Examples with memvid CLI
Source: https://docs.memvid.com/cli/search-and-ask
Demonstrates various ways to use the 'memvid ask' command to query memory files. This includes specifying models, adjusting retrieval parameters like top-k, filtering by date ranges, and obtaining context-only responses. It highlights options for masking PII and using different LLM providers.
```bash
# Ask with local Ollama model (recommended)
memvid ask knowledge.mv2 \
--question "How do I configure authentication?" \
--use-model "ollama:qwen2.5:1.5b"
# Ask with more context
memvid ask knowledge.mv2 \
--question "Explain the architecture in detail" \
--top-k 15 \
--use-model "ollama:qwen2.5:3b"
# Get just the context without LLM synthesis
memvid ask knowledge.mv2 \
--question "What is the architecture?" \
--context-only
# Mask sensitive data before sending to cloud LLM
memvid ask knowledge.mv2 \
--question "What are the contact details?" \
--use-model openai \
--mask-pii
# Filter to specific date range
memvid ask knowledge.mv2 \
--question "What happened in Q4?" \
--start "2024-10-01" \
--end "2024-12-31" \
--use-model "ollama:qwen2.5:1.5b"
# JSON output with Gemini
memvid ask knowledge.mv2 \
--question "Summarize the API" \
--use-model "gemini-2.0-flash" \
--json
```
--------------------------------
### Get Help and Version Information
Source: https://docs.memvid.com/troubleshooting/cli
Retrieves help information for memvid commands and displays version details. This includes general help, command-specific help, and the memvid version.
```bash
# General help
memvid --help
# Command-specific help
memvid create --help
memvid put --help
memvid find --help
memvid doctor --help
# Version info
memvid version
```
--------------------------------
### Create and Ingest Data with Memvid Node.js SDK
Source: https://docs.memvid.com/quickstart/five-minute-guide
Shows how to create a new memory and ingest documents using the Memvid Node.js SDK. Documents are added with titles and labels.
```typescript
import { create } from '@memvid/sdk';
const mem = await create('knowledge.mv2');
// Add documents (no embeddings needed!)
await mem.put({
title: 'Team Info',
label: 'team',
text: 'Alice works at Anthropic as a Senior Engineer in San Francisco.'
});
await mem.put({
title: 'New Hires',
label: 'team',
text: 'Bob joined OpenAI last month as a Research Scientist.'
});
await mem.put({
title: 'Projects',
label: 'project',
text: 'Project Alpha has a budget of $500k and is led by Alice.'
});
```
--------------------------------
### Configure Indexes in Memvid
Source: https://docs.memvid.com/concepts/performance-tuning
Control index creation during Memvid setup to optimize storage and search performance. Disable vector or lexical indexes as needed based on the intended use case.
```bash
# No vector index (lexical only)
memvid create code.mv2 --no-vec
# No lexical index (semantic only)
memvid create semantic.mv2 --no-lex
```
--------------------------------
### Ask Questions with Memvid Node.js SDK
Source: https://docs.memvid.com/quickstart/five-minute-guide
Illustrates how to use LLM-powered Q&A with the Memvid Node.js SDK. Requires an OpenAI API key passed to the SDK.
```typescript
// Ask with LLM synthesis
const answer = await mem.ask("What is Alice's role?", {
model: 'gpt-4o-mini',
modelApiKey: process.env.OPENAI_API_KEY
});
console.log(answer.text);
// "Alice is a Senior Engineer at Anthropic in San Francisco."
```
--------------------------------
### Use Case Examples
Source: https://docs.memvid.com/concepts/time-travel-replay
Practical examples demonstrating how to use Memvid for various scenarios.
```APIDOC
## Use Case Examples
Memvid can be applied to several practical scenarios, including debugging, compliance audits, and model comparisons.
### 1. Debug Missing Results
This example shows how to record a failing scenario and replay it with adaptive retrieval to identify issues.
```bash
# Record the failing scenario
memvid session start knowledge.mv2 --name "Missing Results Debug"
memvid ask knowledge.mv2 --question "What did Databricks purchase?" --use-model openai
memvid session end knowledge.mv2
# Replay with adaptive retrieval
memvid session replay knowledge.mv2 --session --adaptive --verbose
# Reveals: Document existed at rank 12, adaptive found it
```
### 2. Compliance Audit Trail
Use Memvid to create an immutable record of decisions for compliance purposes.
```bash
# Record all decisions for audit
memvid session start knowledge.mv2 --name "Compliance Review 2024-12"
memvid ask knowledge.mv2 --question "Is this transaction fraudulent?" --use-model openai
memvid session end knowledge.mv2
# Later: Replay with frozen context to verify decision
memvid session replay knowledge.mv2 --session --audit
# Shows exact frames and answer - reproducible for auditors
```
### 3. Model Comparison
Compare the performance and output of different LLM models.
```bash
# Ask with GPT-4o
memvid session start knowledge.mv2 --name "Model Comparison"
memvid ask knowledge.mv2 --question "Summarize the key findings" --use-model openai:gpt-4o
memvid session end knowledge.mv2
```
```
--------------------------------
### Memvid CLI Hybrid Search Modes
Source: https://docs.memvid.com/introduction/welcome
Demonstrates how to perform hybrid, lexical, and semantic searches using the Memvid CLI. The 'auto' mode is recommended for combining lexical and semantic search capabilities.
```bash
# Hybrid search (recommended)
memvid find knowledge.mv2 --query "user authentication" --mode auto
# Lexical search - exact keyword matching
memvid find knowledge.mv2 --query "authentication" --mode lex
# Semantic search - conceptual understanding
memvid find knowledge.mv2 --query "how do users log in" --mode sem
```
--------------------------------
### Search Data with Memvid CLI
Source: https://docs.memvid.com/quickstart/five-minute-guide
Shows how to perform a lexical search on a Memvid memory using the CLI. This search is available immediately after data ingestion.
```bash
# Search works immediately (BM25 lexical search)
memvid find knowledge.mv2 --query "who works at AI companies"
```
--------------------------------
### Check Framework Version Compatibility for Memvid
Source: https://docs.memvid.com/errors/troubleshooting
This bash command helps you check the installed version of a framework, such as LangChain, to ensure it's compatible with Memvid. Compatibility issues can arise from outdated or unsupported framework versions.
```bash
pip show langchain # Check version
```
--------------------------------
### Installing and Using Memvid CLI
Source: https://docs.memvid.com/comparisons/vector-databases
Provides bash commands to install the Memvid command-line interface (CLI) using npm, create a new Memvid file, add content to it, and perform a search query. This demonstrates the immediate usability of Memvid without API keys or embedding delays.
```bash
# Install (10 seconds)
npm install -g memvid-cli
# Create and search (10 more seconds)
memvid create test.mv2
echo "The quick brown fox jumps over the lazy dog" | memvid put test.mv2
memvid find test.mv2 --query "quick fox"
# That's it. No API keys. No embedding wait. Just search.
```
--------------------------------
### Select Synthesis Model for RAG with Memvid
Source: https://docs.memvid.com/concepts/performance-tuning
Choose the appropriate synthesis model for RAG tasks based on speed, quality, and cost requirements. Examples show how to specify models for both local and API-based synthesis.
```bash
# Fast local synthesis
memvid ask memory.mv2 --question "..." --use-model tinyllama
# Fast API synthesis
memvid ask memory.mv2 --question "..." --use-model groq
```
--------------------------------
### Memvid Smart Frames Search Examples (Python)
Source: https://docs.memvid.com/comparisons/vector-databases
Demonstrates various search functionalities within Memvid using Python. Includes exact lexical search, temporal queries based on timelines, entity state retrieval using a knowledge graph, and semantic/hybrid search modes. Requires the 'mem' object to be initialized.
```python
# Exact lexical search (instant, no embeddings needed)
results = mem.find("handleAuthentication", k=5)
# Temporal queries (unique to Memvid)
results = mem.timeline("2024-01-01", "2024-01-31")
# Entity state (knowledge graph)
alice = mem.state("Alice") # {employer: "Anthropic", role: "Engineer"}
# Semantic search (when you need it)
results = mem.find("cost reduction strategies", mode="vec")
# Hybrid search (best of both)
results = mem.find("budget optimization", mode="auto")
```
--------------------------------
### Open or Create Memvid Instance (Node.js, Python)
Source: https://docs.memvid.com/quickstart/sdk-recipes
Initializes a Memvid instance using the 'basic' provider and a specified file. It supports optional modes like 'auto' and features like enabling lexical search. Dependencies include the '@memvid/sdk' for Node.js and 'memvid_sdk' for Python.
```typescript
import { use } from "@memvid/sdk";
const mem = await use("basic", "notes.mv2", { mode: "auto", enableLex: true });
```
```python
from memvid_sdk import use
mem = use("basic", "notes.mv2", mode="auto", enable_lex=True, enable_vec=False)
```