docs: nav restructure — the pitch is the structure

Developer Platform now reads: Start Here -> The Context Engine (concepts-
first: architecture, graph, hybrid search, profiles, permissioning,
surfaces) -> Using supermemory (+ versioning, errors-and-limits) ->
Building on supermemory (patterns) -> Connectors (+ faq, sync-lifecycle)
-> Ops and trust (analytics rejoins nav) -> Self-Hosting (+ tiers,
troubleshooting) -> Migration. container-tags/filtering fold into
permissioning/hybrid-search with redirects; 39 leftover files already
shadowed by redirects removed; every removed path redirects to its next
best page.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Dhravya Shah 2026-07-17 15:54:40 -07:00
parent 492e09bae2
commit 56666a663f
13 changed files with 59 additions and 3201 deletions

View file

@ -1,212 +0,0 @@
---
title: "Developer Platform"
description: "API updates, new endpoints, and SDK releases"
---
API updates, new endpoints, SDK releases, and developer-focused features.
## April 13, 2026
- **Google Drive scoped sync:** New connections default to a **hosted folder/file picker** after OAuth; only chosen items sync. Use `metadata.syncScope: "full"` to sync the whole Drive. Import jobs **skip** scoped connections until a selection exists.
## March 18, 2026
- **Supermemory CLI:** New command-line tool for managing memories, documents, profiles, tags, connectors, and API keys directly from the terminal.
- **PPTX Support:** PowerPoint files (`.pptx`) are now a supported content type for ingestion.
- **Multiple containerTags on Scoped API Keys:** Scoped API keys can now be assigned to multiple container tags, allowing a single key to access several spaces.
- **Documents Page in Console:** New dedicated documents browser in the console for viewing, filtering, and managing all ingested content.
- **`@supermemory/tools` v1.4.1:** Now exposes raw `searchResults` in `MemoryPromptData`, giving full control over how retrieved memories are formatted in prompts.
## March 12, 2026
- **Audio Extraction:** Ingest audio files with automatic transcription powered by Gemini 2.5 Flash. Audio content is transcribed, chunked, and indexed like any other document.
- **Delete Connection Without Documents:** Disconnect an external source (Google Drive, Notion, etc.) without deleting the documents it synced.
- **Org-Level Overage Toggle:** Control overage billing per-organization with a new toggle in the billing settings.
- **Retry Failed Documents:** Documents that previously failed ingestion can now be retried by re-submitting with the same `customId`.
- **Copyable Team Invite Link:** Team management page now includes a shareable invite link.
## March 9, 2026
- **Delete Scoped API Keys:** New `DELETE` endpoint to disable scoped API keys programmatically.
- **`supermemory-agent-framework` Python Package:** Official Python package for using Supermemory with Microsoft's Agent Framework — memory tools and middleware out of the box.
- **OpenAI SDK Backfill:** Improved compatibility across `supermemory-openai-sdk` (Python) and `@supermemory/tools` (TypeScript) OpenAI integrations.
- **Bulk Delete in Nova:** Bulk document deletion now available in the Nova app interface.
## March 5, 2026
- **`extends` Relation Type:** Memory graph now supports `extends` as a relation type, enabling richer knowledge graph connections between documents.
- **Interactive Memory Graph in MCP:** The MCP server now includes an interactive graph visualization app for exploring memory connections from any MCP-compatible client.
- **Plugin Auth Connect Page:** New OAuth-style connect page for plugin integrations (Claude Code, OpenCode, OpenClaw).
- **ViaSocket Integration:** New integration guide for connecting Supermemory with ViaSocket automation workflows.
## March 2, 2026
- **Configurable Vector Stores:** Bring your own vector store — Supermemory now supports pluggable vector backends beyond the default.
- **List Memories Endpoint:** New `GET /v3/documents` endpoint with pagination, filtering by container tag, status, and metadata.
## February 26, 2026
- **Self-Hostable Supermemory:** Run the full Supermemory stack on your own infrastructure with Docker.
- **Console v2:** Complete redesign of the developer console with new navigation, improved billing, and a unified project view.
- **No More 120 Memory Limit:** The previous cap of 120 memories per container tag has been removed. Store unlimited memories.
## February 22, 2026
- **Supermemory Skill for Claude Code:** Install with `npx skills add supermemoryai/skills` — teaches Claude to proactively recommend and implement Supermemory when building AI apps that need persistent memory, user profiles, or semantic search. Includes ready-to-use TypeScript and Python examples.
- **Metadata Filtering for Profiles:** User profile search now supports metadata-based filtering for more targeted profile queries.
- **List Documents with Multiple Container Tags:** New `operator` parameter to query documents spanning multiple container tags.
- **Deprecate `include: chunks`:** The `include: chunks` parameter in `/v4/search` is deprecated in favor of the `hybrid` search mode.
## February 9, 2026
- **Unified Organizations:** Consumer and developer organizations merged into a single org type. All orgs can now access both Nova and the developer API.
- **Credits-Based Usage Display:** Billing now shows token usage in a credits-based format.
- **Nova Spaces with Multi-Select:** Spaces in Nova now support multi-select, replacing "All Spaces" with scoped "Nova Spaces."
## February 6, 2026
- **Scoped API Keys for Container Tags:** Create API keys scoped to specific container tags for fine-grained access control per space.
- **DELETE Endpoint for Container Tags:** New endpoint to delete container tags and their associated document relationships.
- **Container Tag-Level Context Prompts:** Set custom context prompts per container tag to control how memories are extracted and summarized within each space.
## February 3, 2026
- **New Integration Docs:** Added guides for LangGraph, OpenAI Agents SDK, CrewAI, Agno, Mastra, and LangChain — covering all major AI agent frameworks.
- **Claude Code Integration:** Official integration page for using Supermemory as persistent memory in Claude Code.
- **Entity Context Documentation:** New docs on how entity extraction and context enrichment work in the memory pipeline.
- **Authentication Docs:** Comprehensive authentication page with code examples for API key auth, OAuth, and scoped keys.
## January 25, 2026
- **Plugin Authentication System:** New auth system for external tool integrations, enabling secure plugin-to-API connections.
- **Enterprise Plan Support:** Enterprise tier now available in the console with dedicated billing and support options.
- **Plugin Catalog:** Dedicated plugin page with auth flows for Claude Code, OpenCode, and OpenClaw integrations.
- **`@supermemory/tools` — Strict Mode:** Strict mode support for OpenAI function calling, ensuring schema-validated tool calls.
## January 14, 2026
- **Hybrid PDF Pipeline:** PDF extraction now uses Mistral OCR 3 with Gemini fallback for significantly improved accuracy on scanned documents and complex layouts.
- **Halfvec Embeddings:** Embedding storage optimized with half-precision vectors, reducing storage costs while maintaining search quality.
- **Spaces Creation with Emoji:** Create and customize spaces with emoji identifiers in Nova.
## January 8, 2026
- **Gmail Connector:** New connector to sync Gmail threads into Supermemory. Threads are stored in R2 for reliable processing of large mailboxes.
- **Container Tag Filters:** Filter documents by container tag in list and search endpoints.
- **Pagination Improvements:** Improved pagination and document view across the console.
- **`supermemory-pipecat` Python Package:** New SDK for integrating Supermemory with Pipecat voice AI pipelines, including Gemini Live speech-to-speech support.
- **`@supermemory/tools` — Prompt Templates:** Customize how memory context is formatted in AI SDK integrations with the new `promptTemplate` option.
## December 30, 2025
- **MCP 4.0:** Major MCP server update with session configuration, project-aware tools on every init, and backward-compatible 3.0 support. Includes the new `context` prompt for automatic user profile injection.
- **S3 Connector:** New connector to sync documents from Amazon S3 buckets, with console UI for bucket configuration.
- **Memory Graph Revamp:** Complete rewrite of `@supermemory/memory-graph` with improved visualization and performance.
## December 24, 2025
- **`@supermemory/tools` — Vercel AI SDK v5/v6:** Now supports both Vercel AI SDK v5 and v6, with automatic version detection.
- **Conversation Support in SDKs:** `supermemory` (TypeScript) and `supermemory-openai-sdk` (Python) now support the conversations API for multi-turn chat with memory.
- **MemoryBench:** New open-source benchmark suite for evaluating memory systems, with documentation and CLI.
## December 17, 2025
- **Hybrid Search Mode:** New `hybrid` search mode in `/v4/search` combining semantic and keyword search for better recall on technical queries.
## December 9, 2025
- **Firecrawl Integration:** Web crawling powered by Firecrawl for more reliable extraction of website content, with fallback support.
- **Custom GitHub Credentials:** Bring your own GitHub OAuth app credentials for the GitHub connector, enabling private repo access.
- **API Key Expiration Emails:** API keys now trigger email notifications before expiration.
- **Connector Sync Logs:** Connection syncs now produce detailed logs visible in the console.
## December 2, 2025
- **Organization Deletion:** Organizations can now be fully deleted from the console, including all associated data.
- **Billing Page Redesign:** New billing layout with invoicing support and improved usage visibility.
- **Console Onboarding Improvements:** Streamlined onboarding flow for new users.
## December 5, 2025
- **`@supermemory/tools` — Browser API Key Support:** `apiKey` can now be passed via options instead of relying on `process.env`, enabling browser-based usage of the tools package.
## November 17, 2025
- **Web Crawler Connector:** New connector to crawl and index entire websites with configurable depth and URL patterns.
- **`@supermemory/memory-graph` Package:** New package for building interactive graph visualizations of memory connections, with a standalone playground.
- **OpenAI Responses API Support:** `@supermemory/tools` OpenAI integration now supports the Responses API.
- **`supermemory-openai-sdk` — Python Middleware:** New `withSupermemory` middleware for the Python OpenAI SDK, enabling transparent memory injection into OpenAI API calls.
- **Browser Extension Webpage Capture:** Chrome extension can now capture full webpage content with markdown conversion, not just bookmarks.
- **Bulk Memory Optimization:** Memory creation now uses bulk inserts for significantly faster batch ingestion.
## October 27, 2025
- **Enhanced Filtering Capabilities:** Major improvements to the search filtering API with new `string_contains` filter type for partial string matching, `ignoreCase` option for case-insensitive string operations, and improved negation support across all filter types including proper numeric equality negation. The implementation also includes enhanced SQL injection protection and wildcard escaping for improved security.
## September 17, 2025
- **Forgotten Memories Search:** New `include.forgottenMemories` parameter in v4 search API allows searching through memories that have been explicitly forgotten or expired. Set to `true` to include forgotten memories in search results, helping recover previously archived information.
## September 14, 2025
- **Enhanced Delete API:** `DELETE /v3/documents/:id` endpoint now supports both internal document ID and customId for flexible document deletion. Developers can now delete documents using the same customId provided during creation, improving API consistency with other endpoints.
- **API Terminology Clarification:** Refined API terminology from "memories" to "documents" for improved developer clarity. New `/v3/documents/*` endpoints provide more intuitive naming while maintaining full backward compatibility via automatic redirects from `/v3/memories/*`. No action required from existing integrations.
## September 13, 2025
- **Documentation v2.0:** Complete rewrite with comprehensive API references, cookbook recipes, and production-ready examples for TypeScript, Python, and cURL
- **AI SDK Integration:** New `@supermemory/tools/ai-sdk` package for native Vercel AI SDK integration with memory tools and infinite chat capabilities
- **Bulk Delete Endpoint:** New `DELETE /v3/documents/bulk` endpoint for efficient memory management
## September 5, 2025
- **Memory Search Endpoint:** New `/v4/search` endpoint optimized for conversational AI and memory retrieval (vs document search)
- **Advanced Memory Management:** Enhanced update/delete operations with better filtering and batch processing capabilities
## August 30, 2025
- **MCP (Model Context Protocol) Server:** Launch of supermemory MCP server for AI model integrations with full project support and auto-detection
- **Enhanced Filtering API:** Improved SQL-based filtering with array_contains, numeric operators, and complex AND/OR logic
## August 15, 2025
- **Memory Router Proxy:** Enhanced proxy functionality for LLM requests with automatic context management and token optimization
- **Search Algorithm Updates:** Configurable similarity thresholds, reranking, and query rewriting for better result quality
## April 30, 2025
- **Comprehensive API Documentation:** New interactive API references with detailed parameter explanations and response schemas
- **Container Tags System:** Enhanced organizational grouping for better memory isolation and user-scoped content
- **Auto Content Type Detection:** Automatic processing of PDFs, images, videos, and web content regardless of URL extensions
## April 28, 2025
- **Google Drive Connector API:** New endpoints for programmatic Google Drive integration and file syncing
## April 25, 2025
- **Search Threshold Controls:** New `documentThreshold` and `chunkThreshold` parameters for fine-tuning search sensitivity
- **Document-Specific Search:** New `docId` parameter to search within specific large documents
- **Enhanced Chunk Control:** `onlyMatchingChunks` parameter for precise result filtering
## April 24, 2025
- **Query Rewriting API:** Automatic query expansion and intent matching for better search results
- **Search Context Options:** New `includeFullDocs` and `includeSummary` parameters for comprehensive document retrieval
## April 18, 2025
- **Enhanced Content Processing:** Improved ingestion pipeline supporting direct URL processing for images, videos, and PDFs
- **Stable Web Ingestion:** More reliable processing of website URLs with better content extraction
## April 14, 2025
- **Team API Endpoints:** New endpoints for team management and permission control
- **Enhanced Analytics API:** Better observability with detailed usage metrics and performance data
## February 1, 2025
- **Multi-Space Search:** Search across multiple container tags simultaneously with array parameter support
- **API Versioning:** Migration to `/v1` endpoints with improved versioning strategy
- **Interactive API Playground:** New testing interface for all endpoints with live examples

View file

@ -77,7 +77,7 @@
"anchor": "Developer Platform",
"pages": [
{
"group": "Getting Started",
"group": "Start Here",
"pages": [
"intro",
"quickstart",
@ -85,28 +85,20 @@
]
},
{
"group": "Self-Hosting",
"pages": [
"self-hosting/overview",
"self-hosting/quickstart",
"self-hosting/configuration",
"self-hosting/embeddings",
"self-hosting/local-vs-enterprise"
]
},
{
"group": "Concepts",
"group": "The Context Engine",
"pages": [
"concepts/architecture",
"concepts/how-it-works",
"concepts/graph-memory",
"concepts/content-types",
"concepts/super-rag",
"concepts/memory-vs-rag",
"concepts/container-tags",
"concepts/filtering",
"concepts/hybrid-search",
"concepts/user-profiles",
"concepts/permissioning",
"concepts/surfaces",
"concepts/memory-vs-rag",
"concepts/super-rag",
"concepts/content-types",
"concepts/customization",
"authentication"
"concepts/glossary"
]
},
{
@ -124,6 +116,21 @@
"memory-review"
]
},
"versioning",
"errors-and-limits",
"authentication"
]
},
{
"group": "Building on supermemory",
"pages": [
"patterns/overview",
"patterns/multi-tenant-saas",
"patterns/ai-companion",
"patterns/multi-agent",
"patterns/agent-task-memory",
"patterns/company-brain",
"patterns/ingestion",
"overview/use-cases"
]
},
@ -145,10 +152,32 @@
"connectors/web-crawler"
]
},
"connectors/faq",
"connectors/sync-lifecycle",
"connectors/troubleshooting",
"memory-api/connectors/managing-resources"
]
},
{
"group": "Ops and trust",
"pages": [
"trust/usage-and-billing",
"trust/security",
"analytics"
]
},
{
"group": "Self-Hosting",
"pages": [
"self-hosting/overview",
"self-hosting/quickstart",
"self-hosting/tiers",
"self-hosting/configuration",
"self-hosting/embeddings",
"self-hosting/troubleshooting",
"self-hosting/local-vs-enterprise"
]
},
{
"group": "Migration Guides",
"pages": [
@ -176,7 +205,8 @@
"pages": [
"supermemory-mcp/claude-desktop"
]
}
},
"supermemory-mcp/troubleshooting"
]
},
{
@ -447,7 +477,7 @@
"source": "/zapier"
},
{
"destination": "/concepts/filtering",
"destination": "/concepts/hybrid-search",
"permanent": true,
"source": "/search/filtering"
},
@ -690,7 +720,7 @@
},
{
"source": "/memory-api/features/filtering",
"destination": "/concepts/filtering"
"destination": "/concepts/hybrid-search"
},
{
"source": "/memory-api/features/query-rewriting",
@ -707,6 +737,14 @@
{
"source": "/memory-api/connectors/creating-connection",
"destination": "/connectors/overview"
},
{
"source": "/concepts/container-tags",
"destination": "/concepts/permissioning"
},
{
"source": "/concepts/filtering",
"destination": "/concepts/hybrid-search"
}
],
"styling": {

View file

@ -1,860 +0,0 @@
---
title: "Ingest Documents and Data"
sidebarTitle: "Ingesting content guide"
description: "Complete guide to ingesting text, URLs, files, and various content types into Supermemory"
---
Supermemory provides a powerful and flexible ingestion system that can process virtually any type of content. Whether you're adding simple text notes, web pages, PDFs, images, or complex documents from various platforms, our API handles it all seamlessly.
## Understanding the Mental Model
Before diving into the API, it's important to understand how Supermemory processes your content:
### Documents vs Memories
- **Documents**: Anything you put into Supermemory (files, URLs, text) is considered a **document**
- **Memories**: Documents are automatically chunked into smaller, searchable pieces called **memories**
When you use the "Add Memory" endpoint, you're actually adding a **document**. Supermemory's job is to intelligently break that document into optimal **memories** that can be searched and retrieved.
```
Your Content → Document → Processing → Multiple Memories
↓ ↓ ↓ ↓
PDF File → Stored Doc → Chunking → Searchable Memories
```
You can visualize this process in the [Supermemory Console](https://console.supermemory.ai) where you'll see a graph view showing how your documents are broken down into interconnected memories.
### Content Sources
Supermemory accepts content through three main methods:
1. **Direct API**: Upload files or send content via API endpoints
2. **Connectors**: Automated integrations with platforms like Google Drive, Notion, and OneDrive ([learn more about connectors](/connectors))
3. **URL Processing**: Automatic extraction from web pages, videos, and social media
## Overview
The ingestion system consists of several key components:
- **Multiple Input Methods**: JSON content, file uploads, and URL processing
- **Asynchronous Processing**: Background workflows handle content extraction and chunking
- **Auto Content Detection**: Automatically identifies and processes different content types
- **Space Organization**: Container tags group related memories for better context inference
- **Status Tracking**: Real-time status updates throughout the processing pipeline
### How It Works
<Steps>
<Step title="Submit Document">
Send your content (text, file, or URL) to create a new document
</Step>
<Step title="Validation">
API validates the request and checks rate limits/quotas
</Step>
<Step title="Document Storage">
Your content is stored as a document and queued for processing
</Step>
<Step title="Content Extraction">
Specialized extractors process the document based on its type
</Step>
<Step title="Memory Creation">
Document is intelligently chunked into multiple searchable memories
</Step>
<Step title="Embedding & Indexing">
Memories are converted to vector embeddings and made searchable
</Step>
</Steps>
## Ingestion Endpoints
### Add Document - JSON Content
The primary endpoint for adding content that will be processed into documents.
**Endpoint:** `POST /v3/documents`
<Note>
Despite the endpoint name, you're creating a **document** that Supermemory will automatically chunk into searchable **memories**.
</Note>
<CodeGroup>
```bash cURL
curl https://api.supermemory.ai/v3/documents \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "Machine learning is a subset of artificial intelligence that enables computers to learn and make decisions from data without explicit programming.",
"containerTags": ["ai-research", "user_123"],
"metadata": {
"source": "research-notes",
"category": "education",
"priority": "high"
},
"customId": "ml-basics-001"
}'
```
```typescript TypeScript
import Supermemory from 'supermemory'
const client = new Supermemory({
apiKey: process.env.SUPERMEMORY_API_KEY
})
async function addContent() {
const result = await client.add({
content: "Machine learning is a subset of artificial intelligence...",
containerTags: ["ai-research"],
metadata: {
source: "research-notes",
category: "education",
priority: "high"
},
customId: "ml-basics-001"
})
console.log(result) // { id: "abc123", status: "queued" }
}
addContent()
```
```python Python
from supermemory import Supermemory
import os
client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
result = client.add(
content="Machine learning is a subset of artificial intelligence...",
container_tags=["ai-research"],
metadata={
"source": "research-notes",
"category": "education",
"priority": "high"
},
custom_id="ml-basics-001"
)
print(result) # { "id": "abc123", "status": "queued" }
```
</CodeGroup>
#### Request Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | The content to process into a document. Can be text, URL, or other supported formats |
| `containerTag` | string | No | **Recommended**: Single tag to group related memories in a space. Defaults to `"sm_project_default"` |
| `containerTags` | string[] | No | Legacy array format. Use `containerTag` instead for better performance |
| `metadata` | object | No | Additional key-value metadata (strings, numbers, booleans only) |
| `customId` | string | No | Your own identifier for this document (max 255 characters) |
| `raw` | string | No | Raw content to store alongside processed content |
#### Response
When you successfully create a document, you'll get back a simple confirmation with the document ID and its initial processing status:
```json
{
"id": "D2Ar7Vo7ub83w3PRPZcaP1",
"status": "queued"
}
```
**What this means:**
- `id`: Your document's unique identifier - save this to track processing or reference later
- `status`: Current processing state. `"queued"` means it's waiting to be processed into memories
<Note>
The document starts processing immediately in the background. Within seconds to minutes (depending on content size), it will be chunked into searchable memories.
</Note>
### File Upload: Drop and Process
Got a PDF, image, or video? Upload it directly and let Supermemory extract the valuable content automatically.
**Endpoint:** `POST /v3/documents/file`
**What makes this powerful:** Instead of manually copying text from PDFs or transcribing videos, just upload the file. Supermemory handles OCR for images, transcription for videos, and intelligent text extraction for documents.
<CodeGroup>
```bash cURL
curl https://api.supermemory.ai/v3/documents/file \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-F "file=@document.pdf" \
-F "containerTags=research_project"
# Response:
# {
# "id": "Mx7fK9pL2qR5tE8yU4nC7",
# "status": "processing"
# }
```
```typescript TypeScript
import Supermemory from 'supermemory'
import fs from 'fs'
const client = new Supermemory({
apiKey: process.env.SUPERMEMORY_API_KEY
})
// Method 1: Using SDK uploadFile method (RECOMMENDED)
const result = await client.documents.uploadFile({
file: fs.createReadStream('/path/to/document.pdf'),
containerTags: 'research_project' // String, not array!
})
// Method 2: Using fetch with form data (for browser/manual implementation)
const formData = new FormData()
formData.append('file', fileInput.files[0])
formData.append('containerTags', 'research_project')
const response = await fetch('https://api.supermemory.ai/v3/documents/file', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`
},
body: formData
})
const result = await response.json()
console.log(result)
// Output: { id: "Mx7fK9pL2qR5tE8yU4nC7", status: "processing" }
```
```python Python
from supermemory import Supermemory
client = Supermemory(api_key="your_api_key")
# Method 1: Using SDK upload_file method (RECOMMENDED)
result = client.documents.upload_file(
file=open('document.pdf', 'rb'),
container_tags='research_project' # String parameter name
)
# Method 2: Using requests with form data
import requests
files = {'file': open('document.pdf', 'rb')}
data = {'containerTags': 'research_project'}
response = requests.post(
'https://api.supermemory.ai/v3/documents/file',
headers={'Authorization': f'Bearer {api_key}'},
files=files,
data=data
)
result = response.json()
print(result)
# Output: {'id': 'Mx7fK9pL2qR5tE8yU4nC7', 'status': 'processing'}
```
</CodeGroup>
#### Supported File Types
<Tabs>
<Tab title="Documents">
- **PDF**: Extracted with OCR support for scanned documents
- **Google Docs**: Via Google Drive API integration
- **Google Sheets**: Spreadsheet content extraction
- **Google Slides**: Presentation content extraction
- **Notion Pages**: Rich content with block structure preservation
- **OneDrive Documents**: Microsoft Office documents
</Tab>
<Tab title="Media">
- **Images**: JPG, PNG, GIF, WebP with OCR text extraction
- **Videos**: MP4, WebM, AVI with transcription (YouTube, Vimeo)
</Tab>
<Tab title="Web Content">
- **Web Pages**: Any public URL with intelligent content extraction
- **Twitter/X Posts**: Tweet content and metadata
- **YouTube Videos**: Automatic transcription and metadata
</Tab>
<Tab title="Text Formats">
- **Plain Text**: TXT, MD, CSV files
</Tab>
</Tabs>
## Content Types & Processing
### Automatic Detection
Supermemory automatically detects content types based on:
- **URL patterns**: Domain and path analysis for special services
- **MIME types**: File type detection from headers/metadata
- **Content analysis**: Structure and format inspection
- **File extensions**: Fallback identification method
```typescript
type MemoryType =
| 'text' // Plain text content
| 'pdf' // PDF documents
| 'tweet' // Twitter/X posts
| 'google_doc' // Google Docs
| 'google_slide'// Google Slides
| 'google_sheet'// Google Sheets
| 'image' // Images with OCR
| 'video' // Videos with transcription
| 'notion_doc' // Notion pages
| 'webpage' // Web pages
| 'onedrive' // OneDrive documents
// Examples of automatic detection
const examples = {
"https://twitter.com/user/status/123": "tweet",
"https://youtube.com/watch?v=abc": "video",
"https://docs.google.com/document/d/123": "google_doc",
"https://docs.google.com/spreadsheets/d/123": "google_sheet",
"https://docs.google.com/presentation/d/123": "google_slide",
"https://notion.so/page-123": "notion_doc",
"https://example.com": "webpage",
"Regular text content": "text",
// PDF files uploaded → "pdf"
// Image files uploaded → "image"
// OneDrive links → "onedrive"
}
```
### Processing Pipeline
Each content type follows a specialized processing pipeline:
<Accordion title="Text Content" defaultOpen>
Content is cleaned, normalized, and chunked for optimal retrieval:
1. **Queued**: Memory enters the processing queue
2. **Extracting**: Text normalization and cleaning
3. **Chunking**: Intelligent splitting based on content structure
4. **Embedding**: Convert to vector representations for search
5. **Indexing**: Add to searchable index
6. **Done:** Metadata extraction completed
</Accordion>
<Accordion title="Web Content">
Web pages undergo sophisticated content extraction:
1. **Queued:** URL queued for processing
2. **Extracting**: Fetch page content with proper headers, remove navigation and boilerplate, extract title, description, etc.
3. **Chunking:** Content split for optimal retrieval
4. **Embedding**: Vector representation generation
5. **Indexing**: Add to search index
6. **Done:** Processing complete with `type: 'webpage'`
</Accordion>
<Accordion title="File Processing">
Files are processed through specialized extractors:
1. **Queued**: File queued for processing
2. **Content Extraction**: Type detection and format-specific processing.
3. **OCR/Transcription**: For images and media files
4. **Chunking:** Content broken down into searchable segments
5. **Embedding:** Vector representation creation
6. **Indexing:** Add to search index
7. **Done:** Processing completed
</Accordion>
## Error Handling
### Common Errors
Scroll right to see more.
<Tabs>
<Tab title="Authentication Errors">
```json
// AuthenticationError class
{
name: "AuthenticationError",
status: 401,
message: "401 Unauthorized",
error: {
message: "Invalid API key",
type: "authentication_error"
}
}
```
**Causes:**
- Missing or invalid API key
- Expired authentication token
- Incorrect authorization header format
</Tab>
<Tab title="Bad Request Errors (400)">
```json
// BadRequestError class
{
name: "BadRequestError",
status: 400,
message: "400 Bad Request",
error: {
message: "Invalid request parameters",
details: {
content: "Content cannot be empty",
customId: "customId exceeds maximum length"
}
}
}
```
**Causes:**
- Missing required fields
- Invalid parameter types
- Content too large
- Custom ID too long
- Invalid metadata structure
</Tab>
<Tab title="Rate Limiting (429)">
```json
// RateLimitError class
{
name: "RateLimitError",
status: 429, // NOT 402!
message: "429 Too Many Requests",
error: {
message: "Rate limit exceeded",
retry_after: 60
}
}
```
**Causes:**
- Monthly token quota exceeded
- Rate limits exceeded
- Subscription limits reached
**Fix:** Implement exponential backoff and respect rate limits
</Tab>
<Tab title="Not Found Errors (404)">
```json
// NotFoundError class
{
name: "NotFoundError",
status: 404,
message: "404 Not Found",
error: {
message: "Memory not found",
resource_id: "invalid_memory_id"
}
}
```
Causes:
- Memory ID doesn't exist
- Memory was deleted
- Invalid endpoint URL
</Tab>
<Tab title="Permission Denied (403)">
```json
// PermissionDeniedError class
{
name: "PermissionDeniedError",
status: 403,
message: "403 Forbidden",
error: {
message: "Insufficient permissions",
required_permission: "memories:write"
}
}
```
Causes:
- API key lacks required permissions
- Accessing restricted resources
- Account limitations
</Tab>
<Tab title="Server Errors (500+)">
```json
// InternalServerError class
{
name: "InternalServerError",
status: 500,
message: "500 Internal Server Error",
error: {
message: "Processing failed",
details: "Content extraction service unavailable"
}
}
```
**Causes:**
- External service unavailable
- Content extraction failure
</Tab>
<Tab title="Network Errors">
```json
// APIConnectionError class - NEW
{
name: "APIConnectionError",
message: "Connection error.",
cause: Error // Original network error
}
// APIConnectionTimeoutError class - NEW
{
name: "APIConnectionTimeoutError",
message: "Request timed out."
}
```
Causes:
- Network connectivity issues
- DNS resolution failures
- Request timeouts
- Proxy/firewall blocking
</Tab>
</Tabs>
## Best Practices
### Container Tags: Optimize for Performance
Use single container tags for better query performance. Multiple tags are supported but increase latency.
```json
{
"content": "Updated authentication flow to use JWT tokens",
"containerTags": "[project_alpha]",
"metadata": {
"type": "technical_change",
"author": "sarah_dev",
"impact": "breaking"
}
}
```
**Single vs Multiple Tags**
```javascript
// ✅ Recommended: Single tag, faster queries
{ "containerTags": ["project_alpha"] }
// ⚠️ Allowed but slower: Multiple tags increase latency
{ "containerTags": ["project_alpha", "auth", "backend"] }
```
**Why single tags perform better:**
- Memories in the same space can reference each other efficiently
- Search queries don't need to traverse multiple spaces
- Connection inference is faster within a single space
### Custom IDs: Deduplication and Updates
Custom IDs prevent duplicates and enable document updates. Two update methods available.
**Method 1: POST with customId (Upsert)**
```bash
# Create document
curl -X POST "https://api.supermemory.ai/v3/documents" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "API uses REST endpoints",
"customId": "api_docs_v1",
"containerTags": ["project_alpha"]
}'
# Response: {"id": "abc123", "status": "queued"}
# Update same document (same customId = upsert)
curl -X POST "https://api.supermemory.ai/v3/documents" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "API migrated to GraphQL",
"customId": "api_docs_v1",
"containerTags": ["project_alpha"]
}'
```
**Method 2: PATCH by ID (Update)**
```bash
curl -X PATCH "https://api.supermemory.ai/v3/documents/abc123" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "API now uses GraphQL with caching",
"metadata": {"version": 3}
}'
```
**Custom ID Patterns**
```javascript
// External system sync
"jira_PROJ_123"
"confluence_456789"
"github_issue_987"
// Database entities
"user_profile_12345"
"order_67890"
// Versioned content
"meeting_2024_01_15"
"api_docs_auth"
"requirements_v3"
```
**Update Behavior**
- **Content changes:** Old memories are deleted, new memories created from updated content. Same document ID maintained.
- **Metadata-only changes:** Document metadata is updated in place. No reindexing—works with both internal `id` and `customId`.
### Rate Limits & Quotas
**Token Usage**
```javascript
"Hello world" // ≈ 2 tokens
"10-page PDF" // ≈ 2,000-4,000 tokens
"YouTube video (10 min)" // ≈ 1,500-3,000 tokens
"Web article" // ≈ 500-2,000 tokens
```
**Current Limits**
| Feature | Free | Starter | Growth |
|---------|------|-----|------------|
| Memory Tokens/month | 100,000 | 1,000,000 | 10,000,000 |
| Search Queries/month | 1,000 | 10,000 | 100,000 |
**Limit Exceeded Response**
```bash
curl -X POST "https://api.supermemory.ai/v3/documents" \
-H "Authorization: Bearer your_api_key" \
-d '{"content": "Some content"}'
```
Response:
```json
{"error": "Memory token limit reached", "status": 402}
```
## Batch Upload of Documents
Process large volumes efficiently with rate limiting and error recovery.
### Implementation Strategy
<Tabs>
<Tab title="TypeScript">
```typescript
import Supermemory, {
BadRequestError,
RateLimitError,
AuthenticationError
} from 'supermemory';
interface Document {
id: string;
content: string;
title?: string;
createdAt?: string;
metadata?: Record<string, string | number | boolean>;
}
async function batchIngest(documents: Document[], options = {}) {
const {
batchSize = 5,
delayBetweenBatches = 2000,
maxRetries = 3
} = options;
const results = [];
for (let i = 0; i < documents.length; i += batchSize) {
const batch = documents.slice(i, i + batchSize);
console.log(`Processing batch ${Math.floor(i/batchSize) + 1}/${Math.ceil(documents.length/batchSize)}`);
const batchResults = await Promise.allSettled(
batch.map(doc => ingestWithRetry(doc, maxRetries))
);
results.push(...batchResults);
// Rate limiting between batches
if (i + batchSize < documents.length) {
await new Promise(resolve => setTimeout(resolve, delayBetweenBatches));
}
}
return results;
}
async function ingestWithRetry(doc: Document, maxRetries: number) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await client.add({
content: doc.content,
customId: doc.id,
containerTags: ["batch_import_user_123"], // CORRECTED: Array
metadata: {
source: "migration",
batch_id: generateBatchId(),
original_created: doc.createdAt || new Date().toISOString(),
title: doc.title || "",
...doc.metadata
}
});
} catch (error) {
// CORRECTED: Proper error handling
if (error instanceof AuthenticationError) {
console.error('Authentication failed - check API key');
throw error; // Don't retry auth errors
}
if (error instanceof BadRequestError) {
console.error('Invalid document format:', doc.id);
throw error; // Don't retry validation errors
}
if (error instanceof RateLimitError) {
console.log(`Rate limited on attempt ${attempt}, waiting longer...`);
const delay = Math.pow(2, attempt) * 2000; // Longer delays for rate limits
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
if (attempt === maxRetries) throw error;
// Exponential backoff for other errors
const delay = Math.pow(2, attempt) * 1000;
console.log(`Retry ${attempt}/${maxRetries} for ${doc.id} in ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
function generateBatchId(): string {
return `batch_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
```
</Tab>
<Tab title="Python">
```python
import asyncio
import time
import logging
from typing import List, Dict, Any, Optional
from supermemory import Supermemory, BadRequestError, RateLimitError
async def batch_ingest(
documents: List[Dict[str, Any]],
options: Optional[Dict[str, Any]] = None
):
options = options or {}
batch_size = options.get('batch_size', 5) # CORRECTED: Conservative size
delay_between_batches = options.get('delay_between_batches', 2.0) # CORRECTED: 2 seconds
max_retries = options.get('max_retries', 3)
results = []
for i in range(0, len(documents), batch_size):
batch = documents[i:i + batch_size]
batch_num = i // batch_size + 1
total_batches = (len(documents) + batch_size - 1) // batch_size
print(f"Processing batch {batch_num}/{total_batches}")
# Process batch with proper error handling
tasks = [ingest_with_retry(doc, max_retries) for doc in batch]
batch_results = await asyncio.gather(*tasks, return_exceptions=True)
results.extend(batch_results)
# Rate limiting between batches
if i + batch_size < len(documents):
await asyncio.sleep(delay_between_batches)
return results
async def ingest_with_retry(doc: Dict[str, Any], max_retries: int):
for attempt in range(1, max_retries + 1):
try:
return await client.add(
content=doc['content'],
custom_id=doc['id'],
container_tags=["batch_import_user_123"], # CORRECTED: List
metadata={
"source": "migration",
"batch_id": generate_batch_id(),
"original_created": doc.get('created_at', ''),
"title": doc.get('title', ''),
**doc.get('metadata', {})
}
)
except BadRequestError as e:
logging.error(f"Invalid document {doc['id']}: {e}")
raise # Don't retry validation errors
except RateLimitError as e:
logging.warning(f"Rate limited on attempt {attempt}")
delay = 2 ** attempt * 2 # Longer delays for rate limits
await asyncio.sleep(delay)
continue
except Exception as error:
if attempt == max_retries:
raise error
# Exponential backoff
delay = 2 ** attempt
logging.info(f"Retry {attempt}/{max_retries} for {doc['id']} in {delay}s")
await asyncio.sleep(delay)
def generate_batch_id() -> str:
import random
import string
return f"batch_{int(time.time())}_{random.choices(string.ascii_lowercase, k=8)}"
```
</Tab>
</Tabs>
### Best Practices for Batch Operations
<Accordion title="Performance Optimization" defaultOpen>
- **Batch Size**: 3-5 documents at once
- **Delays**: 2-3 seconds between batches prevents rate limiting
- **Promise.allSettled()**: Handles mixed success/failure results
- **Progress Tracking**: Monitor long-running operations
**Sample Output**
```
Processing batch 1/50 (documents 1-3)
Successfully processed: 2/3 documents
Failed: 1/3 documents (BadRequestError: Invalid content)
Progress: 3/150 (2.0%) - Next batch in 2s
```
</Accordion>
<Accordion title="Error Handling">
- **Specific Error Types:** Handle `BadRequestError`, `RateLimitError`, `AuthenticationError` differently
- **No Retry Logic**: Don't retry validation or auth errors
- **Rate Limit Handling**: Longer backoff delays for rate limit errors
- **Logging**: Record failures for review/retry
</Accordion>
<Accordion title="Memory Management">
- **Streaming**: Process large files in chunks
- **Cleanup**: Clear processed batches from memory
- **Progress Persistence**: Resume interrupted migrations
</Accordion>
<Note>
Ready to start ingesting? [Get an API key](https://console.supermemory.ai) now!
</Note>

View file

@ -1,162 +0,0 @@
---
title: "Quickstart - 5 mins"
description: "Learn how to integrate supermemory into your application"
---
## Authentication
Head to [supermemory's Developer Platform](https://console.supermemory.ai) built to help you monitor and manage every aspect of the API.
All API requests require authentication using an API key. Include your API key as follows:
<CodeGroup>
```bash cURL
Authorization: Bearer YOUR_API_KEY
```
```typescript Typescript
// npm install supermemory
const client = new supermemory({
apiKey: "YOUR_API_KEY",
});
```
```python Python
# pip install supermemory
client = supermemory(
api_key="YOUR_API_KEY",
)
```
</CodeGroup>
## Installing the clients
You can use supermemory through the APIs, or using our SDKs
<CodeGroup>
```bash cURL
https://api.supermemory.ai/v3
```
```bash Typescript
npm i supermemory
```
```bash Python
pip install supermemory
```
</CodeGroup>
## Add your first memory
<CodeGroup>
```bash cURL
curl https://api.supermemory.ai/v3/documents \
--request POST \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
-d '{"content": "This is the content of my first memory."}'
```
```typescript Typescript
await client.memory.add({
content: "This is the content of my first memory.",
});
```
```python Python
client.memory.add(
content="This is the content of my first memory.",
)
```
</CodeGroup>
This will add a new memory to your supermemory account.
Try it out in the API Reference tab.
## Content Processing
<Accordion title="Processing steps" icon="sparkles">
When you add content to supermemory, it goes through several processing steps:
1. **Queued**: Initial state when content is submitted
2. **Extracting**: Content is being extracted from the source
3. **Chunking**: Content is being split into semantic chunks
4. **Embedding**: Generating vector embeddings for search
5. **Indexing**: Adding content to the search index
6. **Done**: Processing complete
</Accordion>
<Accordion title="Advanced Chunking" icon="sparkles">
The system uses advanced NLP techniques for optimal chunking:
- Sentence-level splitting for natural boundaries
- Context preservation with overlapping chunks
- Smart handling of long content
- Semantic coherence optimization
</Accordion>
## Search your memories
<CodeGroup>
```bash cURL
curl https://api.supermemory.ai/v3/search \
--request POST \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
-d '{"q": "This is the content of my first memory."}'
```
```typescript Typescript
await client.search.execute({
q: "This is the content of my first memory.",
});
```
```python Python
client.search.execute(
q="This is the content of my first memory.",
)
```
</CodeGroup>
Try it out in the API Reference tab.
You can do a lot more with supermemory, and we will walk through everything you need to.
Next, explore the features available in supermemory
<CardGroup cols={2}>
<Card title="Adding memories" icon="plus" href="/memory-api/creation/adding-memories">
Adding memories
</Card>
<Card
title="Searching and filtering"
icon="search"
href="/memory-api/searching/searching-memories"
>
Searching for items
</Card>
<Card
title="Connectors and Syncing"
icon="plug"
href="/memory-api/connectors/overview"
>
Connecting external sources
</Card>
<Card title="Features" icon="sparkles" href="/memory-api/features/filtering">
Explore Features
</Card>
</CardGroup>

View file

@ -1,68 +0,0 @@
---
title: 'Supermemory SDKs'
sidebarTitle: "Python and JavaScript SDKs"
description: 'Learn how to use supermemory with Python and JavaScript'
---
For more information, see the full updated references at
<Columns cols={2}>
<Card title="Python SDK" icon="python" href="https://pypi.org/project/supermemory/">
</Card>
<Card title="Javascript SDK" icon="js" href="https://www.npmjs.com/package/supermemory">
</Card>
</Columns>
## Python SDK
## Installation
```sh
# install from PyPI
pip install --pre supermemory
```
## Usage
```python
import os
from supermemory import Supermemory
client = Supermemory(
api_key=os.environ.get("SUPERMEMORY_API_KEY"), # This is the default and can be omitted
)
response = client.search.documents(
q="documents related to python",
)
print(response.results)
```
## JavaScript SDK
## Installation
```sh
npm install supermemory
```
## Usage
```js
import Supermemory from 'supermemory';
const client = new Supermemory({
apiKey: process.env['SUPERMEMORY_API_KEY'], // This is the default and can be omitted
});
async function main() {
const response = await client.search.documents({ q: 'documents related to python' });
console.debug(response.results);
}
main();
```

View file

@ -1,584 +0,0 @@
---
title: "OpenAI SDK Plugins"
description: "Memory tools for OpenAI function calling with Supermemory integration"
---
Add memory capabilities to the official OpenAI SDKs using Supermemory's function calling tools. These plugins provide seamless integration with OpenAI's chat completions and function calling features.
<CardGroup>
<Card title="Supermemory tools on npm" icon="npm" href="https://www.npmjs.com/package/@supermemory/tools">
Check out the NPM page for more details
</Card>
<Card title="Supermemory AI SDK" icon="python" href="https://pypi.org/project/supermemory-openai-sdk/">
Check out the PyPI page for more details
</Card>
</CardGroup>
## Installation
<CodeGroup>
```bash Python
# Using uv (recommended)
uv add supermemory-openai-sdk
# Or with pip
pip install supermemory-openai-sdk
```
```bash JavaScript/TypeScript
npm install @supermemory/tools
```
</CodeGroup>
## Quick Start
<CodeGroup>
```python Python SDK
import asyncio
import openai
from supermemory_openai import SupermemoryTools, execute_memory_tool_calls
async def main():
# Initialize OpenAI client
client = openai.AsyncOpenAI(api_key="your-openai-api-key")
# Initialize Supermemory tools
tools = SupermemoryTools(
api_key="your-supermemory-api-key",
config={"project_id": "my-project"}
)
# Chat with memory tools
response = await client.chat.completions.create(
model="gpt-5",
messages=[
{
"role": "system",
"content": "You are a helpful assistant with access to user memories."
},
{
"role": "user",
"content": "Remember that I prefer tea over coffee"
}
],
tools=tools.get_tool_definitions()
)
# Handle tool calls if present
if response.choices[0].message.tool_calls:
tool_results = await execute_memory_tool_calls(
api_key="your-supermemory-api-key",
tool_calls=response.choices[0].message.tool_calls,
config={"project_id": "my-project"}
)
print("Tool results:", tool_results)
print(response.choices[0].message.content)
asyncio.run(main())
```
```typescript JavaScript/TypeScript SDK
import { supermemoryTools, getToolDefinitions, createToolCallExecutor } from "@supermemory/tools/openai"
import OpenAI from "openai"
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY!,
})
// Get tool definitions for OpenAI
const toolDefinitions = getToolDefinitions()
// Create tool executor
const executeToolCall = createToolCallExecutor(process.env.SUPERMEMORY_API_KEY!, {
projectId: "your-project-id",
})
// Use with OpenAI Chat Completions
const completion = await client.chat.completions.create({
model: "gpt-5",
messages: [
{
role: "user",
content: "What do you remember about my preferences?",
},
],
tools: toolDefinitions,
})
// Execute tool calls if any
if (completion.choices[0]?.message.tool_calls) {
for (const toolCall of completion.choices[0].message.tool_calls) {
const result = await executeToolCall(toolCall)
console.log(result)
}
}
```
</CodeGroup>
## Configuration
### Memory Tools Configuration
<CodeGroup>
```python Python Configuration
from supermemory_openai import SupermemoryTools
tools = SupermemoryTools(
api_key="your-supermemory-api-key",
config={
"project_id": "my-project", # or use container_tags
"base_url": "https://custom-endpoint.com", # optional
}
)
```
```typescript JavaScript Configuration
import { supermemoryTools } from "@supermemory/tools/openai"
const tools = supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
containerTags: ["your-user-id"],
baseUrl: "https://custom-endpoint.com", // optional
})
```
</CodeGroup>
## Available Tools
### Search Memories
Search through user memories using semantic search:
<CodeGroup>
```python Python
# Search memories
result = await tools.search_memories(
information_to_get="user preferences",
limit=10,
include_full_docs=True
)
print(f"Found {len(result.memories)} memories")
```
```typescript JavaScript
// Search memories
const searchResult = await tools.searchMemories({
informationToGet: "user preferences",
limit: 10,
})
console.log(`Found ${searchResult.memories.length} memories`)
```
</CodeGroup>
### Add Memory
Store new information in memory:
<CodeGroup>
```python Python
# Add memory
result = await tools.add_memory(
memory="User prefers tea over coffee"
)
print(f"Added memory with ID: {result.memory.id}")
```
```typescript JavaScript
// Add memory
const addResult = await tools.addMemory({
memory: "User prefers dark roast coffee",
})
console.log(`Added memory with ID: ${addResult.memory.id}`)
```
</CodeGroup>
### Fetch Memory
Retrieve specific memory by ID:
<CodeGroup>
```python Python
# Fetch specific memory
result = await tools.fetch_memory(
memory_id="memory-id-here"
)
print(f"Memory content: {result.memory.content}")
```
```typescript JavaScript
// Fetch specific memory
const fetchResult = await tools.fetchMemory({
memoryId: "memory-id-here"
})
console.log(`Memory content: ${fetchResult.memory.content}`)
```
</CodeGroup>
## Individual Tools
Use tools separately for more granular control:
<CodeGroup>
```python Python Individual Tools
from supermemory_openai import (
create_search_memories_tool,
create_add_memory_tool,
create_fetch_memory_tool
)
search_tool = create_search_memories_tool("your-api-key")
add_tool = create_add_memory_tool("your-api-key")
fetch_tool = create_fetch_memory_tool("your-api-key")
# Use individual tools in OpenAI function calling
tools_list = [search_tool, add_tool, fetch_tool]
```
```typescript JavaScript Individual Tools
import {
createSearchMemoriesTool,
createAddMemoryTool,
createFetchMemoryTool
} from "@supermemory/tools/openai"
const searchTool = createSearchMemoriesTool(process.env.SUPERMEMORY_API_KEY!)
const addTool = createAddMemoryTool(process.env.SUPERMEMORY_API_KEY!)
const fetchTool = createFetchMemoryTool(process.env.SUPERMEMORY_API_KEY!)
// Use individual tools
const toolDefinitions = [searchTool, addTool, fetchTool]
```
</CodeGroup>
## Complete Chat Example
Here's a complete example showing a multi-turn conversation with memory:
<CodeGroup>
```python Complete Python Example
import asyncio
import openai
from supermemory_openai import SupermemoryTools, execute_memory_tool_calls
async def chat_with_memory():
client = openai.AsyncOpenAI()
tools = SupermemoryTools(
api_key="your-supermemory-api-key",
config={"project_id": "chat-example"}
)
messages = [
{
"role": "system",
"content": """You are a helpful assistant with memory capabilities.
When users share personal information, remember it using addMemory.
When they ask questions, search your memories to provide personalized responses."""
}
]
while True:
user_input = input("You: ")
if user_input.lower() == 'quit':
break
messages.append({"role": "user", "content": user_input})
# Get AI response with tools
response = await client.chat.completions.create(
model="gpt-5",
messages=messages,
tools=tools.get_tool_definitions()
)
# Handle tool calls
if response.choices[0].message.tool_calls:
messages.append(response.choices[0].message)
tool_results = await execute_memory_tool_calls(
api_key="your-supermemory-api-key",
tool_calls=response.choices[0].message.tool_calls,
config={"project_id": "chat-example"}
)
messages.extend(tool_results)
# Get final response after tool execution
final_response = await client.chat.completions.create(
model="gpt-5",
messages=messages
)
assistant_message = final_response.choices[0].message.content
else:
assistant_message = response.choices[0].message.content
messages.append({"role": "assistant", "content": assistant_message})
print(f"Assistant: {assistant_message}")
# Run the chat
asyncio.run(chat_with_memory())
```
```typescript Complete JavaScript Example
import OpenAI from "openai"
import { getToolDefinitions, createToolCallExecutor } from "@supermemory/tools/openai"
import readline from 'readline'
const client = new OpenAI()
const executeToolCall = createToolCallExecutor(process.env.SUPERMEMORY_API_KEY!, {
projectId: "chat-example",
})
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
async function chatWithMemory() {
const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{
role: "system",
content: `You are a helpful assistant with memory capabilities.
When users share personal information, remember it using addMemory.
When they ask questions, search your memories to provide personalized responses.`
}
]
const askQuestion = () => {
rl.question("You: ", async (userInput) => {
if (userInput.toLowerCase() === 'quit') {
rl.close()
return
}
messages.push({ role: "user", content: userInput })
// Get AI response with tools
const response = await client.chat.completions.create({
model: "gpt-5",
messages,
tools: getToolDefinitions(),
})
const choice = response.choices[0]
if (choice?.message.tool_calls) {
messages.push(choice.message)
// Execute tool calls
for (const toolCall of choice.message.tool_calls) {
const result = await executeToolCall(toolCall)
messages.push({
role: "tool",
tool_call_id: toolCall.id,
content: JSON.stringify(result),
})
}
// Get final response after tool execution
const finalResponse = await client.chat.completions.create({
model: "gpt-5",
messages,
})
const assistantMessage = finalResponse.choices[0]?.message.content || "No response"
console.log(`Assistant: ${assistantMessage}`)
messages.push({ role: "assistant", content: assistantMessage })
} else {
const assistantMessage = choice?.message.content || "No response"
console.log(`Assistant: ${assistantMessage}`)
messages.push({ role: "assistant", content: assistantMessage })
}
askQuestion()
})
}
console.log("Chat with memory started. Type 'quit' to exit.")
askQuestion()
}
chatWithMemory()
```
</CodeGroup>
## Error Handling
Handle errors gracefully in your applications:
<CodeGroup>
```python Python Error Handling
from supermemory_openai import SupermemoryTools
import openai
async def safe_chat():
try:
client = openai.AsyncOpenAI()
tools = SupermemoryTools(api_key="your-api-key")
response = await client.chat.completions.create(
model="gpt-5",
messages=[{"role": "user", "content": "Hello"}],
tools=tools.get_tool_definitions()
)
except openai.APIError as e:
print(f"OpenAI API error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
```
```typescript JavaScript Error Handling
import OpenAI from "openai"
import { getToolDefinitions } from "@supermemory/tools/openai"
async function safeChat() {
try {
const client = new OpenAI()
const response = await client.chat.completions.create({
model: "gpt-5",
messages: [{ role: "user", content: "Hello" }],
tools: getToolDefinitions(),
})
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error("OpenAI API error:", error.message)
} else {
console.error("Unexpected error:", error)
}
}
}
```
</CodeGroup>
## API Reference
### Python SDK
#### `SupermemoryTools`
**Constructor**
```python
SupermemoryTools(
api_key: str,
config: Optional[SupermemoryToolsConfig] = None
)
```
**Methods**
- `get_tool_definitions()` - Get OpenAI function definitions
- `search_memories(information_to_get, limit, include_full_docs)` - Search user memories
- `add_memory(memory)` - Add new memory
- `fetch_memory(memory_id)` - Fetch specific memory by ID
- `execute_tool_call(tool_call)` - Execute individual tool call
#### `execute_memory_tool_calls`
```python
execute_memory_tool_calls(
api_key: str,
tool_calls: List[ToolCall],
config: Optional[SupermemoryToolsConfig] = None
) -> List[dict]
```
### JavaScript SDK
#### `supermemoryTools`
```typescript
supermemoryTools(
apiKey: string,
config?: { projectId?: string; baseUrl?: string }
)
```
#### `createToolCallExecutor`
```typescript
createToolCallExecutor(
apiKey: string,
config?: { projectId?: string; baseUrl?: string }
) -> (toolCall: OpenAI.Chat.ChatCompletionMessageToolCall) => Promise<any>
```
## Environment Variables
Set these environment variables:
```bash
SUPERMEMORY_API_KEY=your_supermemory_key
OPENAI_API_KEY=your_openai_key
SUPERMEMORY_BASE_URL=https://custom-endpoint.com # optional
```
## Development
### Python Setup
```bash
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
# Setup project
git clone <repository-url>
cd packages/openai-sdk-python
uv sync --dev
# Run tests
uv run pytest
# Type checking
uv run mypy src/supermemory_openai
# Formatting
uv run black src/ tests/
uv run isort src/ tests/
```
### JavaScript Setup
```bash
# Install dependencies
npm install
# Run tests
npm test
# Type checking
npm run type-check
# Linting
npm run lint
```
## Next Steps
<CardGroup cols={2}>
<Card title="AI SDK Integration" icon="triangle" href="/integrations/ai-sdk">
Use with Vercel AI SDK for streamlined development
</Card>
<Card title="Memory API" icon="database" href="/memory-api/overview">
Direct API access for advanced memory management
</Card>
</CardGroup>

View file

@ -1,24 +0,0 @@
---
title: "Overview"
---
<Columns cols={2}>
<Card title="Native Python and Typescript/JS SDKs" icon="code" href="/integrations/supermemory-sdk">
<br/>
```pip install supermemory```
```npm install supermemory```
</Card>
<Card title="AI SDK plugin" icon="triangle" href="/integrations/ai-sdk">
Easy to use with Vercel AI SDK
</Card>
<Card title="OpenAI SDK plugins" icon="sparkles" href="/integrations/openai">
Use supermemory with the python and javascript OpenAI SDKs
</Card>
<Card title="Request more plugins" icon="life-buoy" href="mailto:support@supermemory.ai">
We will add support for your favorite SDKs asap.
</Card>
</Columns>

View file

@ -1,256 +0,0 @@
---
title: "Track Processing Status"
description: "Monitor document processing status in real-time"
icon: "activity"
---
Track your documents through the processing pipeline to provide better user experiences and handle edge cases.
## Processing Pipeline
![Process of converting documents to memories](/images/pipeline.png)
Each stage serves a specific purpose:
- **Queued**: Document is waiting in the processing queue
- **Extracting**: Content is being extracted (OCR for images, transcription for videos)
- **Chunking**: Content is broken into optimal, searchable pieces
- **Embedding**: Each chunk is converted to vector representations
- **Indexing**: Vectors are added to the search index
- **Done**: Document is fully processed and searchable
<Note>
Processing time varies by content type. Plain text processes in seconds, while a 10-minute video might take 2-3 minutes.
</Note>
## Processing Documents
Monitor all documents currently being processed across your account.
`GET /v3/documents/processing`
<CodeGroup>
```typescript Typescript
// Direct API call (not in SDK)
const response = await fetch('https://api.supermemory.ai/v3/documents/processing', {
headers: {
'Authorization': `Bearer ${SUPERMEMORY_API_KEY}`
}
});
const processing = await response.json();
console.log(`${processing.documents.length} documents processing`);
```
```python Python
# Direct API call (not in SDK)
import requests
response = requests.get(
'https://api.supermemory.ai/v3/documents/processing',
headers={'Authorization': f'Bearer {SUPERMEMORY_API_KEY}'}
)
processing = response.json()
print(f"{len(processing['documents'])} documents processing")
```
```bash cURL
curl -X GET "https://api.supermemory.ai/v3/documents/processing" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY"
```
</CodeGroup>
### Response Format
```json
{
"documents": [
{
"id": "doc_abc123",
"status": "extracting",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:15Z",
"container_tags": ["research"],
"metadata": {
"source": "upload",
"filename": "report.pdf"
}
},
{
"id": "doc_def456",
"status": "chunking",
"created_at": "2024-01-15T10:29:00Z",
"updated_at": "2024-01-15T10:30:00Z",
"container_tags": ["articles"],
"metadata": {
"source": "url",
"url": "https://example.com/article"
}
}
],
"total": 2
}
```
## Individual Documents
Track specific document processing status.
`GET /v3/documents/{id}`
<CodeGroup>
```typescript Typescript
const memory = await client.documents.get("doc_abc123");
console.log(`Status: ${memory.status}`);
// Poll for completion
while (memory.status !== 'done') {
await new Promise(r => setTimeout(r, 2000));
memory = await client.documents.get("doc_abc123");
console.log(`Status: ${memory.status}`);
}
```
```python Python
memory = client.documents.get("doc_abc123")
print(f"Status: {memory['status']}")
# Poll for completion
import time
while memory['status'] != 'done':
time.sleep(2)
memory = client.documents.get("doc_abc123")
print(f"Status: {memory['status']}")
```
```bash cURL
curl -X GET "https://api.supermemory.ai/v3/documents/doc_abc123" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY"
```
</CodeGroup>
### Response Format
```json
{
"id": "doc_abc123",
"status": "done",
"content": "The original content...",
"container_tags": ["research"],
"metadata": {
"source": "upload",
"filename": "report.pdf"
},
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:31:00Z"
}
```
For more comprehensive information on the get documents by ID endpoint, refer to the API Reference tab.
## Status Values
| Status | Description | Typical Duration |
|--------|-------------|------------------|
| `queued` | Waiting to be processed | < 5 seconds |
| `extracting` | Extracting content from source | 5-30 seconds |
| `chunking` | Breaking into searchable pieces | 5-15 seconds |
| `embedding` | Creating vector representations | 10-30 seconds |
| `indexing` | Adding to search index | 5-10 seconds |
| `done` | Fully processed and searchable | - |
| `failed` | Processing failed | - |
## Polling Best Practices
When polling for status updates:
```typescript
async function waitForProcessing(documentId: string, maxWaitMs = 300000) {
const startTime = Date.now();
const pollInterval = 2000; // 2 seconds
while (Date.now() - startTime < maxWaitMs) {
const doc = await client.documents.get(documentId);
if (doc.status === 'done') {
return doc;
}
if (doc.status === 'failed') {
throw new Error(`Processing failed for ${documentId}`);
}
await new Promise(r => setTimeout(r, pollInterval));
}
throw new Error(`Timeout waiting for ${documentId}`);
}
```
## Batch Processing
For multiple documents, track them efficiently:
```typescript
async function trackBatch(documentIds: string[]) {
const statuses = new Map();
// Initial check
for (const id of documentIds) {
const doc = await client.documents.get(id);
statuses.set(id, doc.status);
}
// Poll until all done
while ([...statuses.values()].some(s => s !== 'done' && s !== 'failed')) {
await new Promise(r => setTimeout(r, 5000)); // 5 second interval for batch
for (const id of documentIds) {
if (statuses.get(id) !== 'done' && statuses.get(id) !== 'failed') {
const doc = await client.documents.get(id);
statuses.set(id, doc.status);
}
}
// Log progress
const done = [...statuses.values()].filter(s => s === 'done').length;
console.log(`Progress: ${done}/${documentIds.length} complete`);
}
return statuses;
}
```
## Error Handling
Handle processing failures gracefully:
```typescript
async function addWithRetry(content: string, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const { id } = await client.add({ content });
try {
const result = await waitForProcessing(id);
return result;
} catch (error) {
console.error(`Attempt ${attempt} failed:`, error);
if (attempt === maxRetries) {
throw error;
}
// Exponential backoff
await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));
}
}
}
```

View file

@ -1,334 +0,0 @@
---
title: 'API Reference'
description: 'Complete reference for Memory Graph props and types'
---
## Component Props
### MemoryGraph
The main graph component.
#### Core Props
<ParamField path="documents" type="DocumentWithMemories[]" required>
Array of documents to display in the graph. Each document must include its memory entries.
</ParamField>
<ParamField path="isLoading" type="boolean" default="false">
Shows a loading indicator when true.
</ParamField>
<ParamField path="error" type="Error | null" default="null">
Error object to display. Shows an error message overlay when set.
</ParamField>
<ParamField path="variant" type='"console" | "consumer"' default='"console"'>
Visual variant:
- `console`: Full-featured dashboard view (0.8x zoom, space selector visible)
- `consumer`: Embedded widget view (0.5x zoom, space selector hidden)
</ParamField>
<ParamField path="children" type="ReactNode">
Content to render when no documents exist. Useful for empty states.
</ParamField>
#### Pagination Props
<ParamField path="isLoadingMore" type="boolean" default="false">
Shows a subtle indicator when loading additional documents.
</ParamField>
<ParamField path="hasMore" type="boolean" default="false">
Whether more documents are available to load.
</ParamField>
<ParamField path="totalLoaded" type="number">
Total number of documents currently loaded. Shown in loading indicator.
</ParamField>
<ParamField path="loadMoreDocuments" type="() => Promise<void>">
Callback to load more documents. Called automatically when viewport shows most documents.
</ParamField>
<ParamField path="autoLoadOnViewport" type="boolean" default="true">
Automatically load more documents when 80% are visible in viewport.
</ParamField>
#### Display Props
<ParamField path="showSpacesSelector" type="boolean">
Show or hide the space filter dropdown. Defaults to `true` for console variant, `false` for consumer.
</ParamField>
<ParamField path="highlightDocumentIds" type="string[]" default="[]">
Array of document IDs to highlight with a pulsing outline. Accepts both `customId` and internal `id`.
</ParamField>
<ParamField path="highlightsVisible" type="boolean" default="true">
Controls whether highlights are shown. Useful for toggling highlights without changing the array.
</ParamField>
<ParamField path="occludedRightPx" type="number" default="0">
Pixels occluded on the right side (e.g., by a sidebar). Graph auto-fits accounting for this space.
</ParamField>
<ParamField path="legendId" type="string">
Custom ID for the legend component. Useful for testing or styling.
</ParamField>
#### Controlled State Props
<ParamField path="selectedSpace" type="string">
Currently selected space. When provided, makes space selection controlled. Use `"all"` for all spaces.
</ParamField>
<ParamField path="onSpaceChange" type="(spaceId: string) => void">
Callback when space selection changes. Required when using `selectedSpace`.
</ParamField>
<ParamField path="memoryLimit" type="number">
Maximum memories to show per document when a specific space is selected. Only applies when `selectedSpace !== "all"`.
</ParamField>
<ParamField path="isExperimental" type="boolean" default="false">
Enable experimental features. Currently unused but reserved for future features.
</ParamField>
## Data Types
### DocumentWithMemories
```typescript
interface DocumentWithMemories {
id: string;
customId?: string | null;
contentHash: string | null;
orgId: string;
userId: string;
connectionId?: string | null;
title?: string | null;
content?: string | null;
summary?: string | null;
url?: string | null;
source?: string | null;
type?: string | null;
status: 'pending' | 'processing' | 'done' | 'failed';
metadata?: Record<string, string | number | boolean> | null;
processingMetadata?: Record<string, unknown> | null;
raw?: string | null;
tokenCount?: number | null;
wordCount?: number | null;
chunkCount?: number | null;
averageChunkSize?: number | null;
summaryEmbedding?: number[] | null;
summaryEmbeddingModel?: string | null;
createdAt: string | Date;
updatedAt: string | Date;
memoryEntries: MemoryEntry[];
}
```
### MemoryEntry
```typescript
interface MemoryEntry {
id: string;
customId?: string | null;
documentId: string;
content: string | null;
summary?: string | null;
title?: string | null;
url?: string | null;
type?: string | null;
metadata?: Record<string, string | number | boolean> | null;
embedding?: number[] | null;
embeddingModel?: string | null;
tokenCount?: number | null;
createdAt: string | Date;
updatedAt: string | Date;
// Fields from join relationship
sourceAddedAt?: Date | null;
sourceRelevanceScore?: number | null;
sourceMetadata?: Record<string, unknown> | null;
spaceContainerTag?: string | null;
// Version chain fields
updatesMemoryId?: string | null;
nextVersionId?: string | null;
relation?: 'updates' | 'extends' | 'derives' | null;
// Memory status fields
isForgotten?: boolean;
forgetAfter?: Date | string | null;
isLatest?: boolean;
// Space/container fields
spaceId?: string | null;
// Legacy fields (for backwards compatibility)
memory?: string | null;
memoryRelations?: Array<{
relationType: 'updates' | 'extends' | 'derives';
targetMemoryId: string;
}> | null;
parentMemoryId?: string | null;
}
```
### GraphNode
Internal type for rendered nodes:
```typescript
interface GraphNode {
id: string;
type: 'document' | 'memory';
x: number;
y: number;
data: DocumentWithMemories | MemoryEntry;
size: number;
color: string;
isHovered: boolean;
isDragging: boolean;
}
```
### GraphEdge
Internal type for connections:
```typescript
interface GraphEdge {
id: string;
source: string;
target: string;
similarity: number;
edgeType: 'doc-memory' | 'doc-doc' | 'version';
relationType?: 'updates' | 'extends' | 'derives';
color: string;
visualProps: {
opacity: number;
thickness: number;
glow: number;
pulseDuration: number;
};
}
```
## Exported Components
Besides `MemoryGraph`, the package exports individual components for advanced use cases:
### GraphCanvas
Low-level canvas renderer. Not recommended for direct use.
```typescript
import { GraphCanvas } from '@supermemory/memory-graph';
```
### Legend
Graph legend showing node types and counts.
```typescript
import { Legend } from '@supermemory/memory-graph';
```
### LoadingIndicator
Loading state indicator with progress counter.
```typescript
import { LoadingIndicator } from '@supermemory/memory-graph';
```
### NodeDetailPanel
Side panel showing node details when clicked.
```typescript
import { NodeDetailPanel } from '@supermemory/memory-graph';
```
### SpacesDropdown
Space filter dropdown.
```typescript
import { SpacesDropdown } from '@supermemory/memory-graph';
```
## Exported Hooks
### useGraphData
Processes documents into graph nodes and edges.
```typescript
import { useGraphData } from '@supermemory/memory-graph';
const { nodes, edges } = useGraphData(
data,
selectedSpace,
nodePositions,
draggingNodeId,
memoryLimit
);
```
### useGraphInteractions
Handles pan, zoom, and node interactions.
```typescript
import { useGraphInteractions } from '@supermemory/memory-graph';
const {
panX,
panY,
zoom,
selectedNode,
handlePanStart,
handleWheel,
// ... more interaction handlers
} = useGraphInteractions('console');
```
## Constants
### colors
Color palette used throughout the graph:
```typescript
import { colors } from '@supermemory/memory-graph';
colors.document.primary; // Document fill color
colors.memory.primary; // Memory fill color
colors.connection.strong; // Strong edge color
```
### GRAPH_SETTINGS
Initial zoom and pan settings for variants:
```typescript
import { GRAPH_SETTINGS } from '@supermemory/memory-graph';
GRAPH_SETTINGS.console.initialZoom; // 0.8
GRAPH_SETTINGS.consumer.initialZoom; // 0.5
```
### LAYOUT_CONSTANTS
Spatial layout configuration:
```typescript
import { LAYOUT_CONSTANTS } from '@supermemory/memory-graph';
LAYOUT_CONSTANTS.clusterRadius; // Memory orbit radius
LAYOUT_CONSTANTS.documentSpacing; // Distance between documents
```

View file

@ -1,407 +0,0 @@
---
title: 'Examples'
description: 'Common use cases and implementation patterns'
---
## With Pagination
Load documents in chunks for better performance with large datasets.
```tsx
'use client';
import { MemoryGraph } from '@supermemory/memory-graph';
import type { DocumentWithMemories } from '@supermemory/memory-graph';
import { useCallback, useEffect, useState } from 'react';
export default function PaginatedGraph() {
const [documents, setDocuments] = useState<DocumentWithMemories[]>([]);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [isLoading, setIsLoading] = useState(true);
const [isLoadingMore, setIsLoadingMore] = useState(false);
// Initial load
useEffect(() => {
fetchPage(1, false);
}, []);
const fetchPage = async (pageNum: number, append: boolean) => {
if (pageNum === 1) {
setIsLoading(true);
} else {
setIsLoadingMore(true);
}
const res = await fetch(`/api/graph?page=${pageNum}&limit=100`);
const data = await res.json();
if (append) {
setDocuments(prev => [...prev, ...data.documents]);
} else {
setDocuments(data.documents);
}
setHasMore(data.pagination.currentPage < data.pagination.totalPages);
setIsLoading(false);
setIsLoadingMore(false);
};
const loadMore = useCallback(async () => {
if (!isLoadingMore && hasMore) {
const nextPage = page + 1;
setPage(nextPage);
await fetchPage(nextPage, true);
}
}, [page, hasMore, isLoadingMore]);
return (
<div style={{ height: '100vh' }}>
<MemoryGraph
documents={documents}
isLoading={isLoading}
isLoadingMore={isLoadingMore}
hasMore={hasMore}
totalLoaded={documents.length}
loadMoreDocuments={loadMore}
/>
</div>
);
}
```
## Highlighting Search Results
```tsx
'use client';
import { MemoryGraph } from '@supermemory/memory-graph';
import { useState } from 'react';
export default function SearchableGraph() {
const [documents, setDocuments] = useState([]);
const [searchResults, setSearchResults] = useState<string[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const handleSearch = async (query: string) => {
setSearchQuery(query);
if (!query) {
setSearchResults([]);
return;
}
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
const data = await res.json();
// Extract document IDs from search results
const docIds = data.results.map(r => r.documentId);
setSearchResults(docIds);
};
return (
<div style={{ height: '100vh' }}>
<div style={{ position: 'absolute', top: 16, left: 16, zIndex: 10 }}>
<input
type="text"
placeholder="Search memories..."
value={searchQuery}
onChange={(e) => handleSearch(e.target.value)}
style={{
padding: '8px 12px',
borderRadius: 8,
border: '1px solid #333',
background: '#1a1a1a',
color: 'white',
}}
/>
</div>
<MemoryGraph
documents={documents}
highlightDocumentIds={searchResults}
highlightsVisible={searchResults.length > 0}
/>
</div>
);
}
```
## Controlled Space Selection
Control space filtering from outside the component.
```tsx
'use client';
import { MemoryGraph } from '@supermemory/memory-graph';
import { useState } from 'react';
export default function ControlledSpaceGraph() {
const [documents, setDocuments] = useState([]);
const [selectedSpace, setSelectedSpace] = useState('all');
// Extract available spaces from documents
const spaces = Array.from(
new Set(
documents.flatMap(doc =>
doc.memoryEntries.map(m => m.spaceId || 'default')
)
)
);
return (
<div style={{ height: '100vh' }}>
<div style={{
position: 'absolute',
top: 16,
right: 16,
zIndex: 10,
background: '#1a1a1a',
padding: 16,
borderRadius: 8,
border: '1px solid #333',
}}>
<h3 style={{ margin: '0 0 12px 0', color: 'white' }}>Filters</h3>
<select
value={selectedSpace}
onChange={(e) => setSelectedSpace(e.target.value)}
style={{
padding: '8px 12px',
borderRadius: 6,
background: '#2a2a2a',
color: 'white',
border: '1px solid #444',
width: '100%',
}}
>
<option value="all">All Spaces</option>
{spaces.map(space => (
<option key={space} value={space}>{space}</option>
))}
</select>
<button
onClick={() => setSelectedSpace('all')}
style={{
marginTop: 12,
padding: '6px 12px',
borderRadius: 6,
background: '#333',
color: 'white',
border: 'none',
width: '100%',
cursor: 'pointer',
}}
>
Reset
</button>
</div>
<MemoryGraph
documents={documents}
selectedSpace={selectedSpace}
onSpaceChange={setSelectedSpace}
showSpacesSelector={false}
/>
</div>
);
}
```
## Embedded Widget
Use the consumer variant for embedded views with custom styling.
```tsx
'use client';
import { MemoryGraph } from '@supermemory/memory-graph';
export default function EmbeddedGraph({ documents }) {
return (
<div
style={{
height: 400,
borderRadius: 12,
overflow: 'hidden',
border: '1px solid #2a2a2a',
}}
>
<MemoryGraph
documents={documents}
variant="consumer"
showSpacesSelector={false}
>
<div style={{
textAlign: 'center',
padding: '2rem',
color: '#888',
}}>
<p>No memories to display</p>
</div>
</MemoryGraph>
</div>
);
}
```
## With Loading States
```tsx
'use client';
import { MemoryGraph } from '@supermemory/memory-graph';
import { useEffect, useState } from 'react';
export default function LoadingGraph() {
const [documents, setDocuments] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
fetch('/api/graph')
.then(res => {
if (!res.ok) throw new Error('Failed to load graph');
return res.json();
})
.then(data => {
setDocuments(data.documents);
setIsLoading(false);
})
.catch(err => {
setError(err);
setIsLoading(false);
});
}, []);
return (
<div style={{ height: '100vh' }}>
<MemoryGraph
documents={documents}
isLoading={isLoading}
error={error}
>
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
color: '#888',
}}>
<div>
<h2>Welcome to your Memory Graph</h2>
<p>Add some content to get started</p>
<button
style={{
marginTop: 16,
padding: '8px 16px',
borderRadius: 6,
background: '#2563eb',
color: 'white',
border: 'none',
cursor: 'pointer',
}}
onClick={() => window.location.href = '/add-memory'}
>
Add First Memory
</button>
</div>
</div>
</MemoryGraph>
</div>
);
}
```
## React Server Component
```tsx
// Next.js App Router with Server Component
import { MemoryGraphClient } from './memory-graph-client';
async function getGraphData() {
const res = await fetch('https://api.supermemory.ai/v3/documents/documents', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
page: 1,
limit: 500,
sort: 'createdAt',
order: 'desc',
}),
cache: 'no-store', // or use revalidation
});
return res.json();
}
export default async function GraphPage() {
const data = await getGraphData();
return <MemoryGraphClient initialDocuments={data.documents} />;
}
```
```tsx
// memory-graph-client.tsx
'use client';
import { MemoryGraph } from '@supermemory/memory-graph';
import type { DocumentWithMemories } from '@supermemory/memory-graph';
interface Props {
initialDocuments: DocumentWithMemories[];
}
export function MemoryGraphClient({ initialDocuments }: Props) {
return (
<div style={{ height: '100vh' }}>
<MemoryGraph
documents={initialDocuments}
isLoading={false}
/>
</div>
);
}
```
## Mobile-Responsive Layout
```tsx
'use client';
import { MemoryGraph } from '@supermemory/memory-graph';
import { useState, useEffect } from 'react';
export default function ResponsiveGraph({ documents }) {
const [isMobile, setIsMobile] = useState(false);
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < 768);
};
checkMobile();
window.addEventListener('resize', checkMobile);
return () => window.removeEventListener('resize', checkMobile);
}, []);
return (
<div style={{
height: isMobile ? '60vh' : '100vh',
width: '100%',
}}>
<MemoryGraph
documents={documents}
variant={isMobile ? 'consumer' : 'console'}
showSpacesSelector={!isMobile}
/>
</div>
);
}
```

View file

@ -1,28 +0,0 @@
---
title: 'Installation'
description: 'Install and set up the Memory Graph component'
---
## Installation
Install the package using your preferred package manager:
```bash npm
npm install @supermemory/memory-graph
```
## Requirements
- **React**: 18.0.0 or higher
- **react-dom**: 18.0.0 or higher
## Next Steps
<CardGroup cols={2}>
<Card title="Quick Start" icon="rocket" href="/integrations/memory-graph">
Get the graph running with real data
</Card>
<Card title="API Reference" icon="code" href="/integrations/memory-graph">
Explore all available props and types
</Card>
</CardGroup>

View file

@ -1,38 +0,0 @@
---
title: 'Overview'
description: 'Interactive visualization for documents, memories and connections'
---
## What is Memory Graph?
Memory Graph is a React component that visualizes your Supermemory documents and memories as an interactive network. Documents appear as rectangular nodes, memories as hexagonal nodes, and connections between them show relationships and similarity.
The graph renders using Canvas 2D, providing smooth interactions with hundreds of nodes through pan, zoom, and drag operations.
## When to Use It
Use Memory Graph when you need to:
- **Visualize knowledge graphs** - Show how documents and memories connect
- **Navigate memory spaces** - Filter and browse by workspace or tag
- **Create memory browsers** - Give users a visual overview of their stored content
## Performance
The graph handles hundreds of nodes efficiently through:
- Canvas-based rendering (not DOM elements)
- Viewport culling (only draws visible nodes)
- Level-of-detail optimization (simplifies rendering when zoomed out)
- Change-based rendering (only redraws when state changes)
- Throttled viewport calculations
For very large datasets (1000+ documents), use pagination to load data in chunks.
## Browser Support
Works in all modern browsers that support:
- Canvas 2D API
- ES2020 JavaScript
- CSS custom properties
Tested on Chrome, Firefox, Safari, and Edge (latest versions).

View file

@ -1,207 +0,0 @@
---
title: 'Quick Start'
description: 'Get Memory Graph running in 2 minutes'
---
## Basic Setup
Here's a minimal example to get the graph running:
```tsx
'use client'; // For Next.js App Router
import { MemoryGraph } from '@supermemory/memory-graph';
import type { DocumentWithMemories } from '@supermemory/memory-graph';
import { useEffect, useState } from 'react';
export default function GraphPage() {
const [documents, setDocuments] = useState<DocumentWithMemories[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
fetch('/api/graph')
.then(res => res.json())
.then(data => {
setDocuments(data.documents);
setIsLoading(false);
})
.catch(err => {
setError(err);
setIsLoading(false);
});
}, []);
return (
<div style={{ height: '100vh' }}>
<MemoryGraph
documents={documents}
isLoading={isLoading}
error={error}
variant="console"
/>
</div>
);
}
```
## Backend API Route
Create an API route to fetch documents from Supermemory:
<CodeGroup>
```typescript Next.js App Router
// app/api/graph/route.ts
import { NextResponse } from 'next/server';
export async function GET() {
const response = await fetch('https://api.supermemory.ai/v3/documents/documents', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
},
body: JSON.stringify({
page: 1,
limit: 500,
sort: 'createdAt',
order: 'desc',
}),
});
const data = await response.json();
return NextResponse.json(data);
}
```
```typescript Next.js Pages Router
// pages/api/graph.ts
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const response = await fetch('https://api.supermemory.ai/v3/documents/documents', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
},
body: JSON.stringify({
page: 1,
limit: 500,
sort: 'createdAt',
order: 'desc',
}),
});
const data = await response.json();
res.json(data);
}
```
```javascript Express
// routes/graph.js
app.get('/api/graph', async (req, res) => {
const response = await fetch('https://api.supermemory.ai/v3/documents/documents', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
},
body: JSON.stringify({
page: 1,
limit: 500,
sort: 'createdAt',
order: 'desc',
}),
});
const data = await response.json();
res.json(data);
});
```
</CodeGroup>
<Warning>
Never expose your Supermemory API key to the client. Always fetch data through your backend.
</Warning>
## Environment Variables
Add your API key to `.env.local`:
```bash
SUPERMEMORY_API_KEY=your_api_key_here
```
Get your API key from the [Supermemory dashboard](https://console.supermemory.ai).
## Common Customizations
### Embedded Mode
For a widget-style view, use the consumer variant:
```tsx
<MemoryGraph
documents={documents}
isLoading={isLoading}
variant="consumer"
/>
```
### CSS Import
The component includes bundled styles. You don't need to import CSS separately. Styles are automatically injected when the component mounts.
If you want explicit control, you can import the stylesheet:
```typescript
import '@supermemory/memory-graph/styles.css';
```
<Note>
The automatic CSS injection works for most setups. Only use the explicit import if you need custom control over style loading order.
</Note>
### Custom Empty State
Show custom content when no documents exist:
```tsx
<MemoryGraph
documents={documents}
isLoading={isLoading}
>
<div style={{ textAlign: 'center', padding: '2rem' }}>
<h2>No memories yet</h2>
<p>Add content to see your knowledge graph</p>
</div>
</MemoryGraph>
```
### Hide Space Selector
```tsx
<MemoryGraph
documents={documents}
isLoading={isLoading}
showSpacesSelector={false}
/>
```
## Next Steps
<CardGroup cols={2}>
<Card title="Examples" icon="code" href="/integrations/memory-graph">
See more usage examples
</Card>
<Card title="API Reference" icon="book" href="/integrations/memory-graph">
Full API documentation
</Card>
</CardGroup>