> ## Documentation Index
> Fetch the complete documentation index at: https://docs.memvid.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK

> Build AI applications with persistent memory in TypeScript/JavaScript

The Node.js SDK provides a fully-typed TypeScript interface for working with Memvid memory files.

## Installation

```bash theme={null}
npm install @memvid/sdk
# or
pnpm add @memvid/sdk
# or
yarn add @memvid/sdk
```

<Info>
  **Requirements:** Node.js 18+, macOS/Linux/Windows. Native bindings included.
</Info>

## Quick Start

```typescript theme={null}
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();
```

## API Reference

| Category             | Methods                                                                      | Description                      |
| -------------------- | ---------------------------------------------------------------------------- | -------------------------------- |
| **File Operations**  | `create`, `open`, `close`, `use`                                             | Create, open, close memory files |
| **Data Ingestion**   | `put`, `putMany`                                                             | Add documents with embeddings    |
| **Search**           | `find`, `ask`, `vecSearch`, `timeline`                                       | Query your memory                |
| **Memory Cards**     | `memories`, `state`, `enrich`, `addMemoryCards`                              | Structured fact extraction       |
| **Tables**           | `putPdfTables`, `listTables`, `getTable`                                     | PDF table extraction             |
| **Sessions**         | `sessionStart`, `sessionEnd`, `sessionReplay`                                | Time-travel debugging            |
| **Tickets**          | `syncTickets`, `currentTicket`, `getCapacity`                                | Capacity management              |
| **Cloud Management** | `configure`, `createProject`, `listProjects`, `createMemory`, `listMemories` | Dashboard API                    |
| **Security**         | `lock`, `unlock`, `lockWho`, `lockNudge`                                     | Encryption and access control    |
| **Utilities**        | `verify`, `doctor`, `maskPii`                                                | Maintenance and utilities        |

## Framework Adapters

```typescript theme={null}
import { use } from '@memvid/sdk';

// Vercel AI SDK
const vercel = await use('vercel-ai', 'knowledge.mv2');
const tools = vercel.tools;

// LangChain.js
const langchain = await use('langchain', 'knowledge.mv2');
const retriever = langchain.asRetriever();

// LlamaIndex
const llamaindex = await use('llamaindex', 'knowledge.mv2');

// OpenAI Function Calling
const openai = await use('openai', 'knowledge.mv2');
const functions = openai.functions;

// Google ADK
const googleAdk = await use('google-adk', 'knowledge.mv2');

// Semantic Kernel
const sk = await use('semantic-kernel', 'knowledge.mv2');
```

## Embedding Providers

```typescript theme={null}
import {
  OpenAIEmbeddings,
  GeminiEmbeddings,
  MistralEmbeddings,
  CohereEmbeddings,
  VoyageEmbeddings,
  NvidiaEmbeddings,
  LOCAL_EMBEDDING_MODELS
} from '@memvid/sdk';

// OpenAI
const openai = new OpenAIEmbeddings({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'text-embedding-3-small'
});

// Gemini
const gemini = new GeminiEmbeddings({
  apiKey: process.env.GEMINI_API_KEY
});

// Mistral
const mistral = new MistralEmbeddings({
  apiKey: process.env.MISTRAL_API_KEY
});

// Local (no API required)
await mem.put({
  text: 'content',
  enableEmbedding: true,
  embeddingModel: LOCAL_EMBEDDING_MODELS.BGE_SMALL
});
```

**Local Embedding Models:**

| Model       | Dimensions | Speed   | Quality |
| ----------- | ---------- | ------- | ------- |
| `BGE_SMALL` | 384        | Fastest | Good    |
| `BGE_BASE`  | 768        | Fast    | Better  |
| `NOMIC`     | 768        | Fast    | Better  |
| `GTE_LARGE` | 1024       | Slower  | Best    |

## Entity Extraction

```typescript theme={null}
// Extract facts using rules engine
const result = await mem.enrich('rules');

// View extracted cards
const { cards, count } = await mem.memories();
console.log(`Extracted ${count} memory cards`);

// Get entity state (O(1) lookup)
const alice = await mem.state('Alice');
console.log(alice.slots);
// { employer: 'Anthropic', role: 'Engineer' }

// Add memory cards manually
await mem.addMemoryCards([
  { entity: 'Alice', slot: 'employer', value: 'Anthropic' },
  { entity: 'Bob', slot: 'team', value: 'Infrastructure' }
]);

// Export facts
const json = await mem.exportFacts('json');
const csv = await mem.exportFacts('csv', 'Alice');
```

## Session Recording

Record and replay agent sessions for debugging:

```typescript theme={null}
// Start recording
const sessionId = await mem.sessionStart('Debug Session');

// Perform operations (all recorded)
await mem.put({ title: 'Notes', text: 'Content...' });
await mem.find('test query');

// Add checkpoint
await mem.sessionCheckpoint();

// End session
const summary = await mem.sessionEnd();
console.log(`Recorded ${summary.actionCount} actions`);

// Replay with different parameters
const replay = await mem.sessionReplay(sessionId, {
  adaptive: true,
  topK: 20
});
console.log(`Match rate: ${(replay.matchRate * 100).toFixed(1)}%`);

// Delete session
await mem.sessionDelete(sessionId);
```

## TypeScript Types

The SDK is fully typed:

```typescript theme={null}
import type {
  PutInput,
  PutManyInput,
  FindInput,
  AskInput,
  MemoryCard,
  MemoryCardInput,
  EntityState,
  FrameInfo,
  TableInfo,
  SessionSummary,
  MemvidErrorCode
} from '@memvid/sdk';

const options: FindInput = {
  mode: 'auto',
  k: 5,
  adaptive: true,
  minRelevancy: 0.5
};

const putInput: PutInput = {
  title: 'Document',
  text: 'Content...',
  enableEmbedding: true,
  embeddingModel: 'bge-small'
};
```

## Error Handling

```typescript theme={null}
import {
  MemvidError,
  CapacityExceededError,
  LockedError,
  VecDimensionMismatchError,
  EmbeddingFailedError,
  EncryptedFileError
} from '@memvid/sdk';

try {
  await mem.put({ title: 'Doc', text: 'Content' });
} catch (error) {
  if (error instanceof CapacityExceededError) {
    console.error('Storage full:', error.details);
  } else if (error instanceof LockedError) {
    console.error('File locked, try read-only mode');
  } else if (error instanceof VecDimensionMismatchError) {
    console.error('Embedding dimension mismatch:', error.details);
  } else if (error instanceof EmbeddingFailedError) {
    console.error('Embedding failed:', error.details);
  } else if (error instanceof EncryptedFileError) {
    console.error('File is encrypted, use unlock() first');
  } else if (error instanceof MemvidError) {
    console.error(`Error [${error.code}]: ${error.message}`);
  } else {
    throw error;
  }
}
```

| Error Class                 | Code  | Description                    |
| --------------------------- | ----- | ------------------------------ |
| `CapacityExceededError`     | MV001 | Storage limit reached          |
| `TicketInvalidError`        | MV002 | Invalid ticket signature       |
| `TicketReplayError`         | MV003 | Ticket replay detected         |
| `LexIndexDisabledError`     | MV004 | Lexical search not enabled     |
| `TimeIndexMissingError`     | MV005 | Time index missing             |
| `VerifyFailedError`         | MV006 | Verification failed            |
| `LockedError`               | MV007 | File locked by another process |
| `ApiKeyRequiredError`       | MV008 | API key required               |
| `MemoryAlreadyBoundError`   | MV009 | Memory already bound           |
| `FrameNotFoundError`        | MV010 | Requested frame doesn't exist  |
| `VecIndexDisabledError`     | MV011 | Vector search not enabled      |
| `CorruptFileError`          | MV012 | Corrupt file detected          |
| `IOError`                   | MV013 | I/O error                      |
| `VecDimensionMismatchError` | MV014 | Wrong embedding dimension      |
| `EmbeddingFailedError`      | MV015 | Embedding generation failed    |
| `EncryptedFileError`        | MV016 | File is encrypted              |

See [Error Reference](/errors/reference) for complete documentation.

## Environment Variables

| Variable            | Description            |
| ------------------- | ---------------------- |
| `MEMVID_API_KEY`    | Dashboard API key      |
| `OPENAI_API_KEY`    | OpenAI API key         |
| `GEMINI_API_KEY`    | Google Gemini API key  |
| `MISTRAL_API_KEY`   | Mistral AI API key     |
| `ANTHROPIC_API_KEY` | Anthropic API key      |
| `COHERE_API_KEY`    | Cohere API key         |
| `VOYAGE_API_KEY`    | Voyage AI API key      |
| `NVIDIA_API_KEY`    | NVIDIA API key         |
| `MEMVID_MODELS_DIR` | Model cache directory  |
| `MEMVID_OFFLINE`    | Use cached models only |

## SDK Reference

<CardGroup cols={2}>
  <Card title="Overview" icon="book" href="/node-sdk/overview">
    Complete API reference with all methods
  </Card>

  <Card title="Examples" icon="code" href="/node-sdk/examples">
    TypeScript examples and patterns
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="SDK Recipes" icon="flask" href="/quickstart/sdk-recipes">
    Common patterns and recipes
  </Card>

  <Card title="Framework Integrations" icon="puzzle-piece" href="/frameworks/overview">
    Vercel AI, LangChain, and more
  </Card>
</CardGroup>
