> ## 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.

# API Reference

> Complete reference for all Memvid APIs

Comprehensive documentation for all Memvid APIs across CLI, Python SDK, Node.js SDK, and core Rust APIs.

## Quick Navigation

<CardGroup cols={2}>
  <Card title="REST API" icon="globe" href="/api-reference/rest-api">
    `https://api.memvid.com`

    HTTP REST API for cloud service access.
  </Card>

  <Card title="Python SDK" icon="python" href="/python-sdk/overview">
    `pip install memvid-sdk`

    Full Python API with type hints and async support.
  </Card>

  <Card title="Node.js SDK" icon="node-js" href="/node-sdk/overview">
    `npm install @memvid/sdk`

    TypeScript-first with full type definitions.
  </Card>

  <Card title="CLI Reference" icon="terminal" href="/cli/create-and-put">
    `memvid <command>`

    Command-line interface for all operations.
  </Card>

  <Card title="Core API" icon="cube" href="/core-api/open-and-mutate">
    `memvid-core`

    Low-level Rust API for open/mutate/search/ask.
  </Card>
</CardGroup>

***

## Core Operations

### Create / Open

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    import { use, create } from '@memvid/sdk';

    // Open existing or create if not exists
    const memAuto = await use('basic', 'knowledge.mv2', { mode: 'auto' });

    // Create new
    const memCreate = await use('basic', 'knowledge.mv2', { mode: 'create' });

    // Open existing
    const memOpen = await use('basic', 'knowledge.mv2', { mode: 'open' });

    // Shorthand
    const mem2 = await create('knowledge.mv2');
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from memvid_sdk import use, create

    # Open existing or create if not exists
    mem = use('basic', 'knowledge.mv2', mode='auto')

    # Create new (fails if exists)
    mem = use('basic', 'knowledge.mv2', mode='create')

    # Open existing (fails if not exists)
    mem = use('basic', 'knowledge.mv2', mode='open')

    # Shorthand for create
    mem = create('knowledge.mv2')
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    # Create new file
    memvid create knowledge.mv2

    # Open is implicit in other commands
    memvid find knowledge.mv2 --query "test"
    ```
  </Tab>
</Tabs>

### Put (Store)

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    // Store text content
    const frameId = await mem.put({
      title: 'Document Title',
      label: 'category',
      text: 'The content to store...',
      tags: ['tag1', 'tag2'],
      metadata: { author: 'John', date: '2024-01-15' },
    });

    // Store from file
    const frameId = await mem.put({
      title: 'PDF Document',
      label: 'documents',
      file: '/path/to/document.pdf',
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Store text content
    frame_id = mem.put({
        "title": "Document Title",
        "label": "category",
        "text": "The content to store...",
        "tags": ["tag1", "tag2"],
        "metadata": {"author": "John", "date": "2024-01-15"}
    })

    # Store from file
    frame_id = mem.put({
        "title": "PDF Document",
        "label": "documents",
        "file": "/path/to/document.pdf"
    })

    # Store from URL
    frame_id = mem.put({
        "title": "Web Page",
        "label": "web",
        "uri": "https://example.com/page"
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    # Store text
    memvid put knowledge.mv2 \
      --title "Document Title" \
      --label "category" \
      --text "The content to store..."

    # Store file
    memvid put knowledge.mv2 \
      --input document.pdf \
      --label "documents"

    # Store folder
    memvid put knowledge.mv2 \
      --input ./docs/ \
      --embeddings \
      --recursive
    ```
  </Tab>
</Tabs>

### Find (Search)

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    // Basic search
    const results = await mem.find('search query', { k: 10 });

    // With options
    const results = await mem.find('search query', {
      k: 10,
      mode: 'auto',
      scope: 'label:docs',
      snippetChars: 200,
    });

    // Access results
    for (const hit of results.hits) {
      console.log(`${hit.title} (score: ${hit.score})`);
      console.log(`  ${hit.snippet}`);
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Basic search
    results = mem.find("search query", k=10)

    # With options
    results = mem.find(
        "search query",
        k=10,                    # Number of results
        mode="auto",             # auto, lex, or sem
        scope="label:docs",      # Filter by label
        snippet_chars=200        # Snippet length
    )

    # Access results
    for hit in results.hits:
        print(f"{hit.title} (score: {hit.score})")
        print(f"  {hit.snippet}")
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    # Basic search
    memvid find knowledge.mv2 --query "search query"

    # With options
        memvid find knowledge.mv2 \
          --query "search query" \
          --top-k 10 \
          --mode auto \
          --json
    ```
  </Tab>
</Tabs>

### Ask (Q\&A)

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    // Basic question
    const answer = await mem.ask('What is the main feature?');
    console.log(answer.answer);

    // With options
    const answer = await mem.ask('What is the main feature?', {
      k: 5,
      mode: 'auto',
      model: 'openai:gpt-4o-mini',
      maskPii: true,
    });

    console.log(`Answer: ${answer.answer}`);
    console.log(`Sources: ${answer.sources.map(s => s.title)}`);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Basic question
    answer = mem.ask("What is the main feature?")
    print(answer["answer"])

    # With options
    answer = mem.ask(
        "What is the main feature?",
        k=5,                     # Context documents
        mode="auto",             # Search mode
        model="openai:gpt-4o-mini",  # LLM model
        mask_pii=True            # Mask sensitive data
    )

    # Access answer details
    print(f"Answer: {answer.get('answer')}")
    print(f"Sources: {[s.get('title') for s in answer.get('sources', [])]}")
    print(f"Context: {answer.get('context')}")
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    # Basic question
    memvid ask knowledge.mv2 --question "What is the main feature?"

    # With options
        memvid ask knowledge.mv2 \
          --question "What is the main feature?" \
          --top-k 5 \
          --mode hybrid \
          --json
    ```
  </Tab>
</Tabs>

### Timeline

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    // Get recent entries
    const timeline = await mem.timeline({ limit: 50 });

    // With time range
    const timeline = await mem.timeline({
      limit: 50,
      since: 1700000000,
      until: 1710000000,
      reverse: true,
    });

    for (const entry of timeline.entries) {
      console.log(`[${entry.timestamp}] ${entry.title}`);
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Get recent entries
    timeline = mem.timeline(limit=50)

    # With time range
    timeline = mem.timeline(
        limit=50,
        since=1700000000,        # Unix timestamp
        until=1710000000,
        reverse=True             # Newest first
    )

    for entry in timeline.entries:
        print(f"[{entry.timestamp}] {entry.title}")
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    # Recent entries
    memvid timeline knowledge.mv2 --limit 50

    # With time range
    memvid timeline knowledge.mv2 \
      --since 1700000000 \
      --until 1710000000 \
      --reverse
    ```
  </Tab>
</Tabs>

### Stats

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    const stats = await mem.stats();
    console.log(`Frames: ${stats.frame_count}`);
    console.log(`Size: ${stats.size_bytes} bytes`);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    stats = mem.stats()
    print(f"Frames: {stats['frame_count']}")
    print(f"Size: {stats['size_bytes']} bytes")
    print(f"Capacity: {stats['capacity_bytes']} bytes")
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    memvid stats knowledge.mv2 --json
    ```
  </Tab>
</Tabs>

### Seal (Close)

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    // Always seal when done
    await mem.seal();
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Always seal when done to ensure data is written
    mem.seal()

    # Or use context manager
    with use('basic', 'knowledge.mv2') as mem:
        mem.put(...)
    # Automatically sealed
    ```
  </Tab>

  <Tab title="CLI">
    ```bash theme={null}
    # Explicit seal (usually not needed)
    memvid seal knowledge.mv2
    ```
  </Tab>
</Tabs>

***

## Types Reference

### PutInput

```typescript theme={null}
interface PutInput {
  title: string;           // Document title (required)
  label: string;           // Category label (required)
  text?: string;           // Text content
  file?: string;           // Path to file
  uri?: string;            // URL to fetch
  tags?: string[];         // Searchable tags
  labels?: string[];       // Additional labels
  metadata?: object;       // Custom metadata
  searchText?: string;     // Override search text
  enableEmbedding?: boolean; // Generate vectors
  autoTag?: boolean;       // Auto-generate tags
  extractDates?: boolean;  // Extract dates for timeline
}
```

### FindInput

```typescript theme={null}
interface FindInput {
  k?: number;              // Number of results (default: 10)
  mode?: 'auto' | 'lex' | 'sem';  // Search mode
  snippetChars?: number;   // Snippet length
  scope?: string;          // Filter expression
  cursor?: string;         // Pagination cursor
}
```

### AskInput

```typescript theme={null}
interface AskInput {
  k?: number;              // Context documents
  mode?: 'auto' | 'lex' | 'sem';  // Search mode
  model?: string;          // LLM model
  maskPii?: boolean;       // Mask sensitive data
  contextOnly?: boolean;   // Return context without LLM
  snippetChars?: number;   // Snippet length
  scope?: string;          // Filter expression
}
```

### SearchResult

```typescript theme={null}
interface SearchResult {
  hits: Hit[];             // Matching documents
  total: number;           // Total matches
  cursor?: string;         // Next page cursor
}

interface Hit {
  frameId: number;         // Document ID
  title: string;           // Document title
  label: string;           // Category label
  text: string;            // Full text
  snippet: string;         // Highlighted excerpt
  score: number;           // Relevance score
  metadata?: object;       // Custom metadata
}
```

### AskResult

```typescript theme={null}
interface AskResult {
  text: string;            // Generated answer
  answer: string;          // Alias for text
  sources: Source[];       // Source documents
  context: string;         // Aggregated context
  confidence?: number;     // Confidence score
}

interface Source {
  title: string;
  snippet: string;
  score: number;
}
```

***

## Error Handling

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

```python theme={null}
from memvid_sdk import (
    MemvidError,
    CapacityExceededError,
    TicketInvalidError,
    LockedError,
)

try:
    mem.put(...)
except CapacityExceededError:
    print("Storage full, upgrade your plan")
except LockedError:
    print("File locked by another process")
except MemvidError as e:
    print(f"Error [{e.code}]: {e.message}")
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Python SDK Guide" icon="python" href="/python-sdk/overview">
    Complete Python documentation
  </Card>

  <Card title="Node.js SDK Guide" icon="node-js" href="/node-sdk/overview">
    Complete Node.js documentation
  </Card>

  <Card title="CLI Reference" icon="terminal" href="/cli/create-and-put">
    All CLI commands
  </Card>

  <Card title="Error Reference" icon="circle-exclamation" href="/errors/reference">
    Error codes and solutions
  </Card>
</CardGroup>
