aboutsummaryrefslogtreecommitdiff
path: root/apps/docs
diff options
context:
space:
mode:
authorDhravya Shah <[email protected]>2025-09-28 16:42:06 -0700
committerDhravya Shah <[email protected]>2025-09-28 16:42:06 -0700
commit2093b316d9ecb9cfa9c550f436caee08e12f5d11 (patch)
tree07b87fbd48b0b38ef26b9d5f839ad8cd61d82331 /apps/docs
parentMerge branch 'main' of https://github.com/supermemoryai/supermemory (diff)
downloadsupermemory-2093b316d9ecb9cfa9c550f436caee08e12f5d11.tar.xz
supermemory-2093b316d9ecb9cfa9c550f436caee08e12f5d11.zip
migrate docs to public
Diffstat (limited to 'apps/docs')
-rw-r--r--apps/docs/.cursor/rules/docs.mdc84
-rw-r--r--apps/docs/.gitignore34
-rw-r--r--apps/docs/README.md1
-rw-r--r--apps/docs/add-memories/examples/basic.mdx278
-rw-r--r--apps/docs/add-memories/examples/file-upload.mdx195
-rw-r--r--apps/docs/add-memories/overview.mdx210
-rw-r--r--apps/docs/add-memories/parameters.mdx156
-rw-r--r--apps/docs/ai-sdk/examples.mdx426
-rw-r--r--apps/docs/ai-sdk/infinite-chat.mdx216
-rw-r--r--apps/docs/ai-sdk/memory-tools.mdx147
-rw-r--r--apps/docs/ai-sdk/npm.mdx5
-rw-r--r--apps/docs/ai-sdk/overview.mdx80
-rw-r--r--apps/docs/analytics.mdx300
-rw-r--r--apps/docs/changelog/developer-platform.mdx74
-rw-r--r--apps/docs/changelog/overview.mdx34
-rw-r--r--apps/docs/connectors/google-drive.mdx435
-rw-r--r--apps/docs/connectors/notion.mdx429
-rw-r--r--apps/docs/connectors/onedrive.mdx390
-rw-r--r--apps/docs/connectors/overview.mdx306
-rw-r--r--apps/docs/connectors/troubleshooting.mdx190
-rw-r--r--apps/docs/cookbook/ai-sdk-integration.mdx424
-rw-r--r--apps/docs/cookbook/chat-with-gdrive.mdx4
-rw-r--r--apps/docs/cookbook/customer-support.mdx1047
-rw-r--r--apps/docs/cookbook/document-qa.mdx883
-rw-r--r--apps/docs/cookbook/inf-chat-blog.mdx4
-rw-r--r--apps/docs/cookbook/overview.mdx64
-rw-r--r--apps/docs/cookbook/perplexity-supermemory.mdx4
-rw-r--r--apps/docs/cookbook/personal-assistant.mdx770
-rw-r--r--apps/docs/deployment/self-hosting.mdx243
-rw-r--r--apps/docs/docs.json260
-rw-r--r--apps/docs/favicon.pngbin0 -> 616 bytes
-rw-r--r--apps/docs/how-it-works.mdx152
-rw-r--r--apps/docs/images/Screenshot 2025-06-19 at 3.50.20 PM.pngbin0 -> 231007 bytes
-rw-r--r--apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (2).pngbin0 -> 421664 bytes
-rw-r--r--apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (3).pngbin0 -> 337361 bytes
-rw-r--r--apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM.pngbin0 -> 875873 bytes
-rw-r--r--apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (2).pngbin0 -> 421664 bytes
-rw-r--r--apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (3).pngbin0 -> 337361 bytes
-rw-r--r--apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM.pngbin0 -> 931134 bytes
-rw-r--r--apps/docs/images/connectors-flow.pngbin0 -> 244657 bytes
-rw-r--r--apps/docs/images/create-api.pngbin0 -> 167887 bytes
-rw-r--r--apps/docs/images/dev-platform-api-keys.pngbin0 -> 243273 bytes
-rw-r--r--apps/docs/images/dev-platform-copy-key.pngbin0 -> 310420 bytes
-rw-r--r--apps/docs/images/dev-platform-create-key.pngbin0 -> 266661 bytes
-rw-r--r--apps/docs/images/dev-platform-login.pngbin0 -> 582506 bytes
-rw-r--r--apps/docs/images/doc-to-memory-process.pngbin0 -> 269601 bytes
-rw-r--r--apps/docs/images/graph-view.pngbin0 -> 485021 bytes
-rw-r--r--apps/docs/images/hero-dark.svg32
-rw-r--r--apps/docs/images/hero-light.svg32
-rw-r--r--apps/docs/images/infinite-context.pngbin0 -> 166927 bytes
-rw-r--r--apps/docs/images/memories-inferred.pngbin0 -> 3110130 bytes
-rw-r--r--apps/docs/images/opts/Connectors.pngbin0 -> 4164691 bytes
-rw-r--r--apps/docs/images/opts/Memory_API.pngbin0 -> 4238814 bytes
-rw-r--r--apps/docs/images/opts/Model_Enhancer.pngbin0 -> 4171436 bytes
-rw-r--r--apps/docs/images/opts/Supermemory_MCP.pngbin0 -> 4332671 bytes
-rw-r--r--apps/docs/images/overview-image.pngbin0 -> 5331146 bytes
-rw-r--r--apps/docs/images/pipeline.pngbin0 -> 6616552 bytes
-rw-r--r--apps/docs/images/process.pngbin0 -> 6530812 bytes
-rw-r--r--apps/docs/images/processing.pngbin0 -> 185976 bytes
-rw-r--r--apps/docs/images/query-rewriting.pngbin0 -> 108119 bytes
-rw-r--r--apps/docs/images/rerank.pngbin0 -> 28925 bytes
-rw-r--r--apps/docs/images/sm-header.pngbin0 -> 418889 bytes
-rw-r--r--apps/docs/images/transparent-proxy.pngbin0 -> 96775 bytes
-rw-r--r--apps/docs/intro.mdx63
-rw-r--r--apps/docs/introduction.mdx66
-rw-r--r--apps/docs/list-memories/examples/basic.mdx87
-rw-r--r--apps/docs/list-memories/examples/filtering.mdx508
-rw-r--r--apps/docs/list-memories/examples/monitoring.mdx118
-rw-r--r--apps/docs/list-memories/examples/pagination.mdx110
-rw-r--r--apps/docs/list-memories/overview.mdx153
-rw-r--r--apps/docs/logo/dark.svg1
-rw-r--r--apps/docs/logo/light.svg1
-rw-r--r--apps/docs/memory-api/connectors/advanced/bring-your-own-key.mdx138
-rw-r--r--apps/docs/memory-api/connectors/creating-connection.mdx85
-rw-r--r--apps/docs/memory-api/connectors/google-drive.mdx27
-rw-r--r--apps/docs/memory-api/connectors/overview.mdx26
-rw-r--r--apps/docs/memory-api/creation/adding-memories.mdx376
-rw-r--r--apps/docs/memory-api/creation/status.mdx14
-rw-r--r--apps/docs/memory-api/features/auto-multi-modal.mdx181
-rw-r--r--apps/docs/memory-api/features/content-cleaner.mdx86
-rw-r--r--apps/docs/memory-api/features/filtering.mdx297
-rw-r--r--apps/docs/memory-api/features/query-rewriting.mdx50
-rw-r--r--apps/docs/memory-api/features/reranking.mdx44
-rw-r--r--apps/docs/memory-api/ingesting.mdx861
-rw-r--r--apps/docs/memory-api/introduction.mdx43
-rw-r--r--apps/docs/memory-api/overview.mdx162
-rw-r--r--apps/docs/memory-api/sdks/native.mdx68
-rw-r--r--apps/docs/memory-api/sdks/openai-plugins.mdx584
-rw-r--r--apps/docs/memory-api/sdks/overview.mdx24
-rw-r--r--apps/docs/memory-api/sdks/python.mdx349
-rw-r--r--apps/docs/memory-api/sdks/supermemory-npm.mdx5
-rw-r--r--apps/docs/memory-api/sdks/supermemory-pypi.mdx5
-rw-r--r--apps/docs/memory-api/sdks/typescript.mdx391
-rw-r--r--apps/docs/memory-api/searching/searching-memories.mdx181
-rw-r--r--apps/docs/memory-api/track-progress.mdx274
-rw-r--r--apps/docs/memory-router/overview.mdx158
-rw-r--r--apps/docs/memory-router/usage.mdx214
-rw-r--r--apps/docs/memory-router/with-memory-api.mdx113
-rw-r--r--apps/docs/model-enhancement/context-extender.mdx233
-rw-r--r--apps/docs/model-enhancement/getting-started.mdx99
-rw-r--r--apps/docs/model-enhancement/identifying-users.mdx119
-rw-r--r--apps/docs/openai-sdks/usage.mdx9
-rw-r--r--apps/docs/org-settings.mdx265
-rw-r--r--apps/docs/overview/use-cases.mdx110
-rw-r--r--apps/docs/overview/why-supermemory.mdx67
-rw-r--r--apps/docs/package.json14
-rw-r--r--apps/docs/quickstart.mdx879
-rw-r--r--apps/docs/routervsapi.mdx63
-rw-r--r--apps/docs/search/examples/document-search.mdx588
-rw-r--r--apps/docs/search/examples/memory-search.mdx472
-rw-r--r--apps/docs/search/filtering.mdx1059
-rw-r--r--apps/docs/search/overview.mdx376
-rw-r--r--apps/docs/search/parameters.mdx242
-rw-r--r--apps/docs/search/query-rewriting.mdx440
-rw-r--r--apps/docs/search/reranking.mdx387
-rw-r--r--apps/docs/search/response-schema.mdx261
-rw-r--r--apps/docs/snippets/getting-api-key.mdx34
-rw-r--r--apps/docs/supermemory-mcp/introduction.mdx74
-rw-r--r--apps/docs/supermemory-mcp/setup.mdx67
-rw-r--r--apps/docs/supermemory-mcp/technology.mdx48
-rw-r--r--apps/docs/update-delete-memories/overview.mdx510
121 files changed, 20188 insertions, 0 deletions
diff --git a/apps/docs/.cursor/rules/docs.mdc b/apps/docs/.cursor/rules/docs.mdc
new file mode 100644
index 00000000..6c2516e2
--- /dev/null
+++ b/apps/docs/.cursor/rules/docs.mdc
@@ -0,0 +1,84 @@
+---
+description:
+globs:
+alwaysApply: true
+---
+# Documentation MDX Format
+
+All documentation files use MDX format with a specific structure:
+
+## Frontmatter
+
+Every documentation file must begin with frontmatter:
+
+```mdx
+---
+title: "Page Title"
+description: "Brief description of the page content"
+icon: "icon-name" # Optional, uses Lucide icons
+sidebarTitle: "Optional Sidebar Title" # Optional
+---
+```
+
+Example: @features/query-rewriting.mdx
+
+## Components
+
+Use the following components to enhance documentation:
+
+### Accordion
+
+For collapsible sections:
+
+```mdx
+<Accordion title="Section Title" defaultOpen icon="sparkles">
+ Content goes here...
+</Accordion>
+```
+
+Example: @creation/supported-types.mdx
+
+### Notes and Warnings
+
+For important information:
+
+```mdx
+<Note>
+ Important information goes here.
+</Note>
+
+<Warning>
+ Critical warning goes here.
+</Warning>
+```
+
+Example: @creation/adding-memories.mdx
+
+### Code Examples
+
+For multi-language code examples:
+
+```mdx
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/endpoint \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY'
+```
+
+```typescript Typescript
+await client.method({
+ parameter: "value"
+})
+```
+
+```python Python
+client.method(
+ parameter="value"
+)
+```
+
+</CodeGroup>
+```
+
+Example: @essentials/authentication.mdx
diff --git a/apps/docs/.gitignore b/apps/docs/.gitignore
new file mode 100644
index 00000000..a14702c4
--- /dev/null
+++ b/apps/docs/.gitignore
@@ -0,0 +1,34 @@
+# dependencies (bun install)
+node_modules
+
+# output
+out
+dist
+*.tgz
+
+# code coverage
+coverage
+*.lcov
+
+# logs
+logs
+_.log
+report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
+
+# dotenv environment variable files
+.env
+.env.development.local
+.env.test.local
+.env.production.local
+.env.local
+
+# caches
+.eslintcache
+.cache
+*.tsbuildinfo
+
+# IntelliJ based IDEs
+.idea
+
+# Finder (MacOS) folder config
+.DS_Store
diff --git a/apps/docs/README.md b/apps/docs/README.md
new file mode 100644
index 00000000..2c7ff641
--- /dev/null
+++ b/apps/docs/README.md
@@ -0,0 +1 @@
+# supermemory Docs \ No newline at end of file
diff --git a/apps/docs/add-memories/examples/basic.mdx b/apps/docs/add-memories/examples/basic.mdx
new file mode 100644
index 00000000..e87893fc
--- /dev/null
+++ b/apps/docs/add-memories/examples/basic.mdx
@@ -0,0 +1,278 @@
+---
+title: "Basic Usage"
+description: "Simple examples of adding text content to Supermemory"
+---
+
+Learn how to add basic text content to Supermemory with simple, practical examples.
+
+## Add Simple Text
+
+The most basic operation - adding plain text content.
+
+<CodeGroup>
+
+```typescript TypeScript
+const response = await client.memories.add({
+ content: "Artificial intelligence is transforming how we work and live"
+});
+
+console.log(response);
+// Output: { id: "abc123", status: "queued" }
+```
+
+```python Python
+response = client.memories.add(
+ content="Artificial intelligence is transforming how we work and live"
+)
+
+print(response)
+# Output: {"id": "abc123", "status": "queued"}
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "content": "Artificial intelligence is transforming how we work and live"
+ }'
+```
+
+</CodeGroup>
+
+## Add with Container Tags
+
+Group related content using container tags.
+
+<CodeGroup>
+
+```typescript TypeScript
+const response = await client.memories.add({
+ content: "Q4 2024 revenue exceeded projections by 15%",
+ containerTag: "financial_reports"
+});
+
+console.log(response.id);
+// Output: xyz789
+```
+
+```python Python
+response = client.memories.add(
+ content="Q4 2024 revenue exceeded projections by 15%",
+ container_tag="financial_reports"
+)
+
+print(response['id'])
+# Output: xyz789
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "content": "Q4 2024 revenue exceeded projections by 15%",
+ "containerTag": "financial_reports"
+ }'
+
+# Response: {"id": "xyz789", "status": "queued"}
+```
+
+</CodeGroup>
+
+## Add with Metadata
+
+Attach metadata for better search and filtering.
+
+<CodeGroup>
+
+```typescript TypeScript
+await client.memories.add({
+ content: "New onboarding flow reduces drop-off by 30%",
+ containerTag: "product_updates",
+ metadata: {
+ impact: "high",
+ team: "product"
+ }
+});
+```
+
+```python Python
+client.memories.add(
+ content="New onboarding flow reduces drop-off by 30%",
+ container_tag="product_updates",
+ metadata={
+ "impact": "high",
+ "team": "product"
+ }
+)
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "content": "New onboarding flow reduces drop-off by 30%",
+ "containerTag": "product_updates",
+ "metadata": {"impact": "high", "team": "product"}
+ }'
+```
+
+</CodeGroup>
+
+## Add Multiple Documents
+
+Process multiple related documents.
+
+<CodeGroup>
+
+```typescript TypeScript
+const notes = [
+ "API redesign discussion",
+ "Security audit next month",
+ "New hire starting Monday"
+];
+
+const results = await Promise.all(
+ notes.map(note =>
+ client.memories.add({
+ content: note,
+ containerTag: "meeting_2024_01_15"
+ })
+ )
+);
+```
+
+```python Python
+notes = [
+ "API redesign discussion",
+ "Security audit next month",
+ "New hire starting Monday"
+]
+
+for note in notes:
+ client.memories.add(
+ content=note,
+ container_tag="meeting_2024_01_15"
+ )
+```
+
+```bash cURL
+# Add each note with separate requests
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"content": "API redesign discussion", "containerTag": "meeting_2024_01_15"}'
+```
+
+</CodeGroup>
+
+## Add URLs
+
+Process web pages, YouTube videos, and other URLs automatically.
+
+<CodeGroup>
+
+```typescript TypeScript
+// Web page
+await client.memories.add({
+ content: "https://example.com/article",
+ containerTag: "articles"
+});
+
+// YouTube video (auto-transcribed)
+await client.memories.add({
+ content: "https://youtube.com/watch?v=dQw4w9WgXcQ",
+ containerTag: "videos"
+});
+
+// Google Docs
+await client.memories.add({
+ content: "https://docs.google.com/document/d/abc123/edit",
+ containerTag: "docs"
+});
+```
+
+```python Python
+# Web page
+client.memories.add(
+ content="https://example.com/article",
+ container_tag="articles"
+)
+
+# YouTube video (auto-transcribed)
+client.memories.add(
+ content="https://youtube.com/watch?v=dQw4w9WgXcQ",
+ container_tag="videos"
+)
+
+# Google Docs
+client.memories.add(
+ content="https://docs.google.com/document/d/abc123/edit",
+ container_tag="docs"
+)
+```
+
+```bash cURL
+# Web page
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"content": "https://example.com/article", "containerTag": "articles"}'
+
+# YouTube video
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"content": "https://youtube.com/watch?v=dQw4w9WgXcQ", "containerTag": "videos"}'
+```
+
+</CodeGroup>
+
+## Add Markdown Content
+
+Supermemory preserves markdown formatting.
+
+<CodeGroup>
+
+```typescript TypeScript
+const markdown = `
+# Project Documentation
+
+## Features
+- **Real-time sync**
+- **AI search**
+- **Enterprise security**
+`;
+
+await client.memories.add({
+ content: markdown,
+ containerTag: "docs"
+});
+```
+
+```python Python
+markdown = """
+# Project Documentation
+
+## Features
+- **Real-time sync**
+- **AI search**
+- **Enterprise security**
+"""
+
+client.memories.add(
+ content=markdown,
+ container_tag="docs"
+)
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"content": "# Project Documentation\n\n## Features\n- **Real-time sync**\n- **AI search**", "containerTag": "docs"}'
+```
+
+</CodeGroup>
diff --git a/apps/docs/add-memories/examples/file-upload.mdx b/apps/docs/add-memories/examples/file-upload.mdx
new file mode 100644
index 00000000..b07a44b6
--- /dev/null
+++ b/apps/docs/add-memories/examples/file-upload.mdx
@@ -0,0 +1,195 @@
+---
+title: "File Upload"
+description: "Upload PDFs, images, and other files to Supermemory"
+---
+
+Upload files directly to Supermemory for automatic content extraction and processing.
+
+## Upload a PDF
+
+Extract text from PDFs with OCR support.
+
+<CodeGroup>
+
+```typescript TypeScript
+const file = fs.createReadStream('document.pdf');
+
+const response = await client.memories.uploadFile({
+ file: file,
+ containerTags: 'documents'
+});
+
+console.log(response.id);
+// Output: pdf_123
+```
+
+```python Python
+with open('document.pdf', 'rb') as file:
+ response = client.memories.upload_file(
+ file=file,
+ container_tags='documents'
+ )
+
+print(response['id'])
+# Output: pdf_123
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents/file" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -F "containerTags=documents"
+
+# Response: {"id": "pdf_123", "status": "processing"}
+```
+
+</CodeGroup>
+
+## Upload Images with OCR
+
+Extract text from images.
+
+<CodeGroup>
+
+```typescript TypeScript
+const image = fs.createReadStream('screenshot.png');
+
+await client.memories.uploadFile({
+ file: image,
+ containerTags: 'images'
+});
+```
+
+```python Python
+with open('screenshot.png', 'rb') as file:
+ client.memories.upload_file(
+ file=file,
+ container_tags='images'
+ )
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents/file" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -F "containerTags=images"
+```
+
+</CodeGroup>
+
+## Browser File Upload
+
+Handle browser file uploads.
+
+<CodeGroup>
+
+```javascript JavaScript
+const formData = new FormData();
+formData.append('file', fileInput.files[0]);
+formData.append('containerTags', 'uploads');
+
+const response = await fetch('https://api.supermemory.ai/v3/documents/file', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${API_KEY}`
+ },
+ body: formData
+});
+
+const result = await response.json();
+console.log(result.id);
+```
+
+```typescript React
+function handleUpload(file: File) {
+ const formData = new FormData();
+ formData.append('file', file);
+ formData.append('containerTags', 'uploads');
+
+ return fetch('https://api.supermemory.ai/v3/documents/file', {
+ method: 'POST',
+ headers: { 'Authorization': `Bearer ${API_KEY}` },
+ body: formData
+ });
+}
+```
+
+```bash cURL
+# Browser uploads use FormData, same as file upload
+curl -X POST "https://api.supermemory.ai/v3/documents/file" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -F "containerTags=uploads"
+```
+
+</CodeGroup>
+
+## Upload Multiple Files
+
+Batch upload with rate limiting.
+
+<CodeGroup>
+
+```typescript TypeScript
+for (const file of files) {
+ const stream = fs.createReadStream(file);
+
+ await client.memories.uploadFile({
+ file: stream,
+ containerTags: 'batch'
+ });
+
+ // Rate limit
+ await new Promise(r => setTimeout(r, 1000));
+}
+```
+
+```python Python
+import time
+
+for file_path in files:
+ with open(file_path, 'rb') as file:
+ client.memories.upload_file(
+ file=file,
+ container_tags='batch'
+ )
+
+ time.sleep(1) # Rate limit
+```
+
+```bash cURL
+# Upload each file separately with delays
+for file in *.pdf; do
+ curl -X POST "https://api.supermemory.ai/v3/documents/file" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -F "file=@$file" \
+ -F "containerTags=batch"
+
+ sleep 1 # Rate limit
+done
+```
+
+</CodeGroup>
+
+## Supported File Types
+
+### Documents
+| Format | Extensions | Processing |
+|--------|------------|------------|
+| PDF | .pdf | Text extraction, OCR for scanned pages |
+| Microsoft Word | .doc, .docx | Full text and formatting extraction |
+| Plain Text | .txt, .md | Direct text processing |
+| CSV | .csv | Structured data extraction |
+
+### Images
+| Format | Extensions | Processing |
+|--------|------------|------------|
+| JPEG | .jpg, .jpeg | OCR text extraction |
+| PNG | .png | OCR text extraction |
+| GIF | .gif | OCR for static images |
+| WebP | .webp | OCR text extraction |
+
+### Size Limits
+- **Maximum file size**: 50MB
+- **Recommended size**: < 10MB for optimal processing
+- **Large files**: May take longer to process
diff --git a/apps/docs/add-memories/overview.mdx b/apps/docs/add-memories/overview.mdx
new file mode 100644
index 00000000..6294147e
--- /dev/null
+++ b/apps/docs/add-memories/overview.mdx
@@ -0,0 +1,210 @@
+---
+title: "Add Memories Overview"
+description: "Add content to Supermemory through text, files, or URLs"
+sidebarTitle: "Overview"
+---
+
+Add any type of content to Supermemory - text, files, URLs, images, videos, and more. Everything is automatically processed into searchable memories that form part of your intelligent knowledge graph.
+
+## Quick Start
+
+<CodeGroup>
+
+```typescript TypeScript
+// Add text content
+const result = await client.memories.add({
+ content: "Machine learning enables computers to learn from data",
+ containerTag: "ai-research",
+ metadata: { priority: "high" }
+});
+
+console.log(result);
+// Output: { id: "abc123", status: "queued" }
+```
+
+```python Python
+# Add text content
+result = client.memories.add(
+ content="Machine learning enables computers to learn from data",
+ container_tags=["ai-research"],
+ metadata={"priority": "high"}
+)
+
+print(result)
+# Output: {"id": "abc123", "status": "queued"}
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "content": "Machine learning enables computers to learn from data",
+ "containerTag": "ai-research",
+ "metadata": {"priority": "high"}
+ }'
+
+# Response: {"id": "abc123", "status": "queued"}
+```
+
+</CodeGroup>
+
+## Key Concepts
+
+<Note>
+**New to Supermemory?** Read [How Supermemory Works](/how-it-works) to understand the knowledge graph architecture and the distinction between documents and memories.
+</Note>
+
+### Quick Overview
+- **Documents**: Raw content you upload (PDFs, URLs, text)
+- **Memories**: Searchable chunks created automatically with relationships
+- **Container Tags**: Group related content for better context
+- **Metadata**: Additional information for filtering
+
+### Content Sources
+
+Add content through three methods:
+
+1. **Direct Text**: Send text content directly via API
+2. **File Upload**: Upload PDFs, images, videos for extraction
+3. **URL Processing**: Automatic extraction from web pages and platforms
+
+## Endpoints
+
+<Warning>
+Remember, these endpoints add documents. Memories are inferred by Supermemory.
+</Warning>
+
+### Add Content
+
+`POST /v3/documents`
+
+Add text content, URLs, or any supported format.
+
+<CodeGroup>
+
+```typescript TypeScript
+await client.memories.add({
+ content: "Your content here",
+ containerTag: "project"
+});
+```
+
+```python Python
+client.memories.add(
+ content="Your content here",
+ container_tags=["project"]
+)
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"content": "Your content here", "containerTag": "project"}'
+```
+
+</CodeGroup>
+
+### Upload File
+
+`POST /v3/documents/file`
+
+Upload files directly for processing.
+
+<CodeGroup>
+
+```typescript TypeScript
+await client.memories.uploadFile({
+ file: fileStream,
+ containerTag: "project"
+});
+```
+
+```python Python
+client.memories.upload_file(
+ file=open('file.pdf', 'rb'),
+ container_tags='project'
+)
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/documents/file" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -F "containerTags=project"
+```
+
+</CodeGroup>
+
+### Update Memory
+
+`PATCH /v3/documents/{id}`
+
+Update existing document content.
+
+<CodeGroup>
+
+```typescript TypeScript
+await client.memories.update("doc_id", {
+ content: "Updated content"
+});
+```
+
+```python Python
+client.memories.update("doc_id", {
+ "content": "Updated content"
+})
+```
+
+```bash cURL
+curl -X PATCH "https://api.supermemory.ai/v3/documents/doc_id" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"content": "Updated content"}'
+```
+
+</CodeGroup>
+
+## Supported Content Types
+
+### Documents
+- PDF with OCR support
+- Google Docs, Sheets, Slides
+- Notion pages
+- Microsoft Office files
+
+### Media
+- Images (JPG, PNG, GIF, WebP) with OCR
+
+### Web Content
+- Twitter/X posts
+- YouTube videos with captions
+
+### Text Formats
+- Plain text
+- Markdown
+- CSV files
+
+<Note> Refer to the [connectors guide](/connectors/overview) to learn how you can connect Google Drive, Notion, and OneDrive and sync files in real-time. </Note>
+
+## Response Format
+
+```json
+{
+ "id": "D2Ar7Vo7ub83w3PRPZcaP1",
+ "status": "queued"
+}
+```
+
+- **`id`**: Unique document identifier
+- **`status`**: Processing state (`queued`, `processing`, `done`)
+
+
+
+## Next Steps
+
+- [Track Processing Status](/api/track-progress) - Monitor document processing
+- [Search Memories](/search/overview) - Search your content
+- [List Memories](/list-memories/overview) - Browse stored memories
+- [Update & Delete](/update-delete-memories/overview) - Manage memories
diff --git a/apps/docs/add-memories/parameters.mdx b/apps/docs/add-memories/parameters.mdx
new file mode 100644
index 00000000..dedfad0e
--- /dev/null
+++ b/apps/docs/add-memories/parameters.mdx
@@ -0,0 +1,156 @@
+---
+title: "Parameters"
+description: "Complete reference for add memory parameters"
+---
+
+Detailed parameter documentation for adding memories to Supermemory.
+
+## Request Parameters
+
+### Required Parameters
+
+<ParamField body="content" type="string" required>
+ The content to process into memories. Can be:
+ - Plain text content
+ - URL to process
+ - HTML content
+ - Markdown text
+
+ ```json
+ {
+ "content": "Machine learning is a subset of AI..."
+ }
+ ```
+
+ **URL Examples:**
+ ```json
+ {
+ "content": "https://youtube.com/watch?v=dQw4w9WgXcQ"
+ }
+ ```
+</ParamField>
+
+### Optional Parameters
+
+<ParamField body="containerTag" type="string">
+ **Recommended.** Single tag to group related memories. Improves search performance.
+
+ Default: `"sm_project_default"`
+
+ ```json
+ {
+ "containerTag": "project_alpha"
+ }
+ ```
+
+ <Note>
+ Use `containerTag` (singular) for better performance than `containerTags` (array).
+ </Note>
+</ParamField>
+
+<ParamField body="metadata" type="object">
+ Additional metadata as key-value pairs. Values must be strings, numbers, or booleans.
+
+ ```json
+ {
+ "metadata": {
+ "source": "research-paper",
+ "author": "John Doe",
+ "priority": 1,
+ "reviewed": true
+ }
+ }
+ ```
+
+ **Restrictions:**
+ - No nested objects
+ - No arrays as values
+ - Keys must be strings
+ - Values: string, number, or boolean only
+</ParamField>
+
+<ParamField body="customId" type="string">
+ Your own identifier for the document. Enables deduplication and updates.
+
+ **Maximum length:** 255 characters
+
+ ```json
+ {
+ "customId": "doc_2024_01_research_ml"
+ }
+ ```
+
+ **Use cases:**
+ - Prevent duplicate uploads
+ - Update existing documents
+ - Sync with external systems
+</ParamField>
+
+<ParamField body="raw" type="string">
+ Raw content to store alongside processed content. Useful for preserving original formatting.
+
+ ```json
+ {
+ "content": "# Machine Learning\n\nML is a subset of AI...",
+ "raw": "# Machine Learning\n\nML is a subset of AI..."
+ }
+ ```
+</ParamField>
+
+## File Upload Parameters
+
+For `POST /v3/documents/file` endpoint:
+
+<ParamField body="file" type="file" required>
+ The file to upload. Supported formats:
+ - **Documents:** PDF, DOC, DOCX, TXT, MD
+ - **Images:** JPG, PNG, GIF, WebP
+ - **Videos:** MP4, WebM, AVI
+
+ **Maximum size:** 50MB
+</ParamField>
+
+<ParamField body="containerTags" type="string">
+ Container tag for the uploaded file (sent as form field).
+
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/file" \
+ -F "containerTags=research"
+ ```
+</ParamField>
+
+
+## Container Tag Patterns
+
+### Recommended Patterns
+
+```typescript
+// By user
+"user_123"
+
+// By project
+"project_alpha"
+
+// By organization and type
+"org_456_research"
+
+// By time period
+"2024_q1_reports"
+
+// By data source
+"slack_channel_general"
+```
+
+### Performance Considerations
+
+```typescript
+// ✅ FAST: Single tag
+{ "containerTag": "project_alpha" }
+
+// ⚠️ SLOWER: Multiple tags
+{ "containerTags": ["project_alpha", "backend", "auth"] }
+
+// ❌ AVOID: Too many tags
+{ "containerTags": ["tag1", "tag2", "tag3", "tag4", "tag5"] }
+```
diff --git a/apps/docs/ai-sdk/examples.mdx b/apps/docs/ai-sdk/examples.mdx
new file mode 100644
index 00000000..a0827e6c
--- /dev/null
+++ b/apps/docs/ai-sdk/examples.mdx
@@ -0,0 +1,426 @@
+---
+title: "AI SDK Examples"
+description: "Complete examples showing how to use Supermemory with Vercel AI SDK"
+sidebarTitle: "Examples"
+---
+
+This page provides comprehensive examples of using Supermemory with the Vercel AI SDK, covering both Memory Tools and Infinite Chat approaches.
+
+## Personal Assistant with Memory Tools
+
+Build an AI assistant that remembers user preferences and past interactions:
+
+<CodeGroup>
+
+```typescript Next.js API Route
+import { streamText } from 'ai'
+import { createAnthropic } from '@ai-sdk/anthropic'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+const anthropic = createAnthropic({
+ apiKey: process.env.ANTHROPIC_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages } = await request.json()
+
+ const result = await streamText({
+ model: anthropic('claude-3-sonnet-20240229'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!),
+ system: `You are a helpful personal assistant. When users share information about themselves,
+ remember it using the addMemory tool. When they ask questions, search your memories to provide
+ personalized responses. Always be proactive about remembering important details.`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+```typescript Client Component
+'use client'
+
+import { useChat } from 'ai/react'
+
+export default function PersonalAssistant() {
+ const { messages, input, handleInputChange, handleSubmit } = useChat()
+
+ return (
+ <div className="flex flex-col h-screen max-w-2xl mx-auto p-4">
+ <div className="flex-1 overflow-y-auto space-y-4">
+ {messages.map((message) => (
+ <div
+ key={message.id}
+ className={`p-4 rounded-lg ${
+ message.role === 'user' ? 'bg-blue-100 ml-auto' : 'bg-gray-100'
+ }`}
+ >
+ <p>{message.content}</p>
+ </div>
+ ))}
+ </div>
+
+ <form onSubmit={handleSubmit} className="mt-4">
+ <input
+ value={input}
+ onChange={handleInputChange}
+ placeholder="Tell me about yourself or ask me anything..."
+ className="w-full p-2 border rounded"
+ />
+ </form>
+ </div>
+ )
+}
+```
+
+</CodeGroup>
+
+**Example conversation:**
+- User: "I'm allergic to peanuts and I love Italian food"
+- AI: *Uses addMemory tool* "I've remembered that you're allergic to peanuts and love Italian food!"
+- User: "Suggest a restaurant for dinner"
+- AI: *Uses searchMemories tool* "Based on what I know about you, I'd recommend an Italian restaurant that's peanut-free..."
+
+## Customer Support with Context
+
+Build a customer support system that remembers customer history:
+
+```typescript
+import { streamText } from 'ai'
+import { createOpenAI } from '@ai-sdk/openai'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages, customerId } = await request.json()
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-user-id': customerId
+ }
+ }),
+ system: `You are a customer support agent. Before responding to any query:
+ 1. Search for the customer's previous interactions and issues
+ 2. Remember any new information shared in this conversation
+ 3. Provide personalized help based on their history
+ 4. Always be empathetic and solution-focused`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+## Infinite Chat for Documentation
+
+Create a documentation assistant with unlimited context:
+
+<CodeGroup>
+
+```typescript Documentation Chat
+import { streamText } from 'ai'
+
+const supermemoryInfiniteChat = createOpenAI({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+export async function POST(request: Request) {
+ const { messages } = await request.json()
+
+ const result = await streamText({
+ model: supermemoryInfiniteChat('gpt-4-turbo'),
+ messages,
+ system: `You are a documentation assistant. You have access to all previous
+ conversations and can reference earlier discussions. Help users understand
+ the documentation by building on previous context.`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+```typescript Upload Documentation
+// Separate endpoint to upload documentation to memory
+import { addMemory } from '@supermemory/tools'
+
+export async function POST(request: Request) {
+ const { content, title, url } = await request.json()
+
+ const memory = await addMemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!,
+ content,
+ title,
+ url,
+ headers: {
+ 'x-sm-conversation-id': 'documentation'
+ }
+ })
+
+ return Response.json({ success: true, memory })
+}
+```
+
+</CodeGroup>
+
+## Multi-User Learning Assistant
+
+Build an assistant that learns from multiple users but keeps data separate:
+
+```typescript
+import { streamText } from 'ai'
+import { createAnthropic } from '@ai-sdk/anthropic'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+const anthropic = createAnthropic({
+ apiKey: process.env.ANTHROPIC_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages, userId, courseId } = await request.json()
+
+ const result = await streamText({
+ model: anthropic('claude-3-haiku-20240307'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-user-id': userId,
+ 'x-sm-conversation-id': `course-${courseId}`
+ }
+ }),
+ system: `You are a learning assistant. Help students with their coursework by:
+ 1. Remembering their learning progress and struggles
+ 2. Searching for relevant information from their past sessions
+ 3. Providing personalized explanations based on their learning style
+ 4. Tracking topics they've mastered vs topics they need more help with`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+## Research Assistant with File Processing
+
+Combine file upload with memory tools for research assistance:
+
+<CodeGroup>
+
+```typescript API Route
+import { streamText } from 'ai'
+import { createOpenAI } from '@ai-sdk/openai'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages, projectId } = await request.json()
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-conversation-id': projectId
+ }
+ }),
+ system: `You are a research assistant. You can:
+ 1. Search through uploaded research papers and documents
+ 2. Remember key findings and insights from conversations
+ 3. Help synthesize information across multiple sources
+ 4. Track research progress and important discoveries`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+```typescript File Upload Handler
+import { addMemory } from '@supermemory/tools'
+
+export async function POST(request: Request) {
+ const formData = await request.formData()
+ const file = formData.get('file') as File
+ const projectId = formData.get('projectId') as string
+
+ // Upload file and add to memory
+ const memory = await addMemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!,
+ content: file, // Supermemory handles file processing
+ title: file.name,
+ headers: {
+ 'x-sm-conversation-id': projectId
+ }
+ })
+
+ return Response.json({
+ success: true,
+ message: "Document uploaded and processed for research",
+ memoryId: memory.id
+ })
+}
+```
+
+</CodeGroup>
+
+## Code Assistant with Project Memory
+
+Create a coding assistant that remembers your codebase and preferences:
+
+```typescript
+import { streamText } from 'ai'
+import { createAnthropic } from '@ai-sdk/anthropic'
+import {
+ supermemoryTools,
+ searchMemoriesTool,
+ addMemoryTool
+} from '@supermemory/tools/ai-sdk'
+
+const anthropic = createAnthropic({
+ apiKey: process.env.ANTHROPIC_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages, repositoryId } = await request.json()
+
+ const result = await streamText({
+ model: anthropic('claude-3-sonnet-20240229'),
+ messages,
+ tools: {
+ // Use individual tools for more control
+ searchMemories: searchMemoriesTool(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-conversation-id': `repo-${repositoryId}`
+ }
+ }),
+ addMemory: addMemoryTool(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-conversation-id': `repo-${repositoryId}`
+ }
+ }),
+ // Add custom tools
+ executeCode: {
+ description: 'Execute code in a sandbox environment',
+ parameters: z.object({
+ code: z.string(),
+ language: z.string()
+ }),
+ execute: async ({ code, language }) => {
+ // Your code execution logic
+ return { result: "Code executed successfully" }
+ }
+ }
+ },
+ system: `You are a coding assistant with memory. You can:
+ 1. Remember coding patterns and preferences from past conversations
+ 2. Search through previous code examples and solutions
+ 3. Track project architecture and design decisions
+ 4. Learn from debugging sessions and common issues`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+## Advanced: Custom Tool Integration
+
+Combine Supermemory tools with your own custom tools:
+
+```typescript
+import { streamText } from 'ai'
+import { createOpenAI } from '@ai-sdk/openai'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+import { z } from 'zod'
+
+const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+})
+
+// Custom tool for calendar integration
+const calendarTool = {
+ description: 'Create calendar events',
+ parameters: z.object({
+ title: z.string(),
+ date: z.string(),
+ duration: z.number()
+ }),
+ execute: async ({ title, date, duration }) => {
+ // Your calendar API integration
+ return { eventId: "cal_123", message: "Event created" }
+ }
+}
+
+export async function POST(request: Request) {
+ const { messages } = await request.json()
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ tools: {
+ // Spread Supermemory tools
+ ...supermemoryTools(process.env.SUPERMEMORY_API_KEY!),
+ // Add custom tools
+ createEvent: calendarTool,
+ },
+ system: `You are a personal assistant that can remember information and
+ manage calendars. When users mention events or appointments:
+ 1. Remember the details using addMemory
+ 2. Create calendar events using createEvent
+ 3. Search for conflicts using searchMemories`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+## Environment Setup
+
+For all examples, ensure you have these environment variables:
+
+```bash .env.local
+SUPERMEMORY_API_KEY=your_supermemory_key
+OPENAI_API_KEY=your_openai_key
+ANTHROPIC_API_KEY=your_anthropic_key
+```
+
+## Best Practices
+
+### Memory Tools
+- Use descriptive memory content for better search results
+- Include context in your system prompts about when to use each tool
+- Use project headers to separate different use cases
+- Implement error handling for tool failures
+
+### Infinite Chat
+- Use conversation IDs to maintain separate chat contexts
+- Include user IDs for personalized experiences
+- Test with different providers to find the best fit for your use case
+- Monitor token usage for cost optimization
+
+### General Tips
+- Start with simple examples and gradually add complexity
+- Use the search functionality to avoid duplicate memories
+- Implement proper authentication for production use
+- Consider rate limiting for high-volume applications
+
+## Next Steps
+
+<CardGroup cols={2}>
+ <Card title="Memory API" icon="database" href="/memory-api/overview">
+ Advanced memory management with full API control
+ </Card>
+
+ <Card title="Memory Router" icon="route" href="/memory-router/overview">
+ Drop-in proxy for existing LLM applications
+ </Card>
+</CardGroup>
diff --git a/apps/docs/ai-sdk/infinite-chat.mdx b/apps/docs/ai-sdk/infinite-chat.mdx
new file mode 100644
index 00000000..b287eb5b
--- /dev/null
+++ b/apps/docs/ai-sdk/infinite-chat.mdx
@@ -0,0 +1,216 @@
+---
+title: "Infinite Chat"
+description: "Unlimited context for chat applications with automatic memory management"
+sidebarTitle: "Infinite Chat"
+---
+
+Infinite Chat provides unlimited context for chat applications with automatic memory management.
+
+## Setup
+
+```typescript
+import { streamText } from "ai"
+
+const infiniteChat = createAnthropic({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.anthropic.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+const result = await streamText({
+ model: infiniteChat("claude-3-sonnet"),
+ messages: [
+ { role: "user", content: "Hello! Remember that I love TypeScript." }
+ ]
+})
+```
+
+## Provider Configuration
+
+### Named Providers
+
+<CodeGroup>
+
+```typescript OpenAI
+const infiniteChat = createOpenAI({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+const result = await streamText({
+ model: infiniteChat("gpt-4-turbo"),
+ messages: [...]
+})
+```
+
+```typescript Anthropic
+const infiniteChat = createAnthropic({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.anthropic.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+const result = await streamText({
+ model: infiniteChat("claude-3-sonnet"),
+ messages: [...]
+})
+```
+
+```typescript Google
+const infiniteChat = createGoogleGenerativeAI({
+ baseUrl: 'https://api.supermemory.ai/v3/https://generativelanguage.googleapis.com/v1beta',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+const result = await streamText({
+ model: infiniteChat("gemini-pro"),
+ messages: [...]
+})
+```
+
+```typescript Groq
+const infiniteChat = createGroq({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.groq.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+const result = await streamText({
+ model: infiniteChat("mixtral-8x7b"),
+ messages: [...]
+})
+```
+
+</CodeGroup>
+
+### Custom Provider URL
+
+```typescript
+const infiniteChat = createOpenAI({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+```
+
+## Example Usage
+
+```typescript
+import { streamText } from "ai"
+
+const infiniteChat = createOpenAI({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+const result = await streamText({
+ model: infiniteChat("gpt-4-turbo"),
+ messages: [
+ { role: "user", content: "What did we discuss yesterday?" }
+ ]
+})
+
+return result.toAIStreamResponse()
+```
+
+## Configuration Options
+
+```typescript
+interface ConfigWithProviderName {
+ providerName: 'openai' | 'anthropic' | 'openrouter' |
+ 'deepinfra' | 'groq' | 'google' | 'cloudflare'
+ providerApiKey: string
+ headers?: Record<string, string>
+}
+
+interface ConfigWithProviderUrl {
+ providerUrl: string
+ providerApiKey: string
+ headers?: Record<string, string>
+}
+```
+
+### Custom Headers
+
+Add user IDs, conversation IDs, or other metadata:
+
+```typescript
+const infiniteChat = createOpenAI({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+```
+
+## Comparison with Memory Tools
+
+| Feature | Infinite Chat | Memory Tools |
+|---------|--------------|--------------|
+| Memory Management | Automatic | Manual |
+| Context Handling | Automatic | Manual |
+| Tool Calls | None | searchMemories, addMemory, fetchMemory |
+| Best For | Chat apps | AI agents |
+| Setup Complexity | Simple | Moderate |
+
+## Headers
+
+Add user and conversation context:
+
+```typescript
+const infiniteChat = createOpenAI({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+```
+
+## Comparison
+
+| Feature | Infinite Chat | Memory Tools |
+|---------|--------------|-------------|
+| Memory Management | Automatic | Manual |
+| Context Handling | Automatic | Manual |
+| Tool Calls | None | searchMemories, addMemory, fetchMemory |
+| Best For | Chat apps | AI agents |
+
+## Next Steps
+
+<CardGroup cols={2}>
+ <Card title="Memory Tools" icon="wrench" href="/ai-sdk/memory-tools">
+ Explore explicit memory control
+ </Card>
+
+ <Card title="Examples" icon="code" href="/cookbook/ai-sdk-integration">
+ See complete implementations
+ </Card>
+</CardGroup>
diff --git a/apps/docs/ai-sdk/memory-tools.mdx b/apps/docs/ai-sdk/memory-tools.mdx
new file mode 100644
index 00000000..69b961e1
--- /dev/null
+++ b/apps/docs/ai-sdk/memory-tools.mdx
@@ -0,0 +1,147 @@
+---
+title: "Memory Tools"
+description: "Add memory capabilities to your AI agents with Vercel AI SDK tools"
+sidebarTitle: "Memory Tools"
+---
+
+Memory tools allow AI agents to search, add, and fetch memories.
+
+## Setup
+
+```typescript
+import { streamText } from "ai"
+import { createOpenAI } from "@ai-sdk/openai"
+import { supermemoryTools } from "@supermemory/tools/ai-sdk"
+
+const openai = createOpenAI({
+ apiKey: "YOUR_OPENAI_KEY"
+})
+
+const result = await streamText({
+ model: openai("gpt-4-turbo"),
+ prompt: "Remember that my name is Alice",
+ tools: supermemoryTools("YOUR_SUPERMEMORY_KEY")
+})
+```
+
+## Available Tools
+
+### Search Memories
+
+Semantic search through user memories:
+
+```typescript
+const result = await streamText({
+ model: openai("gpt-4"),
+ prompt: "What are my dietary preferences?",
+ tools: supermemoryTools("API_KEY")
+})
+
+// The AI will automatically call searchMemories tool
+// Example tool call:
+// searchMemories({ informationToGet: "dietary preferences and restrictions" })
+```
+
+### Add Memory
+
+Store new information:
+
+```typescript
+const result = await streamText({
+ model: anthropic("claude-3-sonnet"),
+ prompt: "Remember that I'm allergic to peanuts",
+ tools: supermemoryTools("API_KEY")
+})
+
+// The AI will automatically call addMemory tool
+// Example tool call:
+// addMemory({ memory: "User is allergic to peanuts" })
+```
+
+### Fetch Memory
+
+Retrieve specific memory by ID:
+
+```typescript
+const result = await streamText({
+ model: openai("gpt-4"),
+ prompt: "Get the details of memory abc123",
+ tools: supermemoryTools("API_KEY")
+})
+
+// The AI will automatically call fetchMemory tool
+// Example tool call:
+// fetchMemory({ memoryId: "abc123" })
+```
+
+## Using Individual Tools
+
+For more control, import tools separately:
+
+```typescript
+import {
+ searchMemoriesTool,
+ addMemoryTool,
+ fetchMemoryTool
+} from "@supermemory/tools/ai-sdk"
+
+// Use only search tool
+const result = await streamText({
+ model: openai("gpt-4"),
+ prompt: "What do you know about me?",
+ tools: {
+ searchMemories: searchMemoriesTool("API_KEY", {
+ projectId: "personal"
+ })
+ }
+})
+
+// Combine with custom tools
+const result = await streamText({
+ model: anthropic("claude-3"),
+ prompt: "Help me with my calendar",
+ tools: {
+ searchMemories: searchMemoriesTool("API_KEY"),
+ // Your custom tools
+ createEvent: yourCustomTool,
+ sendEmail: anotherCustomTool
+ }
+})
+```
+
+## Tool Results
+
+Each tool returns a result object:
+
+```typescript
+// searchMemories result
+{
+ success: true,
+ results: [...], // Array of memories
+ count: 5
+}
+
+// addMemory result
+{
+ success: true,
+ memory: { id: "mem_123", ... }
+}
+
+// fetchMemory result
+{
+ success: true,
+ memory: { id: "mem_123", content: "...", ... }
+}
+```
+
+## Next Steps
+
+<CardGroup cols={2}>
+ <Card title="Infinite Chat" icon="infinity" href="/ai-sdk/infinite-chat">
+ Try automatic memory management
+ </Card>
+
+ <Card title="Examples" icon="code" href="/cookbook/ai-sdk-integration">
+ See more complete examples
+ </Card>
+</CardGroup>
diff --git a/apps/docs/ai-sdk/npm.mdx b/apps/docs/ai-sdk/npm.mdx
new file mode 100644
index 00000000..88ced6c2
--- /dev/null
+++ b/apps/docs/ai-sdk/npm.mdx
@@ -0,0 +1,5 @@
+---
+title: "NPM link"
+url: "https://www.npmjs.com/package/@supermemory/tools"
+icon: npm
+---
diff --git a/apps/docs/ai-sdk/overview.mdx b/apps/docs/ai-sdk/overview.mdx
new file mode 100644
index 00000000..3192fea1
--- /dev/null
+++ b/apps/docs/ai-sdk/overview.mdx
@@ -0,0 +1,80 @@
+---
+title: "AI SDK Integration"
+description: "Use Supermemory with Vercel AI SDK for seamless memory management"
+sidebarTitle: "Overview"
+---
+
+The Supermemory AI SDK provides native integration with Vercel's AI SDK through two approaches: **Memory Tools** for agent-based interactions and **Infinite Chat** for automatic context management.
+
+<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>
+
+## Installation
+
+```bash
+npm install @supermemory/tools
+```
+
+## Memory Tools
+
+Add memory capabilities to AI agents with search, add, and fetch operations.
+
+```typescript
+import { streamText } from "ai"
+import { createAnthropic } from "@ai-sdk/anthropic"
+import { supermemoryTools } from "@supermemory/tools/ai-sdk"
+
+const anthropic = createAnthropic({
+ apiKey: "YOUR_ANTHROPIC_KEY"
+})
+
+const result = await streamText({
+ model: anthropic("claude-3-sonnet"),
+ prompt: "Remember that my name is Alice",
+ tools: supermemoryTools("YOUR_SUPERMEMORY_KEY")
+})
+```
+
+## Infinite Chat
+
+Automatic memory management for chat applications with unlimited context.
+
+```typescript
+import { streamText } from "ai"
+
+const infiniteChat = createAnthropic({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.anthropic.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+const result = await streamText({
+ model: infiniteChat("claude-3-sonnet"),
+ messages: [
+ { role: "user", content: "What's my name?" }
+ ]
+})
+```
+
+## When to Use
+
+| Approach | Use Case |
+|----------|----------|
+| Memory Tools | AI agents that need explicit memory control |
+| Infinite Chat | Chat applications with automatic context |
+
+## Next Steps
+
+<CardGroup cols={2}>
+ <Card title="Memory Tools" icon="wrench" href="/ai-sdk/memory-tools">
+ Agent-based memory management
+ </Card>
+
+ <Card title="Infinite Chat" icon="infinity" href="/ai-sdk/infinite-chat">
+ Automatic context management
+ </Card>
+</CardGroup>
diff --git a/apps/docs/analytics.mdx b/apps/docs/analytics.mdx
new file mode 100644
index 00000000..a0927663
--- /dev/null
+++ b/apps/docs/analytics.mdx
@@ -0,0 +1,300 @@
+---
+title: "Analytics & Monitoring"
+description: "Observe usage, errors, and logs to monitor your Supermemory integration"
+icon: "chart-line"
+---
+
+Monitor your Supermemory usage with detailed analytics on API calls, errors, and performance metrics.
+
+## Overview
+
+The Analytics API provides comprehensive insights into your Supermemory usage:
+
+- **Usage Statistics**: Track API calls by type, hourly trends, and per-API key breakdown
+- **Error Monitoring**: Identify top error types and patterns
+- **Detailed Logs**: Access complete request/response logs for debugging
+- **Performance Metrics**: Monitor average response times and processing duration
+
+<Note>
+Analytics data is available for your entire organization and can be filtered by time period.
+</Note>
+
+## Usage Statistics
+
+Get comprehensive usage statistics including hourly breakdowns and per-key metrics.
+
+### Endpoint
+
+`GET /v3/analytics/usage`
+
+### Parameters
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `from` | string (ISO 8601) | Start date/time for the period |
+| `to` | string (ISO 8601) | End date/time for the period |
+| `period` | string | Alternative to `from`: `1h`, `24h`, `7d`, `30d` |
+| `page` | integer | Page number for pagination (default: 1) |
+| `limit` | integer | Items per page (default: 20, max: 100) |
+
+### Example Request
+
+<CodeGroup>
+
+```typescript TypeScript
+// Get usage for the last 24 hours
+const usage = await fetch('https://api.supermemory.ai/v3/analytics/usage?period=24h', {
+ headers: {
+ 'Authorization': `Bearer ${SUPERMEMORY_API_KEY}`
+ }
+});
+
+const data = await usage.json();
+```
+
+```python Python
+import requests
+from datetime import datetime, timedelta
+
+# Get usage for the last 7 days
+response = requests.get(
+ 'https://api.supermemory.ai/v3/analytics/usage',
+ params={'period': '7d'},
+ headers={'Authorization': f'Bearer {SUPERMEMORY_API_KEY}'}
+)
+
+data = response.json()
+```
+
+```bash cURL
+# Get usage for a specific date range
+curl -X GET "https://api.supermemory.ai/v3/analytics/usage?from=2024-01-01T00:00:00Z&to=2024-01-31T23:59:59Z" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+```
+
+</CodeGroup>
+
+### Response Schema
+
+```json
+{
+ "usage": [
+ {
+ "type": "add",
+ "count": 1523,
+ "avgDuration": 245.5,
+ "lastUsed": "2024-01-15T14:30:00Z"
+ },
+ {
+ "type": "search",
+ "count": 3421,
+ "avgDuration": 89.2,
+ "lastUsed": "2024-01-15T14:35:00Z"
+ }
+ ],
+ "hourly": [
+ {
+ "hour": "2024-01-15T14:00:00Z",
+ "count": 156,
+ "avgDuration": 125.3
+ }
+ ],
+ "byKey": [
+ {
+ "keyId": "key_abc123",
+ "keyName": "Production API",
+ "count": 2341,
+ "avgDuration": 98.7,
+ "lastUsed": "2024-01-15T14:35:00Z"
+ }
+ ],
+ "totalMemories": 45678,
+ "pagination": {
+ "currentPage": 1,
+ "limit": 20,
+ "totalItems": 150,
+ "totalPages": 8
+ }
+}
+```
+
+## Error Monitoring
+
+Track and analyze errors to identify issues and improve reliability.
+
+### Endpoint
+
+`GET /v3/analytics/errors`
+
+### Parameters
+
+Same as usage endpoint - supports `from`, `to`, `period`, `page`, and `limit`.
+
+### Example Request
+
+<CodeGroup>
+
+```typescript TypeScript
+// Get errors from the last 24 hours
+const errors = await fetch('https://api.supermemory.ai/v3/analytics/errors?period=24h', {
+ headers: {
+ 'Authorization': `Bearer ${SUPERMEMORY_API_KEY}`
+ }
+});
+
+const data = await errors.json();
+```
+
+```python Python
+# Monitor errors and alert on spikes
+response = requests.get(
+ 'https://api.supermemory.ai/v3/analytics/errors?period=1h',
+ headers={'Authorization': f'Bearer {SUPERMEMORY_API_KEY}'}
+)
+
+data = response.json()
+```
+
+```bash cURL
+# Get errors for the last 7 days
+curl -X GET "https://api.supermemory.ai/v3/analytics/errors?period=7d" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+```
+
+</CodeGroup>
+
+### Response Schema
+
+```json
+{
+ "totalErrors": 234,
+ "errorRate": 0.023,
+ "topErrors": [
+ {
+ "type": "ValidationError",
+ "count": 89,
+ "statusCodes": [400],
+ "lastOccurred": "2024-01-15T14:30:00Z"
+ },
+ {
+ "type": "RateLimitError",
+ "count": 45,
+ "statusCodes": [429],
+ "lastOccurred": "2024-01-15T13:15:00Z"
+ }
+ ],
+ "timeline": [
+ {
+ "time": "2024-01-15T14:00:00Z",
+ "count": 12,
+ "types": ["ValidationError", "NotFoundError"]
+ }
+ ],
+ "byStatusCode": {
+ "400": 89,
+ "404": 34,
+ "429": 45,
+ "500": 66
+ }
+}
+```
+
+## Detailed Logs
+
+Access complete request/response logs for debugging and auditing.
+
+### Endpoint
+
+`GET /v3/analytics/logs`
+
+### Parameters
+
+Same as usage endpoint, plus optional filters:
+- `type`: Filter by request type (add, search, update, delete)
+- `statusCode`: Filter by HTTP status code
+- `keyId`: Filter by specific API key
+
+### Example Request
+
+<CodeGroup>
+
+```typescript TypeScript
+// Get recent failed requests
+const logs = await fetch('https://api.supermemory.ai/v3/analytics/logs?period=1h&statusCode=500', {
+ headers: {
+ 'Authorization': `Bearer ${SUPERMEMORY_API_KEY}`
+ }
+});
+
+const data = await logs.json();
+```
+
+```python Python
+# Debug specific API key usage
+response = requests.get(
+ 'https://api.supermemory.ai/v3/analytics/logs',
+ params={
+ 'keyId': 'key_abc123',
+ 'period': '24h'
+ },
+ headers={'Authorization': f'Bearer {SUPERMEMORY_API_KEY}'}
+)
+
+logs = response.json()['logs']
+
+```
+
+```bash cURL
+# Get all logs for debugging
+curl -X GET "https://api.supermemory.ai/v3/analytics/logs?period=1h&limit=50" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+```
+
+</CodeGroup>
+
+### Response Schema
+
+```json
+{
+ "logs": [
+ {
+ "id": "req_xyz789",
+ "createdAt": "2024-01-15T14:30:00Z",
+ "type": "search",
+ "statusCode": 200,
+ "duration": 89,
+ "input": {
+ "q": "user query",
+ "limit": 10
+ },
+ "output": {
+ "results": 10,
+ "processingTime": 85
+ }
+ }
+ ],
+ "pagination": {
+ "currentPage": 1,
+ "limit": 20,
+ "totalItems": 500,
+ "totalPages": 25
+ }
+}
+```
+
+## Rate Limits
+
+Analytics endpoints have the following rate limits:
+- 100 requests per minute per organization
+- Maximum time range: 90 days
+- Maximum page size: 100 items
+
+<Warning>
+Analytics data is retained for 90 days. For longer retention, export and store the data in your own systems.
+</Warning>
+
+## Related Resources
+
+- [API Authentication](/essentials/authentication) - Set up API keys
+- [Error Handling](/essentials/errors) - Understanding error codes
+- [Rate Limits](/essentials/rate-limits) - API usage limits
diff --git a/apps/docs/changelog/developer-platform.mdx b/apps/docs/changelog/developer-platform.mdx
new file mode 100644
index 00000000..62d610e8
--- /dev/null
+++ b/apps/docs/changelog/developer-platform.mdx
@@ -0,0 +1,74 @@
+---
+title: "Developer Platform"
+description: "API updates, new endpoints, and SDK releases"
+---
+
+
+API updates, new endpoints, SDK releases, and developer-focused features.
+
+## 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
diff --git a/apps/docs/changelog/overview.mdx b/apps/docs/changelog/overview.mdx
new file mode 100644
index 00000000..f2b67d31
--- /dev/null
+++ b/apps/docs/changelog/overview.mdx
@@ -0,0 +1,34 @@
+---
+title: "Release Notes"
+description: "Follow along with updates across Supermemory's API and Console"
+---
+
+Stay up to date with the latest changes and improvements to Supermemory.
+
+<CardGroup cols={2}>
+ <Card title="Developer Platform" icon="code" href="/changelog/developer-platform">
+ API updates, new endpoints, SDK releases, and developer-focused features.
+
+ **Latest:** Documentation v2.0, AI SDK integration, bulk delete endpoint
+ </Card>
+</CardGroup>
+
+## What's New This Month
+
+**September 2025** has been a big month for Supermemory:
+
+### For Developers
+- **Complete Documentation Rewrite** - Brand new docs with cookbook recipes and production examples
+- **Native AI SDK Integration** - Use Supermemory directly with Vercel AI SDK
+- **Enhanced APIs** - New bulk operations and optimized search endpoints
+
+### For Users
+- **Visual Console Overhaul** - New masonry layout and redesigned preview cards
+- **Better Memory Browsing** - Interactive graph visualization with WebGL performance
+- **Improved Mobile Experience** - Better responsive design across all features
+
+---
+
+<Note>
+Looking for older updates? Check the individual platform pages for complete release history.
+</Note>
diff --git a/apps/docs/connectors/google-drive.mdx b/apps/docs/connectors/google-drive.mdx
new file mode 100644
index 00000000..94bc7809
--- /dev/null
+++ b/apps/docs/connectors/google-drive.mdx
@@ -0,0 +1,435 @@
+---
+title: "Google Drive Connector"
+description: "Connect Google Drive to sync documents into your Supermemory knowledge base"
+icon: "google-drive"
+---
+
+Connect Google Drive to sync documents into your Supermemory knowledge base with OAuth authentication and custom app support.
+
+## Quick Setup
+
+### 1. Create Google Drive Connection
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ import Supermemory from 'supermemory';
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ });
+
+ const connection = await client.connections.create('google-drive', {
+ redirectUrl: 'https://yourapp.com/auth/google-drive/callback',
+ containerTags: ['user-123', 'gdrive-sync'],
+ documentLimit: 3000,
+ metadata: {
+ source: 'google-drive',
+ department: 'engineering'
+ }
+ });
+
+ // Redirect user to Google OAuth
+ window.location.href = connection.authLink;
+ console.log('Auth expires in:', connection.expiresIn);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ from supermemory import Supermemory
+ import os
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+ connection = client.connections.create(
+ 'google-drive',
+ redirect_url='https://yourapp.com/auth/google-drive/callback',
+ container_tags=['user-123', 'gdrive-sync'],
+ document_limit=3000,
+ metadata={
+ 'source': 'google-drive',
+ 'department': 'engineering'
+ }
+ )
+
+ # Redirect user to Google OAuth
+ print(f'Redirect to: {connection.auth_link}')
+ print(f'Expires in: {connection.expires_in}')
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/connections/google-drive" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "redirectUrl": "https://yourapp.com/auth/google-drive/callback",
+ "containerTags": ["user-123", "gdrive-sync"],
+ "documentLimit": 3000,
+ "metadata": {
+ "source": "google-drive",
+ "department": "engineering"
+ }
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### 2. Handle OAuth Callback
+
+After user grants permissions, Google redirects to your callback URL. The connection is automatically established.
+
+### 3. Check Connection Status
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Get connection details
+ const connection = await client.connections.getByTags('google-drive', {
+ containerTags: ['user-123', 'gdrive-sync']
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Get connection details
+ connection = client.connections.get_by_tags(
+ 'google-drive',
+ container_tags=['user-123', 'gdrive-sync']
+ )
+
+ # List synced documents
+ documents = client.connections.list_documents(
+ 'google-drive',
+ container_tags=['user-123', 'gdrive-sync']
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Get connections by provider and tags
+ curl -X POST "https://api.supermemory.ai/v3/connections/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user-123", "gdrive-sync"],
+ "provider": "google-drive"
+ }'
+
+ # List synced documents
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user-123", "gdrive-sync"],
+ "source": "google-drive"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Supported Document Types
+
+Based on the API type definitions, Google Drive documents are identified with these types:
+- `google_doc` - Google Docs
+- `google_slide` - Google Slides
+- `google_sheet` - Google Sheets
+
+## Connection Management
+
+### List All Connections
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // List all connections for specific container tags
+ const connections = await client.connections.list({
+ containerTags: ['user-123']
+ });
+
+ connections.forEach(conn => {
+ console.log(`Provider: ${conn.provider}`);
+ console.log(`ID: ${conn.id}`);
+ console.log(`Email: ${conn.email}`);
+ console.log(`Created: ${conn.createdAt}`);
+ console.log(`Document limit: ${conn.documentLimit}`);
+ console.log('---');
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # List all connections for specific container tags
+ connections = client.connections.list(
+ container_tags=['user-123']
+ )
+
+ for conn in connections:
+ print(f'Provider: {conn.provider}')
+ print(f'ID: {conn.id}')
+ print(f'Email: {conn.email}')
+ print(f'Created: {conn.created_at}')
+ print(f'Document limit: {conn.document_limit}')
+ print('---')
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # List all connections for specific container tags
+ curl -X POST "https://api.supermemory.ai/v3/connections/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user-123"]
+ }'
+
+ # Response example:
+ # [
+ # {
+ # "id": "conn_gd123",
+ # "provider": "google-drive",
+ # "email": "[email protected]",
+ # "createdAt": "2024-01-15T10:30:00.000Z",
+ # "documentLimit": 3000
+ # }
+ # ]
+ ```
+ </Tab>
+</Tabs>
+
+### Delete Connection
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Delete by connection ID
+ const result = await client.connections.deleteByID('connection_id_123');
+ console.log('Deleted connection:', result.id);
+
+ // Delete by provider and container tags
+ const providerResult = await client.connections.deleteByProvider('google-drive', {
+ containerTags: ['user-123']
+ });
+ console.log('Deleted provider connection:', providerResult.id);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Delete by connection ID
+ result = client.connections.delete_by_id('connection_id_123')
+ print(f'Deleted connection: {result.id}')
+
+ # Delete by provider and container tags
+ provider_result = client.connections.delete_by_provider(
+ 'google-drive',
+ container_tags=['user-123']
+ )
+ print(f'Deleted provider connection: {provider_result.id}')
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Delete by connection ID
+ curl -X DELETE "https://api.supermemory.ai/v3/connections/connection_id_123" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+
+ # Response: {"id": "connection_id_123", "provider": "google-drive"}
+
+ # Delete by provider and container tags
+ curl -X DELETE "https://api.supermemory.ai/v3/connections/google-drive" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user-123"]
+ }'
+
+ # Response: {"id": "conn_gd123", "provider": "google-drive"}
+ ```
+ </Tab>
+</Tabs>
+
+<Note>
+Deleting a connection will:
+- Stop all future syncs from Google Drive
+- Remove the OAuth authorization
+- Keep existing synced documents in Supermemory (they won't be deleted)
+</Note>
+
+### Manual Sync
+
+Trigger a manual synchronization:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Trigger sync for Google Drive connections
+ await client.connections.import('google-drive');
+
+ // Trigger sync for specific container tags
+ await client.connections.import('google-drive', {
+ containerTags: ['user-123']
+ });
+
+ console.log('Manual sync initiated');
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Trigger sync for Google Drive connections
+ client.connections.import_('google-drive')
+
+ # Trigger sync for specific container tags
+ client.connections.import_(
+ 'google-drive',
+ container_tags=['user-123']
+ )
+
+ print('Manual sync initiated')
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Trigger sync for all Google Drive connections
+ curl -X POST "https://api.supermemory.ai/v3/connections/google-drive/import" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+
+ # Trigger sync for specific container tags
+ curl -X POST "https://api.supermemory.ai/v3/connections/google-drive/import" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user-123"]
+ }'
+
+ # Response: {"message": "Manual sync initiated", "provider": "google-drive"}
+ ```
+ </Tab>
+</Tabs>
+
+
+
+## Advanced Configuration
+
+### Custom OAuth Application
+
+Configure your own Google OAuth app using the settings API:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Update organization settings with your Google OAuth app
+ await client.settings.update({
+ googleDriveCustomKeyEnabled: true,
+ googleDriveClientId: 'your-google-client-id.googleusercontent.com',
+ googleDriveClientSecret: 'your-google-client-secret'
+ });
+
+ // Get current settings
+ const settings = await client.settings.get();
+ console.log('Google Drive custom key enabled:', settings.googleDriveCustomKeyEnabled);
+ console.log('Client ID configured:', !!settings.googleDriveClientId);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Update organization settings with your Google OAuth app
+ client.settings.update(
+ google_drive_custom_key_enabled=True,
+ google_drive_client_id='your-google-client-id.googleusercontent.com',
+ google_drive_client_secret='your-google-client-secret'
+ )
+
+ # Get current settings
+ settings = client.settings.get()
+ print(f'Google Drive custom key enabled: {settings.google_drive_custom_key_enabled}')
+ print(f'Client ID configured: {bool(settings.google_drive_client_id)}')
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Update organization settings
+ curl -X PATCH "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "googleDriveCustomKeyEnabled": true,
+ "googleDriveClientId": "your-google-client-id.googleusercontent.com",
+ "googleDriveClientSecret": "your-google-client-secret"
+ }'
+
+ # Get current settings
+ curl -X GET "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+ ```
+ </Tab>
+</Tabs>
+
+### Document Filtering
+
+Configure filtering using the settings API:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ await client.settings.update({
+ shouldLLMFilter: true,
+ filterPrompt: "Only sync important business documents",
+ includeItems: {
+ // Your include patterns
+ },
+ excludeItems: {
+ // Your exclude patterns
+ }
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ client.settings.update(
+ should_llm_filter=True,
+ filter_prompt="Only sync important business documents",
+ include_items={
+ # Your include patterns
+ },
+ exclude_items={
+ # Your exclude patterns
+ }
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Configure document filtering
+ curl -X PATCH "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "shouldLLMFilter": true,
+ "filterPrompt": "Only sync important business documents",
+ "includeItems": {
+ "patterns": ["*.pdf", "*.docx"],
+ "folders": ["Important Documents", "Projects"]
+ },
+ "excludeItems": {
+ "patterns": ["*.tmp", "*.backup"],
+ "folders": ["Archive", "Trash"]
+ }
+ }'
+
+ # Response: {
+ # "shouldLLMFilter": true,
+ # "filterPrompt": "Only sync important business documents",
+ # "includeItems": {...},
+ # "excludeItems": {...}
+ # }
+ ```
+ </Tab>
+</Tabs>
+
+<Warning>
+**Important Notes:**
+- OAuth tokens may expire - check `expiresAt` field
+- Document processing happens asynchronously
+- Use container tags consistently for filtering
+- Monitor document status for failed syncs
+</Warning>
diff --git a/apps/docs/connectors/notion.mdx b/apps/docs/connectors/notion.mdx
new file mode 100644
index 00000000..ba315b92
--- /dev/null
+++ b/apps/docs/connectors/notion.mdx
@@ -0,0 +1,429 @@
+---
+title: "Notion Connector"
+description: "Sync Notion pages, databases, and blocks with real-time webhooks and workspace integration"
+icon: "notion"
+---
+Connect Notion workspaces to automatically sync pages, databases, and content blocks into your Supermemory knowledge base. Supports real-time updates, rich formatting, and database properties.
+
+## Quick Setup
+
+### 1. Create Notion Connection
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ import Supermemory from 'supermemory';
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ });
+
+ const connection = await client.connections.create('notion', {
+ redirectUrl: 'https://yourapp.com/auth/notion/callback',
+ containerTags: ['user-123', 'notion-workspace'],
+ documentLimit: 2000,
+ metadata: {
+ source: 'notion',
+ workspaceType: 'team',
+ department: 'product'
+ }
+ });
+
+ // Redirect user to Notion OAuth
+ window.location.href = connection.authLink;
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ from supermemory import Supermemory
+ import os
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+ connection = client.connections.create(
+ 'notion',
+ redirect_url='https://yourapp.com/auth/notion/callback',
+ container_tags=['user-123', 'notion-workspace'],
+ document_limit=2000,
+ metadata={
+ 'source': 'notion',
+ 'workspaceType': 'team',
+ 'department': 'product'
+ }
+ )
+
+ # Redirect user to Notion OAuth
+ print(f'Redirect to: {connection.auth_link}')
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/connections/notion" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "redirectUrl": "https://yourapp.com/auth/notion/callback",
+ "containerTags": ["user-123", "notion-workspace"],
+ "documentLimit": 2000,
+ "metadata": {
+ "source": "notion",
+ "workspaceType": "team",
+ "department": "product"
+ }
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### 2. Handle OAuth Flow
+
+After user grants workspace access, Notion redirects to your callback URL. The connection is automatically established.
+
+### 3. Monitor Sync Progress
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Check connection details
+ const connection = await client.connections.getByTags('notion', {
+ containerTags: ['user-123', 'notion-workspace']
+ });
+
+ console.log('Connected workspace:', connection.email);
+ console.log('Connection created:', connection.createdAt);
+
+ // List synced pages and databases
+ const documents = await client.connections.listDocuments('notion', {
+ containerTags: ['user-123', 'notion-workspace']
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Check connection details
+ connection = client.connections.get_by_tags(
+ 'notion',
+ container_tags=['user-123', 'notion-workspace']
+ )
+
+ print(f'Connected workspace: {connection.email}')
+ print(f'Connection created: {connection.created_at}')
+
+ # List synced pages and databases
+ documents = client.connections.list_documents(
+ 'notion',
+ container_tags=['user-123', 'notion-workspace']
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Get connection details by provider and tags
+ curl -X POST "https://api.supermemory.ai/v3/connections/notion/connection" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123", "notion-workspace"]}'
+
+ # Response includes connection details:
+ # {
+ # "id": "conn_abc123",
+ # "provider": "notion",
+ # "email": "[email protected]",
+ # "createdAt": "2024-01-15T10:00:00Z",
+ # "documentLimit": 2000,
+ # "metadata": {...}
+ # }
+
+ # List synced documents
+ curl -X POST "https://api.supermemory.ai/v3/connections/notion/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123", "notion-workspace"]}'
+
+ # Response: Array of document objects with sync status
+ # [
+ # {"title": "Product Roadmap", "type": "notion_database", "status": "done"},
+ # {"title": "Meeting Notes", "type": "notion_page", "status": "done"}
+ # ]
+ ```
+ </Tab>
+</Tabs>
+
+## Supported Content Types
+
+### Notion Pages
+- **Rich text blocks** with formatting preserved
+- **Nested pages** and hierarchical structure
+- **Embedded content** (images, videos, files)
+- **Code blocks** with syntax highlighting
+- **Callouts and quotes** converted to markdown
+
+### Notion Databases
+- **Database entries** synced as individual documents
+- **Properties** included in metadata
+- **Relations** between database entries
+- **Formulas and rollups** calculated values
+- **Multi-select and select** properties
+
+### Block Types
+
+| Block Type | Processing | Markdown Output |
+|------------|------------|-----------------|
+| **Text** | Formatting preserved | `**bold**`, `*italic*`, `~~strikethrough~~` |
+| **Heading** | Hierarchy maintained | `# H1`, `## H2`, `### H3` |
+| **Code** | Language detected | ````python\ncode here\n```` |
+| **Quote** | Blockquote format | `> quoted text` |
+| **Callout** | Custom formatting | `> 💡 **Note:** callout text` |
+| **List** | Structure preserved | `- item 1\n - nested item` |
+| **Table** | Markdown tables | `| Col 1 | Col 2 |\n|-------|-------|` |
+| **Image** | Referenced with metadata | `![alt text](url)` |
+| **Embed** | Link with context | `[Embedded Content](url)` |
+
+## Delete Connection
+
+Remove a Notion connection when no longer needed:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Delete by connection ID
+ const result = await client.connections.delete('connection_id_123');
+ console.log('Deleted connection:', result.id);
+
+ // Delete by provider and container tags
+ const providerResult = await client.connections.deleteByProvider('notion', {
+ containerTags: ['user-123']
+ });
+ console.log('Deleted Notion connection for user');
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Delete by connection ID
+ result = client.connections.delete('connection_id_123')
+ print(f'Deleted connection: {result.id}')
+
+ # Delete by provider and container tags
+ provider_result = client.connections.delete_by_provider(
+ 'notion',
+ container_tags=['user-123']
+ )
+ print('Deleted Notion connection for user')
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Delete by connection ID
+ curl -X DELETE "https://api.supermemory.ai/v3/connections/connection_id_123" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+
+ # Delete by provider and container tags
+ curl -X DELETE "https://api.supermemory.ai/v3/connections/notion" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123"]}'
+ ```
+ </Tab>
+</Tabs>
+
+<Note>
+Deleting a connection will:
+- Stop all future syncs from Notion
+- Remove the OAuth authorization
+- Keep existing synced documents in Supermemory (they won't be deleted)
+</Note>
+
+## Advanced Configuration
+
+### Custom Notion Integration
+
+For production deployments, create your own Notion integration:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // First, update organization settings with your Notion app credentials
+ await client.settings.update({
+ notionCustomKeyEnabled: true,
+ notionClientId: 'your-notion-client-id',
+ notionClientSecret: 'your-notion-client-secret'
+ });
+
+ // Then create connections using your custom integration
+ const connection = await client.connections.create('notion', {
+ redirectUrl: 'https://yourapp.com/callback',
+ containerTags: ['org-456', 'user-789'],
+ metadata: { customIntegration: true }
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # First, update organization settings with your Notion app credentials
+ client.settings.update(
+ notion_custom_key_enabled=True,
+ notion_client_id='your-notion-client-id',
+ notion_client_secret='your-notion-client-secret'
+ )
+
+ # Then create connections using your custom integration
+ connection = client.connections.create(
+ 'notion',
+ redirect_url='https://yourapp.com/callback',
+ container_tags=['org-456', 'user-789'],
+ metadata={'customIntegration': True}
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Update organization settings
+ curl -X PATCH "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "notionCustomKeyEnabled": true,
+ "notionClientId": "your-notion-client-id",
+ "notionClientSecret": "your-notion-client-secret"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Content Filtering
+
+Control which Notion content gets synced:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Configure intelligent filtering for Notion content
+ await client.settings.update({
+ shouldLLMFilter: true,
+ includeItems: {
+ pageTypes: ['page', 'database'],
+ titlePatterns: ['*Spec*', '*Documentation*', '*Meeting Notes*'],
+ databases: ['Project Tracker', 'Knowledge Base', 'Team Wiki']
+ },
+ excludeItems: {
+ titlePatterns: ['*Draft*', '*Personal*', '*Archive*'],
+ databases: ['Personal Tasks', 'Scratchpad']
+ },
+ filterPrompt: "Sync professional documentation, project specs, meeting notes, and team knowledge. Skip personal notes, drafts, and archived content."
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Configure intelligent filtering for Notion content
+ client.settings.update(
+ should_llm_filter=True,
+ include_items={
+ 'pageTypes': ['page', 'database'],
+ 'titlePatterns': ['*Spec*', '*Documentation*', '*Meeting Notes*'],
+ 'databases': ['Project Tracker', 'Knowledge Base', 'Team Wiki']
+ },
+ exclude_items={
+ 'titlePatterns': ['*Draft*', '*Personal*', '*Archive*'],
+ 'databases': ['Personal Tasks', 'Scratchpad']
+ },
+ filter_prompt="Sync professional documentation, project specs, meeting notes, and team knowledge. Skip personal notes, drafts, and archived content."
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Configure intelligent filtering for Notion content
+ curl -X PATCH "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "shouldLLMFilter": true,
+ "includeItems": {
+ "pageTypes": ["page", "database"],
+ "titlePatterns": ["*Spec*", "*Documentation*", "*Meeting Notes*"],
+ "databases": ["Project Tracker", "Knowledge Base", "Team Wiki"]
+ },
+ "excludeItems": {
+ "titlePatterns": ["*Draft*", "*Personal*", "*Archive*"],
+ "databases": ["Personal Tasks", "Scratchpad"]
+ },
+ "filterPrompt": "Sync professional documentation, project specs, meeting notes, and team knowledge. Skip personal notes, drafts, and archived content."
+ }'
+
+ # Response:
+ # {
+ # "success": true,
+ # "message": "Settings updated successfully"
+ # }
+ ```
+ </Tab>
+</Tabs>
+
+## Workspace Permissions
+
+Notion connector respects workspace permissions:
+
+| Permission Level | Sync Behavior |
+|-----------------|---------------|
+| **Admin** | Full workspace access |
+| **Member** | Pages with read access |
+| **Guest** | Only shared pages |
+| **No Access** | Removed from index |
+
+
+## Database Integration
+
+### Database Properties
+
+Notion database properties are mapped to metadata:
+
+```typescript
+// Example: Project database with properties
+const documents = await client.connections.listDocuments('notion', {
+ containerTags: ['user-123']
+});
+
+// Find database entries
+const projectEntries = documents.filter(doc =>
+ doc.metadata?.database === 'Projects'
+);
+
+// Database properties become searchable metadata
+const projectWithStatus = await client.search.documents({
+ q: "machine learning project",
+ containerTags: ['user-123'],
+ filters: JSON.stringify({
+ AND: [
+ { key: "status", value: "In Progress", negate: false },
+ { key: "priority", value: "High", negate: false }
+ ]
+ })
+});
+```
+
+### Optimization Strategies
+
+1. **Set appropriate document limits** based on workspace size
+2. **Use targeted container tags** for efficient organization
+3. **Monitor database sync performance** for large datasets
+4. **Implement content filtering** to sync only relevant pages
+5. **Handle webhook delays** gracefully in your application
+
+<Callout type="info">
+**Notion-Specific Benefits:**
+- Real-time sync via webhooks for instant updates
+- Rich formatting and block structure preserved
+- Database properties become searchable metadata
+- Hierarchical page structure maintained
+- Collaborative workspace support
+</Callout>
+
+<Warning>
+**Important Limitations:**
+- Complex block formatting may be simplified in markdown conversion
+- Large databases can take significant time to sync initially
+- Workspace permissions affect which content is accessible
+- Notion API rate limits may affect sync speed for large workspaces
+- Embedded files and images are referenced, not stored directly
+</Warning>
diff --git a/apps/docs/connectors/onedrive.mdx b/apps/docs/connectors/onedrive.mdx
new file mode 100644
index 00000000..f9449520
--- /dev/null
+++ b/apps/docs/connectors/onedrive.mdx
@@ -0,0 +1,390 @@
+---
+title: "OneDrive Connector"
+description: "Sync Microsoft Office documents from OneDrive with scheduled synchronization and business account support"
+icon: "microsoft"
+---
+
+
+Connect OneDrive to automatically sync Word documents, Excel spreadsheets, and PowerPoint presentations into your Supermemory knowledge base. Supports both personal and business accounts with scheduled synchronization.
+
+## Quick Setup
+
+### 1. Create OneDrive Connection
+
+<CodeGroup>
+
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+});
+
+const connection = await client.connections.create('onedrive', {
+ redirectUrl: 'https://yourapp.com/auth/onedrive/callback',
+ containerTags: ['user-123', 'onedrive-sync'],
+ documentLimit: 1500,
+ metadata: {
+ source: 'onedrive',
+ accountType: 'business',
+ department: 'marketing'
+ }
+});
+
+// Redirect user to Microsoft OAuth
+window.location.href = connection.authLink;
+// Output: Redirects to OAuth provider
+// Output: Redirects to https://login.microsoftonline.com/oauth2/authorize?...
+```
+
+```python Python
+from supermemory import Supermemory
+import os
+
+client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+connection = client.connections.create(
+ 'onedrive',
+ redirect_url='https://yourapp.com/auth/onedrive/callback',
+ container_tags=['user-123', 'onedrive-sync'],
+ document_limit=1500,
+ metadata={
+ 'source': 'onedrive',
+ 'accountType': 'business',
+ 'department': 'marketing'
+ }
+)
+
+# Redirect user to Microsoft OAuth
+print(f'Redirect to: {connection.auth_link}')
+# Output: Redirect to: https://oauth.provider.com/...
+# Output: Redirect to: https://login.microsoftonline.com/oauth2/authorize?...
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/connections/onedrive" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "redirectUrl": "https://yourapp.com/auth/onedrive/callback",
+ "containerTags": ["user-123", "onedrive-sync"],
+ "documentLimit": 1500,
+ "metadata": {
+ "source": "onedrive",
+ "accountType": "business",
+ "department": "marketing"
+ }
+ }'
+
+# Response: {
+# "authLink": "https://login.microsoftonline.com/oauth2/authorize?...",
+# "expiresIn": "1 hour",
+# "id": "conn_od123"
+# }
+```
+
+</CodeGroup>
+
+### 2. Handle Microsoft OAuth
+
+After user grants permissions, Microsoft redirects to your callback URL. The connection is automatically established and initial sync begins.
+
+### 3. Monitor Sync Status
+
+<CodeGroup>
+ ```typescript Typescript
+ // Check connection details
+ const connection = await client.connections.getByTags('onedrive', {
+ containerTags: ['user-123', 'onedrive-sync']
+ });
+
+
+ // List synced Office documents
+ const documents = await client.connections.listDocuments('onedrive', {
+ containerTags: ['user-123', 'onedrive-sync']
+ });
+ ```
+ ```python Python
+ # Check connection details
+ connection = client.connections.get_by_tags(
+ 'onedrive',
+ container_tags=['user-123', 'onedrive-sync']
+ )
+
+ # List synced Office documents
+ documents = client.connections.list_documents(
+ 'onedrive',
+ container_tags=['user-123', 'onedrive-sync']
+ )
+ ```
+ ```bash cURL
+ # Get connections by provider and tags
+ curl -X POST "https://api.supermemory.ai/v3/connections/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user-123", "onedrive-sync"],
+ "provider": "onedrive"
+ }'
+
+ # List synced Office documents
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user-123", "onedrive-sync"],
+ "source": "onedrive"
+ }'
+ ```
+</CodeGroup>
+
+## Supported Document Types
+
+### Microsoft Word Documents
+- **Rich text formatting** converted to markdown
+- **Headers and styles** preserved as markdown hierarchy
+- **Images and charts** extracted and referenced
+- **Tables** converted to markdown tables
+
+### Excel Spreadsheets
+- **Worksheet data** converted to structured markdown
+- **Multiple sheets** processed separately
+- **Charts and graphs** extracted as images
+- **Formulas** converted to calculated values
+- **Cell formatting** simplified in markdown
+
+### PowerPoint Presentations
+- **Slide content** converted to structured markdown
+- **Speaker notes** included when present
+- **Images and media** extracted and referenced
+- **Embedded objects** processed when possible
+
+## Sync Mechanism
+
+Webhooks lead to real-time syncing of changes in documents. You may also manually trigger a sync.
+
+### Manual Sync Trigger
+
+<CodeGroup>
+ ```typescript Typescript
+ // Trigger immediate sync for all OneDrive connections
+ await client.connections.import('onedrive');
+
+ // Trigger sync for specific user
+ await client.connections.import('onedrive', {
+ containerTags: ['user-123']
+ });
+
+ console.log('Manual sync initiated - documents will update within 5-10 minutes');
+ ```
+ ```python Python
+ # Trigger immediate sync for all OneDrive connections
+ client.connections.import_('onedrive')
+
+ # Trigger sync for specific user
+ client.connections.import_(
+ 'onedrive',
+ container_tags=['user-123']
+ )
+
+ print('Manual sync initiated - documents will update within 5-10 minutes')
+ ```
+ ```bash cURL
+ # Trigger manual sync
+ curl -X POST "https://api.supermemory.ai/v3/connections/onedrive/import" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123"]}'
+ ```
+</CodeGroup>
+
+## Delete Connection
+
+Remove a OneDrive connection when no longer needed:
+
+<CodeGroup>
+
+```typescript Typescript
+// Delete by connection ID
+const result = await client.connections.delete('connection_id_123');
+console.log('Deleted connection:', result.id);
+
+// Delete by provider and container tags
+const providerResult = await client.connections.deleteByProvider('onedrive', {
+ containerTags: ['user-123']
+});
+console.log('Deleted OneDrive connection for user');
+```
+
+```python Python
+# Delete by connection ID
+result = client.connections.delete('connection_id_123')
+print(f'Deleted connection: {result.id}')
+
+# Delete by provider and container tags
+provider_result = client.connections.delete_by_provider(
+ 'onedrive',
+ container_tags=['user-123']
+)
+print('Deleted OneDrive connection for user')
+```
+
+```bash cURL
+# Delete by connection ID
+curl -X DELETE "https://api.supermemory.ai/v3/connections/connection_id_123" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+
+# Delete by provider and container tags
+curl -X DELETE "https://api.supermemory.ai/v3/connections/onedrive" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123"]}'
+```
+
+</CodeGroup>
+
+<Note>
+Deleting a connection will:
+- Stop all future syncs from OneDrive
+- Remove the OAuth authorization
+- Keep existing synced documents in Supermemory (they won't be deleted)
+</Note>
+
+## Advanced Configuration
+
+### Custom Microsoft App
+
+For production deployments, configure your own Microsoft application:
+
+<CodeGroup>
+ ```typescript Typescript
+ // First, update organization settings with your Microsoft app credentials
+ await client.settings.update({
+ onedriveCustomKeyEnabled: true,
+ onedriveClientId: 'your-microsoft-app-id',
+ onedriveClientSecret: 'your-microsoft-app-secret'
+ });
+
+ // Then create connections using your custom app
+ const connection = await client.connections.create('onedrive', {
+ redirectUrl: 'https://yourapp.com/callback',
+ containerTags: ['org-456', 'user-789'],
+ metadata: { customApp: true }
+ });
+ ```
+ ```python Python
+ # First, update organization settings with your Microsoft app credentials
+ client.settings.update(
+ onedrive_custom_key_enabled=True,
+ onedrive_client_id='your-microsoft-app-id',
+ onedrive_client_secret='your-microsoft-app-secret'
+ )
+
+ # Then create connections using your custom app
+ connection = client.connections.create(
+ 'onedrive',
+ redirect_url='https://yourapp.com/callback',
+ container_tags=['org-456', 'user-789'],
+ metadata={'customApp': True}
+ )
+ ```
+ ```bash cURL
+ # Update organization settings
+ curl -X PATCH "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "onedriveCustomKeyEnabled": true,
+ "onedriveClientId": "your-microsoft-app-id",
+ "onedriveClientSecret": "your-microsoft-app-secret"
+ }'
+ ```
+</CodeGroup>
+
+### Document Filtering
+
+Control which OneDrive documents get synced:
+
+<CodeGroup>
+ ```typescript Typescript
+ // Configure filtering for Office documents
+ await client.settings.update({
+ shouldLLMFilter: true,
+ includeItems: {
+ fileTypes: ['docx', 'xlsx', 'pptx'],
+ folderNames: ['Projects', 'Documentation', 'Reports'],
+ titlePatterns: ['*Proposal*', '*Specification*', '*Analysis*']
+ },
+ excludeItems: {
+ folderNames: ['Archive', 'Templates', 'Personal'],
+ titlePatterns: ['*Draft*', '*Old*', '*Backup*', '*~$*']
+ },
+ filterPrompt: "Sync professional business documents, project files, reports, and presentations. Skip personal files, drafts, temporary files, and archived content."
+ });
+ ```
+ ```python Python
+ # Configure filtering for Office documents
+ client.settings.update(
+ should_llm_filter=True,
+ include_items={
+ 'fileTypes': ['docx', 'xlsx', 'pptx'],
+ 'folderNames': ['Projects', 'Documentation', 'Reports'],
+ 'titlePatterns': ['*Proposal*', '*Specification*', '*Analysis*']
+ },
+ exclude_items={
+ 'folderNames': ['Archive', 'Templates', 'Personal'],
+ 'titlePatterns': ['*Draft*', '*Old*', '*Backup*', '*~$*']
+ },
+ filter_prompt="Sync professional business documents, project files, reports, and presentations. Skip personal files, drafts, temporary files, and archived content."
+ )
+ ```
+ ```bash cURL
+ # Configure filtering for Office documents
+ curl -X PATCH "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "shouldLLMFilter": true,
+ "includeItems": {
+ "fileTypes": ["docx", "xlsx", "pptx"],
+ "folderNames": ["Projects", "Documentation", "Reports"],
+ "titlePatterns": ["*Proposal*", "*Specification*", "*Analysis*"]
+ },
+ "excludeItems": {
+ "folderNames": ["Archive", "Templates", "Personal"],
+ "titlePatterns": ["*Draft*", "*Old*", "*Backup*", "*~$*"]
+ },
+ "filterPrompt": "Sync professional business documents, project files, reports, and presentations. Skip personal files, drafts, temporary files, and archived content."
+ }'
+
+ # Response: {
+ # "shouldLLMFilter": true,
+ # "includeItems": {...},
+ # "excludeItems": {...},
+ # "filterPrompt": "..."
+ # }
+ ```
+</CodeGroup>
+
+### Optimization Tips
+
+1. **Set realistic document limits** based on storage and usage
+2. **Use targeted filtering** to sync only business-critical documents
+3. **Monitor sync health** regularly due to scheduled nature
+4. **Trigger manual syncs** when immediate updates are needed
+5. **Consider account type** when setting expectations
+
+<Callout type="info">
+**OneDrive-Specific Benefits:**
+- Supports both personal and business Microsoft accounts
+- Processes all major Office document formats
+- Preserves document structure and formatting
+- Handles large enterprise document collections
+</Callout>
+
+<Warning>
+**Important Limitations:**
+- Large Office documents may take significant time to process
+- Complex Excel formulas may not convert perfectly to markdown
+- Microsoft API rate limits may slow sync for large accounts
+</Warning>
diff --git a/apps/docs/connectors/overview.mdx b/apps/docs/connectors/overview.mdx
new file mode 100644
index 00000000..6d12d510
--- /dev/null
+++ b/apps/docs/connectors/overview.mdx
@@ -0,0 +1,306 @@
+---
+title: "Connectors Overview"
+description: "Integrate Google Drive, Notion, and OneDrive to automatically sync documents into your knowledge base"
+sidebarTitle: "Overview"
+---
+
+Connect external platforms to automatically sync documents into Supermemory. Supported connectors include Google Drive, Notion, and OneDrive with real-time synchronization and intelligent content processing.
+
+## Supported Connectors
+
+<CardGroup cols={3}>
+ <Card title="Google Drive" icon="google-drive" href="/connectors/google-drive">
+ **Google Docs, Slides, Sheets**
+
+ Real-time sync via webhooks. Supports shared drives, nested folders, and collaborative documents.
+ </Card>
+
+ <Card title="Notion" icon="notion" href="/connectors/notion">
+ **Pages, Databases, Blocks**
+
+ Instant sync of workspace content. Handles rich formatting, embeds, and database properties.
+ </Card>
+
+ <Card title="OneDrive" icon="microsoft" href="/connectors/onedrive">
+ **Word, Excel, PowerPoint**
+
+ Scheduled sync every 4 hours. Supports personal and business accounts with file versioning.
+ </Card>
+</CardGroup>
+
+## Quick Start
+
+### 1. Create Connection
+
+<CodeGroup>
+
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+});
+
+const connection = await client.connections.create('notion', {
+ redirectUrl: 'https://yourapp.com/callback',
+ containerTags: ['user-123', 'workspace-alpha'],
+ documentLimit: 5000,
+ metadata: { department: 'sales' }
+});
+
+// Redirect user to complete OAuth
+console.log('Auth URL:', connection.authLink);
+console.log('Expires in:', connection.expiresIn);
+// Output: Auth URL: https://api.notion.com/v1/oauth/authorize?...
+// Output: Expires in: 1 hour
+```
+
+```python Python
+from supermemory import Supermemory
+import os
+
+client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+connection = client.connections.create(
+ 'notion',
+ redirect_url='https://yourapp.com/callback',
+ container_tags=['user-123', 'workspace-alpha'],
+ document_limit=5000,
+ metadata={'department': 'sales'}
+)
+
+# Redirect user to complete OAuth
+print(f'Auth URL: {connection.auth_link}')
+print(f'Expires in: {connection.expires_in}')
+# Output: Auth URL: https://api.notion.com/v1/oauth/authorize?...
+# Output: Expires in: 1 hour
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/connections/notion" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "redirectUrl": "https://yourapp.com/callback",
+ "containerTags": ["user-123", "workspace-alpha"],
+ "documentLimit": 5000,
+ "metadata": {"department": "sales"}
+ }'
+
+# Response: {
+# "authLink": "https://api.notion.com/v1/oauth/authorize?...",
+# "expiresIn": "1 hour",
+# "id": "conn_abc123",
+# "redirectsTo": "https://yourapp.com/callback"
+# }
+```
+
+</CodeGroup>
+
+### 2. Handle OAuth Callback
+
+After user completes OAuth, the connection is automatically established and sync begins.
+
+### 3. Monitor Sync Status
+
+<CodeGroup>
+
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+});
+
+// List all connections using SDK
+const connections = await client.connections.list({
+ containerTags: ['user-123', 'workspace-alpha']
+});
+
+connections.forEach(conn => {
+ console.log('Connection:', conn.id);
+ console.log('Provider:', conn.provider);
+ console.log('Email:', conn.email);
+ console.log('Created:', conn.createdAt);
+});
+
+// List synced documents (memories) using SDK
+const memories = await client.memories.list({
+ containerTags: ['user-123', 'workspace-alpha']
+});
+
+console.log(`Synced ${memories.memories.length} documents`);
+// Output: Synced 45 documents
+```
+
+```python Python
+from supermemory import Supermemory
+import os
+
+client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+# List all connections using SDK
+connections = client.connections.list(
+ container_tags=['user-123', 'workspace-alpha']
+)
+
+for conn in connections:
+ print(f'Connection: {conn.id}')
+ print(f'Provider: {conn.provider}')
+ print(f'Email: {conn.email}')
+ print(f'Created: {conn.created_at}')
+
+# List synced documents (memories) using SDK
+memories = client.memories.list(container_tags=['user-123', 'workspace-alpha'])
+
+print(f'Synced {len(memories.memories)} documents')
+# Output: Synced 45 documents
+```
+
+```bash cURL
+# List all connections
+curl -X POST "https://api.supermemory.ai/v3/connections/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123", "workspace-alpha"]}'
+
+# Response: [{"id": "conn_abc", "provider": "notion", "email": "[email protected]", ...}]
+
+# List synced documents
+curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123", "workspace-alpha"]}'
+
+# Response: {"results": [...], "totalCount": 45}
+```
+
+</CodeGroup>
+
+## How Connectors Work
+
+### Authentication Flow
+
+1. **Create Connection**: Call `/v3/connections/{provider}` to get OAuth URL
+2. **User Authorization**: Redirect user to complete OAuth flow
+3. **Automatic Setup**: Connection established, sync begins immediately
+4. **Continuous Sync**: Real-time updates via webhooks + scheduled sync every 4 hours
+
+### Document Processing Pipeline
+
+```mermaid
+graph TD
+ A[External Document] --> B[Webhook/Schedule Trigger]
+ B --> C[Content Extraction]
+ C --> D[Chunking & Embedding]
+ D --> E[Index in Supermemory]
+
+ E --> F[Searchable Memory]
+ E --> G[Document Search]
+```
+
+### Sync Mechanisms
+
+| Provider | Real-time Sync | Scheduled Sync | Manual Sync |
+|----------|---------------|----------------|-------------|
+| **Google Drive** | ✅ Webhooks (7-day expiry) | ✅ Every 4 hours | ✅ On-demand |
+| **Notion** | ✅ Webhooks | ✅ Every 4 hours | ✅ On-demand |
+| **OneDrive** | ✅ Webhooks (30-day expiry) | ✅ Every 4 hours | ✅ On-demand |
+
+
+## Connection Management
+
+### List All Connections
+
+<CodeGroup>
+
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+});
+
+const connections = await client.connections.list({
+ containerTags: ['org-123']
+});
+```
+
+```python Python
+from supermemory import Supermemory
+import os
+
+client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+connections = client.connections.list(container_tags=['org-123'])
+
+for conn in connections:
+ print(f"{conn.provider}: {conn.email} ({conn.id})")
+ print(f"Documents: {conn.document_limit or 'unlimited'}")
+ print(f"Expires: {conn.expires_at or 'never'}")
+# Output: notion: [email protected] (conn_abc123)
+# Output: Documents: 5000
+# Output: Expires: never
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/connections/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["org-123"]}'
+
+# Response: [
+# {
+# "id": "conn_abc123",
+# "provider": "notion",
+# "email": "[email protected]",
+# "documentLimit": 5000,
+# "createdAt": "2024-01-15T10:30:00.000Z"
+# }
+# ]
+```
+
+</CodeGroup>
+
+### Delete Connections
+
+<CodeGroup>
+
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+});
+
+// Delete by connection ID using SDK
+const result = await client.connections.delete(connectionId);
+
+console.log('Deleted:', result.id, result.provider);
+// Output: Deleted: conn_abc123 notion
+```
+
+```python Python
+from supermemory import Supermemory
+import os
+
+client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+# Delete by connection ID using SDK
+result = client.connections.delete(connection_id)
+
+print(f"Deleted: {result.id} {result.provider}")
+# Output: Deleted: conn_abc123 notion
+```
+
+```bash cURL
+curl -X DELETE "https://api.supermemory.ai/v3/connections/conn_abc123" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+
+# Response: {
+# "id": "conn_abc123",
+# "provider": "notion"
+# }
+```
+
+</CodeGroup>
diff --git a/apps/docs/connectors/troubleshooting.mdx b/apps/docs/connectors/troubleshooting.mdx
new file mode 100644
index 00000000..847a7987
--- /dev/null
+++ b/apps/docs/connectors/troubleshooting.mdx
@@ -0,0 +1,190 @@
+---
+title: "Connector Troubleshooting"
+description: "Diagnose and resolve common issues with Google Drive, Notion, and OneDrive connectors"
+---
+
+Quick guide to resolve common connector issues with authentication, syncing, and permissions.
+
+## Quick Health Check
+
+Check if your connectors are working properly:
+
+<CodeGroup>
+
+```typescript TypeScript
+const connections = await client.connections.list({
+ containerTags: ['user-123']
+});
+
+connections.forEach(conn => {
+ console.log(`${conn.provider}: ${conn.email} - Connected ${conn.createdAt}`);
+});
+
+// Check for stuck documents
+const documents = await client.connections.listDocuments('notion', {
+ containerTags: ['user-123']
+});
+
+const failed = documents.filter(doc => doc.status === 'failed');
+if (failed.length > 0) {
+ console.log(`⚠️ ${failed.length} documents failed to sync`);
+}
+```
+
+```python Python
+connections = client.connections.list(container_tags=['user-123'])
+
+for conn in connections:
+ print(f"{conn.provider}: {conn.email} - Connected {conn.created_at}")
+
+# Check for stuck documents
+documents = client.connections.list_documents(
+ 'notion',
+ container_tags=['user-123']
+)
+
+failed = [doc for doc in documents if doc.status == 'failed']
+if failed:
+ print(f"⚠️ {len(failed)} documents failed to sync")
+```
+
+```bash cURL
+# List all connections
+curl -X POST "https://api.supermemory.ai/v3/connections/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123"]}'
+
+# Check document status
+curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user-123"], "source": "notion"}'
+```
+
+</CodeGroup>
+
+## Common Issues
+
+### OAuth Callback Fails
+
+**Problem:** "Invalid redirect URI" error after user grants permissions
+
+**Solution:** Ensure your redirect URL matches EXACTLY what's configured in your OAuth app:
+
+```typescript
+// correct - exact match with OAuth app settings
+const connection = await client.connections.create('notion', {
+ redirectUrl: 'https://yourapp.com/auth/notion/callback',
+ containerTags: ['user-123']
+});
+
+// Wrong - URL doesn't match
+// redirectUrl: 'https://yourapp.com/callback'
+```
+
+**Prevention:**
+- Use HTTPS for production URLs
+- Copy the exact URL from your OAuth app settings
+- Test the flow in development first
+
+### Documents Not Syncing
+
+**Problem:** Documents stuck in "queued" or "extracting" status for over 30 minutes
+
+**Solution:** Trigger a manual sync:
+
+```typescript
+// Force sync for stuck documents
+await client.connections.import('notion', {
+ containerTags: ['user-123']
+});
+```
+
+If documents consistently fail:
+- Check if files are over 50MB (may timeout)
+- Verify you have permission to access the documents
+- Ensure the document type is supported
+
+### Permission Denied Errors
+
+**Problem:** Some documents show "permission denied" or aren't syncing
+
+**Solution:** Re-authenticate with proper permissions:
+
+```typescript
+// Delete and recreate connection
+await client.connections.deleteByProvider('google-drive', {
+ containerTags: ['user-123']
+});
+
+const newConnection = await client.connections.create('google-drive', {
+ redirectUrl: 'https://yourapp.com/callback',
+ containerTags: ['user-123']
+});
+
+// User must re-authenticate
+window.location.href = newConnection.authLink;
+```
+
+### Sync Takes Too Long
+
+**Problem:** Hundreds of documents taking hours to sync
+
+**Solution:** Set reasonable document limits:
+
+```typescript
+const connection = await client.connections.create('onedrive', {
+ redirectUrl: 'https://yourapp.com/callback',
+ containerTags: ['user-123'],
+ documentLimit: 500 // Start with fewer documents
+});
+```
+
+## Provider-Specific Issues
+
+### Google Drive
+
+**Shared Drive Issues**
+
+Shared drives require special permissions. Make sure:
+- User has access to the shared drive
+- OAuth app has drive.readonly scope
+- User is a member of the shared drive
+
+### Notion
+
+**Database Not Syncing**
+
+Notion databases need explicit permission. If databases aren't syncing:
+
+1. Go to Notion workspace settings
+2. Find your integration under "Connections"
+3. Click on the integration
+4. Select specific pages/databases to share
+5. Re-sync after granting access
+
+**Workspace Access**
+
+For full workspace access, a workspace admin must:
+1. Approve the integration
+2. Grant access to all pages
+3. Enable "Read content" permission
+
+### OneDrive
+
+**Business vs Personal Accounts**
+
+Business accounts may have additional restrictions:
+- Admin consent might be required
+- Some SharePoint sites may be restricted
+- Compliance policies may block certain files
+
+
+## Best Practices
+
+1. **Set reasonable document limits** - Start with 500-1000 documents
+2. **Use descriptive container tags** - Makes debugging easier
+3. **Monitor failed documents** - Check weekly for sync issues
+4. **Handle rate limits gracefully** - Implement exponential backoff
+5. **Test OAuth in development** - Ensure redirect URLs work before production
diff --git a/apps/docs/cookbook/ai-sdk-integration.mdx b/apps/docs/cookbook/ai-sdk-integration.mdx
new file mode 100644
index 00000000..1bf217af
--- /dev/null
+++ b/apps/docs/cookbook/ai-sdk-integration.mdx
@@ -0,0 +1,424 @@
+---
+title: "AI SDK Integration"
+description: "Complete examples showing how to use Supermemory with Vercel AI SDK for building intelligent applications"
+---
+
+This page provides comprehensive examples of using Supermemory with the Vercel AI SDK, covering both Memory Tools and Infinite Chat approaches.
+
+## Personal Assistant with Memory Tools
+
+Build an AI assistant that remembers user preferences and past interactions:
+
+<CodeGroup>
+
+```typescript Next.js API Route
+import { streamText } from 'ai'
+import { createAnthropic } from '@ai-sdk/anthropic'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+const anthropic = createAnthropic({
+ apiKey: process.env.ANTHROPIC_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages } = await request.json()
+
+ const result = await streamText({
+ model: anthropic('claude-3-sonnet-20240229'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!),
+ system: `You are a helpful personal assistant. When users share information about themselves,
+ remember it using the addMemory tool. When they ask questions, search your memories to provide
+ personalized responses. Always be proactive about remembering important details.`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+```typescript Client Component
+'use client'
+
+import { useChat } from 'ai/react'
+
+export default function PersonalAssistant() {
+ const { messages, input, handleInputChange, handleSubmit } = useChat()
+
+ return (
+ <div className="flex flex-col h-screen max-w-2xl mx-auto p-4">
+ <div className="flex-1 overflow-y-auto space-y-4">
+ {messages.map((message) => (
+ <div
+ key={message.id}
+ className={`p-4 rounded-lg ${
+ message.role === 'user' ? 'bg-blue-100 ml-auto' : 'bg-gray-100'
+ }`}
+ >
+ <p>{message.content}</p>
+ </div>
+ ))}
+ </div>
+
+ <form onSubmit={handleSubmit} className="mt-4">
+ <input
+ value={input}
+ onChange={handleInputChange}
+ placeholder="Tell me about yourself or ask me anything..."
+ className="w-full p-2 border rounded"
+ />
+ </form>
+ </div>
+ )
+}
+```
+
+</CodeGroup>
+
+**Example conversation:**
+- User: "I'm allergic to peanuts and I love Italian food"
+- AI: *Uses addMemory tool* "I've remembered that you're allergic to peanuts and love Italian food!"
+- User: "Suggest a restaurant for dinner"
+- AI: *Uses searchMemories tool* "Based on what I know about you, I'd recommend an Italian restaurant that's peanut-free..."
+
+## Customer Support with Context
+
+Build a customer support system that remembers customer history:
+
+```typescript
+import { streamText } from 'ai'
+import { createOpenAI } from '@ai-sdk/openai'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages, customerId } = await request.json()
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-user-id': customerId,
+ 'x-sm-conversation-id': 'customer-support'
+ }
+ }),
+ system: `You are a customer support agent. Before responding to any query:
+ 1. Search for the customer's previous interactions and issues
+ 2. Remember any new information shared in this conversation
+ 3. Provide personalized help based on their history
+ 4. Always be empathetic and solution-focused`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+## Infinite Chat for Documentation
+
+Create a documentation assistant with unlimited context:
+
+<CodeGroup>
+
+```typescript Documentation Chat
+import { streamText } from 'ai'
+
+const infiniteChat = createOpenAI({
+ baseUrl: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ apiKey: 'your-provider-api-key',
+ headers: {
+ 'x-supermemory-api-key': 'supermemory-api-key',
+ 'x-sm-conversation-id': 'conversation-id'
+ }
+})
+
+export async function POST(request: Request) {
+ const { messages } = await request.json()
+
+ const result = await streamText({
+ model: infiniteChat('gpt-4-turbo'),
+ messages,
+ system: `You are a documentation assistant. You have access to all previous
+ conversations and can reference earlier discussions. Help users understand
+ the documentation by building on previous context.`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+```typescript Upload Documentation
+// Separate endpoint to upload documentation to memory
+import { addMemory } from '@supermemory/tools'
+
+export async function POST(request: Request) {
+ const { content, title, url } = await request.json()
+
+ const memory = await addMemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!,
+ content,
+ title,
+ url,
+ headers: {
+ 'x-sm-conversation-id': 'documentation'
+ }
+ })
+
+ return Response.json({ success: true, memory })
+}
+```
+
+</CodeGroup>
+
+## Multi-User Learning Assistant
+
+Build an assistant that learns from multiple users but keeps data separate:
+
+```typescript
+import { streamText } from 'ai'
+import { createAnthropic } from '@ai-sdk/anthropic'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+const anthropic = createAnthropic({
+ apiKey: process.env.ANTHROPIC_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages, userId, courseId } = await request.json()
+
+ const result = await streamText({
+ model: anthropic('claude-3-haiku-20240307'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-user-id': userId,
+ 'x-sm-conversation-id': `course-${courseId}`
+ }
+ }),
+ system: `You are a learning assistant. Help students with their coursework by:
+ 1. Remembering their learning progress and struggles
+ 2. Searching for relevant information from their past sessions
+ 3. Providing personalized explanations based on their learning style
+ 4. Tracking topics they've mastered vs topics they need more help with`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+## Research Assistant with File Processing
+
+Combine file upload with memory tools for research assistance:
+
+<CodeGroup>
+
+```typescript API Route
+import { streamText } from 'ai'
+import { createOpenAI } from '@ai-sdk/openai'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages, projectId } = await request.json()
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-conversation-id': projectId
+ }
+ }),
+ system: `You are a research assistant. You can:
+ 1. Search through uploaded research papers and documents
+ 2. Remember key findings and insights from conversations
+ 3. Help synthesize information across multiple sources
+ 4. Track research progress and important discoveries`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+```typescript File Upload Handler
+import { addMemory } from '@supermemory/tools'
+
+export async function POST(request: Request) {
+ const formData = await request.formData()
+ const file = formData.get('file') as File
+ const projectId = formData.get('projectId') as string
+
+ // Upload file and add to memory
+ const memory = await addMemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!,
+ content: file, // Supermemory handles file processing
+ title: file.name,
+ headers: {
+ 'x-sm-conversation-id': projectId
+ }
+ })
+
+ return Response.json({
+ success: true,
+ message: "Document uploaded and processed for research",
+ memoryId: memory.id
+ })
+}
+```
+
+</CodeGroup>
+
+## Code Assistant with Project Memory
+
+Create a coding assistant that remembers your codebase and preferences:
+
+```typescript
+import { streamText } from 'ai'
+import { createAnthropic } from '@ai-sdk/anthropic'
+import {
+ supermemoryTools,
+ searchMemoriesTool,
+ addMemoryTool
+} from '@supermemory/tools/ai-sdk'
+
+const anthropic = createAnthropic({
+ apiKey: process.env.ANTHROPIC_API_KEY!
+})
+
+export async function POST(request: Request) {
+ const { messages, repositoryId } = await request.json()
+
+ const result = await streamText({
+ model: anthropic('claude-3-sonnet-20240229'),
+ messages,
+ tools: {
+ // Use individual tools for more control
+ searchMemories: searchMemoriesTool(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ }
+ }),
+ addMemory: addMemoryTool(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ }
+ }),
+ // Add custom tools
+ executeCode: {
+ description: 'Execute code in a sandbox environment',
+ parameters: z.object({
+ code: z.string(),
+ language: z.string()
+ }),
+ execute: async ({ code, language }) => {
+ // Your code execution logic
+ return { result: "Code executed successfully" }
+ }
+ }
+ },
+ system: `You are a coding assistant with memory. You can:
+ 1. Remember coding patterns and preferences from past conversations
+ 2. Search through previous code examples and solutions
+ 3. Track project architecture and design decisions
+ 4. Learn from debugging sessions and common issues`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+## Advanced: Custom Tool Integration
+
+Combine Supermemory tools with your own custom tools:
+
+```typescript
+import { streamText } from 'ai'
+import { createOpenAI } from '@ai-sdk/openai'
+import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+import { z } from 'zod'
+
+const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+})
+
+// Custom tool for calendar integration
+const calendarTool = {
+ description: 'Create calendar events',
+ parameters: z.object({
+ title: z.string(),
+ date: z.string(),
+ duration: z.number()
+ }),
+ execute: async ({ title, date, duration }) => {
+ // Your calendar API integration
+ return { eventId: "cal_123", message: "Event created" }
+ }
+}
+
+export async function POST(request: Request) {
+ const { messages } = await request.json()
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ tools: {
+ // Spread Supermemory tools
+ ...supermemoryTools(process.env.SUPERMEMORY_API_KEY!),
+ // Add custom tools
+ createEvent: calendarTool,
+ },
+ system: `You are a personal assistant that can remember information and
+ manage calendars. When users mention events or appointments:
+ 1. Remember the details using addMemory
+ 2. Create calendar events using createEvent
+ 3. Search for conflicts using searchMemories`
+ })
+
+ return result.toAIStreamResponse()
+}
+```
+
+## Environment Setup
+
+For all examples, ensure you have these environment variables:
+
+```bash .env.local
+SUPERMEMORY_API_KEY=your_supermemory_key
+OPENAI_API_KEY=your_openai_key
+ANTHROPIC_API_KEY=your_anthropic_key
+```
+
+## Best Practices
+
+### Memory Tools
+- Use descriptive memory content for better search results
+- Include context in your system prompts about when to use each tool
+- Use project headers to separate different use cases
+- Implement error handling for tool failures
+
+### Infinite Chat
+- Use conversation IDs to maintain separate chat contexts
+- Include user IDs for personalized experiences
+- Test with different providers to find the best fit for your use case
+- Monitor token usage for cost optimization
+
+### General Tips
+- Start with simple examples and gradually add complexity
+- Use the search functionality to avoid duplicate memories
+- Implement proper authentication for production use
+- Consider rate limiting for high-volume applications
+
+## Next Steps
+
+<CardGroup cols={2}>
+ <Card title="Memory API" icon="database" href="/memory-api/overview">
+ Advanced memory management with full API control
+ </Card>
+
+ <Card title="Memory Router" icon="route" href="/memory-router/overview">
+ Drop-in proxy for existing LLM applications
+ </Card>
+</CardGroup>
diff --git a/apps/docs/cookbook/chat-with-gdrive.mdx b/apps/docs/cookbook/chat-with-gdrive.mdx
new file mode 100644
index 00000000..fd7e217b
--- /dev/null
+++ b/apps/docs/cookbook/chat-with-gdrive.mdx
@@ -0,0 +1,4 @@
+---
+title: "Chat with Google Drive"
+url: "https://supermemory.ai/blog/building-an-ai-compliance-chatbot-with-supermemory-and-google-drive/"
+---
diff --git a/apps/docs/cookbook/customer-support.mdx b/apps/docs/cookbook/customer-support.mdx
new file mode 100644
index 00000000..250def78
--- /dev/null
+++ b/apps/docs/cookbook/customer-support.mdx
@@ -0,0 +1,1047 @@
+---
+title: "Customer Support Bot"
+description: "Build an intelligent support system that remembers customer history and provides personalized help"
+---
+
+Create a customer support system that remembers every interaction, tracks issues across conversations, and provides personalized support based on customer history and preferences.
+
+## What You'll Build
+
+A customer support bot that:
+- **Remembers customer history** across all conversations and channels
+- **Tracks ongoing issues** and follows up automatically
+- **Provides personalized responses** based on customer tier and preferences
+- **Escalates complex issues** to human agents with full context
+- **Learns from resolutions** to improve future responses
+
+## Prerequisites
+
+- Node.js 18+ or Python 3.8+
+- Supermemory API key
+- OpenAI API key
+- Customer database or CRM integration
+- Basic understanding of customer support workflows
+
+## Implementation
+
+### Step 1: Customer Context Management
+
+<Tabs>
+ <Tab title="Next.js">
+ ```typescript lib/customer-context.ts
+ import { Supermemory } from 'supermemory'
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ })
+
+ interface Customer {
+ id: string
+ email: string
+ name: string
+ tier: 'free' | 'pro' | 'enterprise'
+ joinDate: string
+ preferences?: Record<string, any>
+ }
+
+ interface SupportTicket {
+ id: string
+ customerId: string
+ subject: string
+ status: 'open' | 'pending' | 'resolved' | 'closed'
+ priority: 'low' | 'medium' | 'high' | 'urgent'
+ category: string
+ createdAt: string
+ updatedAt: string
+ assignedAgent?: string
+ }
+
+ export class CustomerContextManager {
+ private getContainerTag(customerId: string): string {
+ return `customer_${customerId}`
+ }
+
+ async addInteraction(customerId: string, interaction: {
+ type: 'chat' | 'email' | 'phone' | 'ticket'
+ content: string
+ channel: string
+ outcome?: 'resolved' | 'escalated' | 'pending'
+ agentId?: string
+ metadata?: Record<string, any>
+ }) {
+ try {
+ const result = await client.memories.add({
+ content: `${interaction.type.toUpperCase()}: ${interaction.content}`,
+ containerTag: this.getContainerTag(customerId),
+ metadata: {
+ type: 'customer_interaction',
+ interactionType: interaction.type,
+ channel: interaction.channel,
+ outcome: interaction.outcome,
+ agentId: interaction.agentId,
+ timestamp: new Date().toISOString(),
+ ...interaction.metadata
+ }
+ })
+
+ return result
+ } catch (error) {
+ console.error('Failed to add customer interaction:', error)
+ throw error
+ }
+ }
+
+ async getCustomerHistory(customerId: string, limit: number = 10) {
+ try {
+ const memories = await client.memories.list({
+ containerTags: [this.getContainerTag(customerId)],
+ limit,
+ sort: 'updatedAt',
+ order: 'desc'
+ })
+
+ return memories.memories.map(memory => ({
+ id: memory.id,
+ content: memory.content,
+ type: memory.metadata?.interactionType || 'unknown',
+ channel: memory.metadata?.channel,
+ outcome: memory.metadata?.outcome,
+ timestamp: memory.metadata?.timestamp || memory.createdAt,
+ agentId: memory.metadata?.agentId
+ }))
+ } catch (error) {
+ console.error('Failed to get customer history:', error)
+ throw error
+ }
+ }
+
+ async searchCustomerContext(customerId: string, query: string) {
+ try {
+ const results = await client.search.memories({
+ q: query,
+ containerTag: this.getContainerTag(customerId),
+ threshold: 0.6,
+ limit: 5,
+ rerank: true
+ })
+
+ return results.results.map(result => ({
+ content: result.memory,
+ similarity: result.similarity,
+ metadata: result.metadata
+ }))
+ } catch (error) {
+ console.error('Failed to search customer context:', error)
+ throw error
+ }
+ }
+
+ async trackIssue(customerId: string, issue: {
+ subject: string
+ description: string
+ category: string
+ priority: 'low' | 'medium' | 'high' | 'urgent'
+ status: 'open' | 'pending' | 'resolved'
+ }) {
+ try {
+ const issueContent = `ISSUE: ${issue.subject}\n\nDescription: ${issue.description}\nCategory: ${issue.category}\nPriority: ${issue.priority}\nStatus: ${issue.status}`
+
+ const result = await client.memories.add({
+ content: issueContent,
+ containerTag: this.getContainerTag(customerId),
+ metadata: {
+ type: 'support_issue',
+ subject: issue.subject,
+ category: issue.category,
+ priority: issue.priority,
+ status: issue.status,
+ createdAt: new Date().toISOString()
+ }
+ })
+
+ return result
+ } catch (error) {
+ console.error('Failed to track issue:', error)
+ throw error
+ }
+ }
+
+ async updateIssueStatus(issueId: string, status: 'open' | 'pending' | 'resolved' | 'closed', resolution?: string) {
+ try {
+ // Note: In a real implementation, you'd update the memory
+ // For now, we'll add a status update
+ const memory = await client.memories.get(issueId)
+ const customerId = memory.containerTag.replace('customer_', '')
+
+ const updateContent = `ISSUE UPDATE: ${memory.metadata?.subject}\nStatus changed to: ${status}${resolution ? `\nResolution: ${resolution}` : ''}`
+
+ return await this.addInteraction(customerId, {
+ type: 'ticket',
+ content: updateContent,
+ channel: 'internal',
+ outcome: status === 'resolved' ? 'resolved' : 'pending',
+ metadata: {
+ originalIssueId: issueId,
+ statusUpdate: true
+ }
+ })
+ } catch (error) {
+ console.error('Failed to update issue status:', error)
+ throw error
+ }
+ }
+ }
+ ```
+ </Tab>
+
+ <Tab title="Python">
+ ```python customer_context.py
+ from supermemory import Supermemory
+ import os
+ from typing import Dict, List, Any, Optional
+ from datetime import datetime
+ from enum import Enum
+
+ class InteractionType(Enum):
+ CHAT = "chat"
+ EMAIL = "email"
+ PHONE = "phone"
+ TICKET = "ticket"
+
+ class Priority(Enum):
+ LOW = "low"
+ MEDIUM = "medium"
+ HIGH = "high"
+ URGENT = "urgent"
+
+ class Status(Enum):
+ OPEN = "open"
+ PENDING = "pending"
+ RESOLVED = "resolved"
+ CLOSED = "closed"
+
+ class CustomerContextManager:
+ def __init__(self):
+ self.client = Supermemory(api_key=os.getenv("SUPERMEMORY_API_KEY"))
+
+ def _get_container_tag(self, customer_id: str) -> str:
+ return f"customer_{customer_id}"
+
+ def add_interaction(self, customer_id: str, interaction: Dict[str, Any]) -> Dict:
+ """Add a customer interaction to memory"""
+ try:
+ content = f"{interaction['type'].upper()}: {interaction['content']}"
+
+ result = self.client.memories.add(
+ content=content,
+ container_tag=self._get_container_tag(customer_id),
+ metadata={
+ 'type': 'customer_interaction',
+ 'interactionType': interaction['type'],
+ 'channel': interaction['channel'],
+ 'outcome': interaction.get('outcome'),
+ 'agentId': interaction.get('agentId'),
+ 'timestamp': datetime.now().isoformat(),
+ **interaction.get('metadata', {})
+ }
+ )
+ return result
+ except Exception as e:
+ print(f"Failed to add customer interaction: {e}")
+ raise
+
+ def get_customer_history(self, customer_id: str, limit: int = 10) -> List[Dict]:
+ """Get customer interaction history"""
+ try:
+ memories = self.client.memories.list(
+ container_tags=[self._get_container_tag(customer_id)],
+ limit=limit,
+ sort='updatedAt',
+ order='desc'
+ )
+
+ return [
+ {
+ 'id': memory.id,
+ 'content': memory.content,
+ 'type': memory.metadata.get('interactionType', 'unknown') if memory.metadata else 'unknown',
+ 'channel': memory.metadata.get('channel') if memory.metadata else None,
+ 'outcome': memory.metadata.get('outcome') if memory.metadata else None,
+ 'timestamp': memory.metadata.get('timestamp', memory.created_at) if memory.metadata else memory.created_at,
+ 'agentId': memory.metadata.get('agentId') if memory.metadata else None
+ }
+ for memory in memories.memories
+ ]
+ except Exception as e:
+ print(f"Failed to get customer history: {e}")
+ raise
+
+ def search_customer_context(self, customer_id: str, query: str) -> List[Dict]:
+ """Search customer's interaction history"""
+ try:
+ results = self.client.search.memories(
+ q=query,
+ container_tag=self._get_container_tag(customer_id),
+ threshold=0.6,
+ limit=5,
+ rerank=True
+ )
+
+ return [
+ {
+ 'content': result.memory,
+ 'similarity': result.similarity,
+ 'metadata': result.metadata
+ }
+ for result in results.results
+ ]
+ except Exception as e:
+ print(f"Failed to search customer context: {e}")
+ raise
+
+ def track_issue(self, customer_id: str, issue: Dict[str, str]) -> Dict:
+ """Track a customer support issue"""
+ try:
+ issue_content = f"""ISSUE: {issue['subject']}
+
+Description: {issue['description']}
+Category: {issue['category']}
+Priority: {issue['priority']}
+Status: {issue['status']}"""
+
+ result = self.client.memories.add(
+ content=issue_content,
+ container_tag=self._get_container_tag(customer_id),
+ metadata={
+ 'type': 'support_issue',
+ 'subject': issue['subject'],
+ 'category': issue['category'],
+ 'priority': issue['priority'],
+ 'status': issue['status'],
+ 'createdAt': datetime.now().isoformat()
+ }
+ )
+ return result
+ except Exception as e:
+ print(f"Failed to track issue: {e}")
+ raise
+
+ def update_issue_status(self, issue_id: str, status: str, resolution: Optional[str] = None) -> Dict:
+ """Update the status of a support issue"""
+ try:
+ # Get original issue
+ memory = self.client.memories.get(issue_id)
+ customer_id = memory.container_tag.replace('customer_', '')
+
+ update_content = f"ISSUE UPDATE: {memory.metadata.get('subject', 'Unknown')}\nStatus changed to: {status}"
+ if resolution:
+ update_content += f"\nResolution: {resolution}"
+
+ return self.add_interaction(customer_id, {
+ 'type': 'ticket',
+ 'content': update_content,
+ 'channel': 'internal',
+ 'outcome': 'resolved' if status == 'resolved' else 'pending',
+ 'metadata': {
+ 'originalIssueId': issue_id,
+ 'statusUpdate': True
+ }
+ })
+ except Exception as e:
+ print(f"Failed to update issue status: {e}")
+ raise
+ ```
+ </Tab>
+</Tabs>
+
+### Step 2: Support API with Context
+
+<Tabs>
+ <Tab title="Next.js API Route">
+ ```typescript app/api/support/chat/route.ts
+ import { streamText } from 'ai'
+ import { createOpenAI } from '@ai-sdk/openai'
+ import { CustomerContextManager } from '@/lib/customer-context'
+
+ const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+ })
+
+ const contextManager = new CustomerContextManager()
+
+ interface Customer {
+ id: string
+ name: string
+ email: string
+ tier: 'free' | 'pro' | 'enterprise'
+ joinDate: string
+ }
+
+ export async function POST(request: Request) {
+ const {
+ message,
+ customerId,
+ customer,
+ conversationHistory = [],
+ agentId
+ } = await request.json()
+
+ try {
+ // Get customer history and context
+ const [history, contextResults] = await Promise.all([
+ contextManager.getCustomerHistory(customerId, 5),
+ contextManager.searchCustomerContext(customerId, message)
+ ])
+
+ // Build customer context
+ const customerContext = `
+CUSTOMER PROFILE:
+- Name: ${customer.name}
+- Email: ${customer.email}
+- Tier: ${customer.tier.toUpperCase()}
+- Member since: ${customer.joinDate}
+
+RECENT INTERACTIONS (Last 5):
+${history.map(h => `- ${h.timestamp}: ${h.type.toUpperCase()} - ${h.content.substring(0, 100)}...`).join('\n')}
+
+RELEVANT CONTEXT:
+${contextResults.map(c => `- ${c.content.substring(0, 150)}... (${(c.similarity * 100).toFixed(1)}% relevant)`).join('\n')}
+ `.trim()
+
+ // Determine if escalation is needed
+ const escalationKeywords = ['angry', 'frustrated', 'cancel', 'refund', 'legal', 'complaint', 'manager', 'supervisor']
+ const needsEscalation = escalationKeywords.some(keyword =>
+ message.toLowerCase().includes(keyword)
+ ) || customer.tier === 'enterprise'
+
+ const systemPrompt = `You are a helpful customer support agent with access to complete customer history and context.
+
+CUSTOMER CONTEXT:
+${customerContext}
+
+SUPPORT GUIDELINES:
+1. **Personalization**: Address the customer by name and reference their tier/history when relevant
+2. **Context Awareness**: Use previous interactions to inform your response
+3. **Tier-Specific Service**:
+ - Free: Standard support, guide to self-service resources
+ - Pro: Priority support, detailed explanations, proactive suggestions
+ - Enterprise: White-glove service, immediate escalation path, dedicated attention
+
+4. **Issue Tracking**: If this is a new issue, categorize it (billing, technical, account, product)
+5. **Escalation**: ${needsEscalation ? 'This interaction may need human agent escalation - provide helpful response but prepare escalation summary' : 'Handle directly unless customer specifically requests human agent'}
+
+RESPONSE STYLE:
+- Professional but friendly
+- Reference specific details from customer history when relevant
+- Provide actionable next steps
+- Include relevant links or resources for their tier level
+
+If you cannot resolve the issue completely, prepare a clear summary for escalation to human agents.`
+
+ const messages = [
+ { role: 'system' as const, content: systemPrompt },
+ ...conversationHistory,
+ { role: 'user' as const, content: message }
+ ]
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ temperature: 0.3,
+ maxTokens: 800,
+ onFinish: async (completion) => {
+ // Store this interaction
+ await contextManager.addInteraction(customerId, {
+ type: 'chat',
+ content: `Customer: ${message}\nAgent: ${completion.text}`,
+ channel: 'web_chat',
+ outcome: needsEscalation ? 'escalated' : 'resolved',
+ agentId,
+ metadata: {
+ customerTier: customer.tier,
+ needsEscalation,
+ responseLength: completion.text.length
+ }
+ })
+
+ // If this looks like a new issue, track it
+ if (message.length > 50 && !contextResults.some(c => c.similarity > 0.8)) {
+ const issueCategory = categorizeIssue(message)
+ const priority = determinePriority(customer.tier, message)
+
+ await contextManager.trackIssue(customerId, {
+ subject: message.substring(0, 100),
+ description: message,
+ category: issueCategory,
+ priority,
+ status: needsEscalation ? 'pending' : 'open'
+ })
+ }
+ }
+ })
+
+ return result.toAIStreamResponse({
+ data: {
+ needsEscalation,
+ customerTier: customer.tier,
+ contextCount: contextResults.length
+ }
+ })
+
+ } catch (error) {
+ console.error('Support chat error:', error)
+ return Response.json(
+ { error: 'Failed to process support request', details: error.message },
+ { status: 500 }
+ )
+ }
+ }
+
+ function categorizeIssue(message: string): string {
+ const categories = {
+ billing: ['bill', 'charge', 'payment', 'refund', 'price', 'cost'],
+ technical: ['error', 'bug', 'broken', 'not working', 'crash', 'slow'],
+ account: ['login', 'password', 'access', 'settings', 'profile'],
+ product: ['feature', 'how to', 'tutorial', 'help', 'guide']
+ }
+
+ const messageLower = message.toLowerCase()
+
+ for (const [category, keywords] of Object.entries(categories)) {
+ if (keywords.some(keyword => messageLower.includes(keyword))) {
+ return category
+ }
+ }
+
+ return 'general'
+ }
+
+ function determinePriority(tier: string, message: string): 'low' | 'medium' | 'high' | 'urgent' {
+ const urgentKeywords = ['urgent', 'critical', 'emergency', 'down', 'broken']
+ const highKeywords = ['important', 'asap', 'soon', 'problem']
+
+ const messageLower = message.toLowerCase()
+
+ if (urgentKeywords.some(keyword => messageLower.includes(keyword))) {
+ return 'urgent'
+ }
+
+ if (tier === 'enterprise') {
+ return highKeywords.some(keyword => messageLower.includes(keyword)) ? 'urgent' : 'high'
+ }
+
+ if (tier === 'pro') {
+ return highKeywords.some(keyword => messageLower.includes(keyword)) ? 'high' : 'medium'
+ }
+
+ return 'low'
+ }
+ ```
+ </Tab>
+
+ <Tab title="Python FastAPI">
+ ```python support_api.py
+ from fastapi import FastAPI, HTTPException
+ from fastapi.responses import StreamingResponse
+ from pydantic import BaseModel
+ from typing import List, Dict, Any, Optional
+ import openai
+ from customer_context import CustomerContextManager
+ import json
+ import os
+ import re
+
+ app = FastAPI()
+
+ openai_client = openai.AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ context_manager = CustomerContextManager()
+
+ class Customer(BaseModel):
+ id: str
+ name: str
+ email: str
+ tier: str
+ joinDate: str
+
+ class SupportRequest(BaseModel):
+ message: str
+ customerId: str
+ customer: Customer
+ conversationHistory: List[Dict[str, str]] = []
+ agentId: Optional[str] = None
+
+ def categorize_issue(message: str) -> str:
+ """Categorize support issue based on message content"""
+ categories = {
+ 'billing': ['bill', 'charge', 'payment', 'refund', 'price', 'cost'],
+ 'technical': ['error', 'bug', 'broken', 'not working', 'crash', 'slow'],
+ 'account': ['login', 'password', 'access', 'settings', 'profile'],
+ 'product': ['feature', 'how to', 'tutorial', 'help', 'guide']
+ }
+
+ message_lower = message.lower()
+
+ for category, keywords in categories.items():
+ if any(keyword in message_lower for keyword in keywords):
+ return category
+
+ return 'general'
+
+ def determine_priority(tier: str, message: str) -> str:
+ """Determine issue priority based on tier and message content"""
+ urgent_keywords = ['urgent', 'critical', 'emergency', 'down', 'broken']
+ high_keywords = ['important', 'asap', 'soon', 'problem']
+
+ message_lower = message.lower()
+
+ if any(keyword in message_lower for keyword in urgent_keywords):
+ return 'urgent'
+
+ if tier == 'enterprise':
+ return 'urgent' if any(keyword in message_lower for keyword in high_keywords) else 'high'
+
+ if tier == 'pro':
+ return 'high' if any(keyword in message_lower for keyword in high_keywords) else 'medium'
+
+ return 'low'
+
+ @app.post("/support/chat")
+ async def support_chat(request: SupportRequest):
+ try:
+ # Get customer history and context
+ history = context_manager.get_customer_history(request.customerId, 5)
+ context_results = context_manager.search_customer_context(request.customerId, request.message)
+
+ # Build customer context
+ customer_context = f"""
+CUSTOMER PROFILE:
+- Name: {request.customer.name}
+- Email: {request.customer.email}
+- Tier: {request.customer.tier.upper()}
+- Member since: {request.customer.joinDate}
+
+RECENT INTERACTIONS (Last 5):
+{chr(10).join([f"- {h['timestamp']}: {h['type'].upper()} - {h['content'][:100]}..." for h in history])}
+
+RELEVANT CONTEXT:
+{chr(10).join([f"- {c['content'][:150]}... ({c['similarity']*100:.1f}% relevant)" for c in context_results])}
+ """.strip()
+
+ # Determine if escalation is needed
+ escalation_keywords = ['angry', 'frustrated', 'cancel', 'refund', 'legal', 'complaint', 'manager', 'supervisor']
+ needs_escalation = any(keyword in request.message.lower() for keyword in escalation_keywords) or request.customer.tier == 'enterprise'
+
+ system_prompt = f"""You are a helpful customer support agent with access to complete customer history and context.
+
+CUSTOMER CONTEXT:
+{customer_context}
+
+SUPPORT GUIDELINES:
+1. **Personalization**: Address the customer by name and reference their tier/history when relevant
+2. **Context Awareness**: Use previous interactions to inform your response
+3. **Tier-Specific Service**:
+ - Free: Standard support, guide to self-service resources
+ - Pro: Priority support, detailed explanations, proactive suggestions
+ - Enterprise: White-glove service, immediate escalation path, dedicated attention
+
+4. **Issue Tracking**: If this is a new issue, categorize it (billing, technical, account, product)
+5. **Escalation**: {'This interaction may need human agent escalation - provide helpful response but prepare escalation summary' if needs_escalation else 'Handle directly unless customer specifically requests human agent'}
+
+RESPONSE STYLE:
+- Professional but friendly
+- Reference specific details from customer history when relevant
+- Provide actionable next steps
+- Include relevant links or resources for their tier level
+
+If you cannot resolve the issue completely, prepare a clear summary for escalation to human agents."""
+
+ messages = [
+ {"role": "system", "content": system_prompt},
+ *request.conversationHistory,
+ {"role": "user", "content": request.message}
+ ]
+
+ response = await openai_client.chat.completions.create(
+ model="gpt-4-turbo",
+ messages=messages,
+ temperature=0.3,
+ max_tokens=800,
+ stream=True
+ )
+
+ async def generate():
+ full_response = ""
+ async for chunk in response:
+ if chunk.choices[0].delta.content:
+ content = chunk.choices[0].delta.content
+ full_response += content
+ yield f"data: {json.dumps({'content': content})}\n\n"
+
+ # Store interaction after completion
+ context_manager.add_interaction(request.customerId, {
+ 'type': 'chat',
+ 'content': f"Customer: {request.message}\nAgent: {full_response}",
+ 'channel': 'web_chat',
+ 'outcome': 'escalated' if needs_escalation else 'resolved',
+ 'agentId': request.agentId,
+ 'metadata': {
+ 'customerTier': request.customer.tier,
+ 'needsEscalation': needs_escalation,
+ 'responseLength': len(full_response)
+ }
+ })
+
+ # Track new issues
+ if len(request.message) > 50 and not any(c['similarity'] > 0.8 for c in context_results):
+ issue_category = categorize_issue(request.message)
+ priority = determine_priority(request.customer.tier, request.message)
+
+ context_manager.track_issue(request.customerId, {
+ 'subject': request.message[:100],
+ 'description': request.message,
+ 'category': issue_category,
+ 'priority': priority,
+ 'status': 'pending' if needs_escalation else 'open'
+ })
+
+ yield f"data: {json.dumps({'done': True, 'needsEscalation': needs_escalation})}\n\n"
+
+ return StreamingResponse(generate(), media_type="text/plain")
+
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=f"Support chat error: {str(e)}")
+
+ if __name__ == "__main__":
+ import uvicorn
+ uvicorn.run(app, host="0.0.0.0", port=8000)
+ ```
+ </Tab>
+</Tabs>
+
+### Step 3: Support Dashboard Interface
+
+```tsx app/support/page.tsx
+'use client'
+
+import { useState, useEffect } from 'react'
+import { useChat } from 'ai/react'
+import { CustomerContextManager } from '@/lib/customer-context'
+
+interface Customer {
+ id: string
+ name: string
+ email: string
+ tier: 'free' | 'pro' | 'enterprise'
+ joinDate: string
+}
+
+interface SupportTicket {
+ id: string
+ subject: string
+ status: 'open' | 'pending' | 'resolved' | 'closed'
+ priority: 'low' | 'medium' | 'high' | 'urgent'
+ category: string
+ createdAt: string
+}
+
+export default function SupportDashboard() {
+ const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null)
+ const [customerHistory, setCustomerHistory] = useState<any[]>([])
+ const [tickets, setTickets] = useState<SupportTicket[]>([])
+ const [showEscalation, setShowEscalation] = useState(false)
+ const [agentId] = useState('agent_001') // In real app, get from auth
+
+ const contextManager = new CustomerContextManager()
+
+ const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
+ api: '/api/support/chat',
+ body: {
+ customerId: selectedCustomer?.id,
+ customer: selectedCustomer,
+ agentId
+ },
+ onFinish: (message, { data }) => {
+ if (data?.needsEscalation) {
+ setShowEscalation(true)
+ }
+ // Refresh customer history
+ if (selectedCustomer) {
+ loadCustomerHistory(selectedCustomer.id)
+ }
+ }
+ })
+
+ // Mock customers - in real app, fetch from your customer database
+ const mockCustomers: Customer[] = [
+ {
+ id: 'cust_001',
+ name: 'Sarah Johnson',
+ email: '[email protected]',
+ tier: 'pro',
+ joinDate: '2023-06-15'
+ },
+ {
+ id: 'cust_002',
+ name: 'TechCorp Inc',
+ email: '[email protected]',
+ tier: 'enterprise',
+ joinDate: '2022-03-20'
+ },
+ {
+ id: 'cust_003',
+ name: 'Mike Chen',
+ email: '[email protected]',
+ tier: 'free',
+ joinDate: '2024-01-10'
+ }
+ ]
+
+ const loadCustomerHistory = async (customerId: string) => {
+ try {
+ const history = await contextManager.getCustomerHistory(customerId, 10)
+ setCustomerHistory(history)
+ } catch (error) {
+ console.error('Failed to load customer history:', error)
+ }
+ }
+
+ const handleCustomerSelect = async (customer: Customer) => {
+ setSelectedCustomer(customer)
+ await loadCustomerHistory(customer.id)
+ setShowEscalation(false)
+ }
+
+ const getTierColor = (tier: string) => {
+ switch (tier) {
+ case 'enterprise': return 'bg-purple-100 text-purple-800'
+ case 'pro': return 'bg-blue-100 text-blue-800'
+ case 'free': return 'bg-gray-100 text-gray-800'
+ default: return 'bg-gray-100 text-gray-800'
+ }
+ }
+
+ const getPriorityColor = (priority: string) => {
+ switch (priority) {
+ case 'urgent': return 'bg-red-100 text-red-800'
+ case 'high': return 'bg-orange-100 text-orange-800'
+ case 'medium': return 'bg-yellow-100 text-yellow-800'
+ case 'low': return 'bg-green-100 text-green-800'
+ default: return 'bg-gray-100 text-gray-800'
+ }
+ }
+
+ return (
+ <div className="h-screen flex">
+ {/* Customer List Sidebar */}
+ <div className="w-80 bg-white border-r border-gray-200 overflow-y-auto">
+ <div className="p-4 border-b">
+ <h2 className="text-lg font-semibold">Customers</h2>
+ </div>
+ <div className="divide-y divide-gray-200">
+ {mockCustomers.map((customer) => (
+ <div
+ key={customer.id}
+ onClick={() => handleCustomerSelect(customer)}
+ className={`p-4 cursor-pointer hover:bg-gray-50 ${
+ selectedCustomer?.id === customer.id ? 'bg-blue-50 border-r-2 border-blue-500' : ''
+ }`}
+ >
+ <div className="flex items-center justify-between mb-2">
+ <div className="font-medium text-gray-900">{customer.name}</div>
+ <span className={`px-2 py-1 text-xs rounded-full ${getTierColor(customer.tier)}`}>
+ {customer.tier}
+ </span>
+ </div>
+ <div className="text-sm text-gray-600">{customer.email}</div>
+ <div className="text-xs text-gray-500 mt-1">
+ Member since {customer.joinDate}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <div className="flex-1 flex flex-col">
+ {selectedCustomer ? (
+ <>
+ {/* Customer Header */}
+ <div className="bg-white border-b border-gray-200 p-4">
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-xl font-semibold">{selectedCustomer.name}</h1>
+ <p className="text-gray-600">{selectedCustomer.email}</p>
+ </div>
+ <div className="flex items-center space-x-4">
+ <span className={`px-3 py-1 text-sm rounded-full ${getTierColor(selectedCustomer.tier)}`}>
+ {selectedCustomer.tier.toUpperCase()} Customer
+ </span>
+ {showEscalation && (
+ <div className="bg-red-100 text-red-800 px-3 py-1 text-sm rounded-full">
+ Needs Escalation
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="flex-1 flex">
+ {/* Chat Area */}
+ <div className="flex-1 flex flex-col">
+ {/* Messages */}
+ <div className="flex-1 overflow-y-auto p-4 space-y-4">
+ {messages.length === 0 && (
+ <div className="text-center py-8 text-gray-500">
+ <div className="text-lg font-medium">Welcome to Support Chat</div>
+ <p className="mt-2">
+ Start a conversation with {selectedCustomer.name}
+ </p>
+ <div className="mt-4 text-sm">
+ <p><strong>Customer Tier:</strong> {selectedCustomer.tier}</p>
+ <p><strong>Join Date:</strong> {selectedCustomer.joinDate}</p>
+ </div>
+ </div>
+ )}
+
+ {messages.map((message) => (
+ <div
+ key={message.id}
+ className={`flex ${
+ message.role === 'user' ? 'justify-end' : 'justify-start'
+ }`}
+ >
+ <div
+ className={`max-w-2xl p-4 rounded-lg ${
+ message.role === 'user'
+ ? 'bg-blue-500 text-white'
+ : 'bg-gray-100 text-gray-900'
+ }`}
+ >
+ <div className="flex items-center space-x-2 mb-2">
+ <span className="text-sm font-medium">
+ {message.role === 'user' ? selectedCustomer.name : 'Support Agent'}
+ </span>
+ <span className="text-xs opacity-75">
+ {new Date().toLocaleTimeString()}
+ </span>
+ </div>
+ <div className="whitespace-pre-wrap">{message.content}</div>
+ </div>
+ </div>
+ ))}
+
+ {isLoading && (
+ <div className="flex justify-start">
+ <div className="max-w-2xl p-4 bg-gray-100 rounded-lg">
+ <div className="flex items-center space-x-2">
+ <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
+ <span className="text-sm">Agent is typing...</span>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Chat Input */}
+ <div className="border-t border-gray-200 p-4">
+ <form onSubmit={handleSubmit} className="flex space-x-2">
+ <input
+ value={input}
+ onChange={handleInputChange}
+ placeholder={`Respond to ${selectedCustomer.name}...`}
+ className="flex-1 p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
+ disabled={isLoading}
+ />
+ <button
+ type="submit"
+ disabled={isLoading || !input.trim()}
+ className="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ Send
+ </button>
+ </form>
+ </div>
+ </div>
+
+ {/* Customer History Sidebar */}
+ <div className="w-80 bg-gray-50 border-l border-gray-200 overflow-y-auto">
+ <div className="p-4 border-b bg-white">
+ <h3 className="font-medium">Customer History</h3>
+ </div>
+ <div className="p-4 space-y-3">
+ {customerHistory.map((interaction, index) => (
+ <div key={index} className="bg-white p-3 rounded-lg border text-sm">
+ <div className="flex items-center justify-between mb-2">
+ <span className="font-medium capitalize">{interaction.type}</span>
+ <span className="text-xs text-gray-500">
+ {new Date(interaction.timestamp).toLocaleDateString()}
+ </span>
+ </div>
+ <p className="text-gray-700 line-clamp-3">
+ {interaction.content.length > 100
+ ? `${interaction.content.substring(0, 100)}...`
+ : interaction.content
+ }
+ </p>
+ {interaction.outcome && (
+ <div className="mt-2">
+ <span className={`text-xs px-2 py-1 rounded ${
+ interaction.outcome === 'resolved'
+ ? 'bg-green-100 text-green-800'
+ : interaction.outcome === 'escalated'
+ ? 'bg-red-100 text-red-800'
+ : 'bg-yellow-100 text-yellow-800'
+ }`}>
+ {interaction.outcome}
+ </span>
+ </div>
+ )}
+ </div>
+ ))}
+
+ {customerHistory.length === 0 && (
+ <div className="text-center py-8 text-gray-500">
+ <p>No previous interactions</p>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </>
+ ) : (
+ <div className="flex-1 flex items-center justify-center text-gray-500">
+ <div className="text-center">
+ <div className="text-lg font-medium">Customer Support</div>
+ <p className="mt-2">Select a customer to start a support conversation</p>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
+```
+
+## Testing Your Support System
+
+### Step 4: Test Support Scenarios
+
+1. **Test Customer Tiers**:
+ - Free tier: Basic responses, self-service guidance
+ - Pro tier: Detailed help, proactive suggestions
+ - Enterprise: White-glove service, escalation readiness
+
+2. **Test Memory & Context**:
+ - Ask about a previous issue
+ - Reference customer preferences
+ - Follow up on unresolved tickets
+
+3. **Test Escalation Triggers**:
+ - Use keywords like "angry", "manager", "refund"
+ - Test enterprise customer automatic escalation
+
+This comprehensive customer support recipe provides the foundation for building intelligent, context-aware support systems that improve customer satisfaction through personalized service.
+
+---
+
+*Customize this recipe based on your specific support workflows and customer needs.* \ No newline at end of file
diff --git a/apps/docs/cookbook/document-qa.mdx b/apps/docs/cookbook/document-qa.mdx
new file mode 100644
index 00000000..c3bc224e
--- /dev/null
+++ b/apps/docs/cookbook/document-qa.mdx
@@ -0,0 +1,883 @@
+---
+title: "Document Q&A System"
+description: "Build a chatbot that answers questions from your documents with citations and source references"
+---
+
+Create a powerful document Q&A system that can ingest PDFs, text files, and web pages, then answer questions with accurate citations. Perfect for documentation sites, research databases, or internal knowledge bases.
+
+## What You'll Build
+
+A document Q&A system that:
+- **Ingests multiple file types** (PDFs, DOCX, text, URLs)
+- **Answers questions accurately** with source citations
+- **Provides source references** with page numbers and document titles
+- **Handles follow-up questions** with conversation context
+- **Supports multiple document collections** for different topics
+
+## Prerequisites
+
+- Node.js 18+ or Python 3.8+
+- Supermemory API key
+- OpenAI API key
+- Basic understanding of file handling
+
+## Implementation
+
+### Step 1: Document Processing System
+
+<Tabs>
+ <Tab title="Next.js">
+ ```typescript lib/document-processor.ts
+ import { Supermemory } from 'supermemory'
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ })
+
+ interface DocumentUpload {
+ file: File
+ collection: string
+ metadata?: Record<string, any>
+ }
+
+ export class DocumentProcessor {
+ async uploadDocument({ file, collection, metadata = {} }: DocumentUpload) {
+ try {
+ const formData = new FormData()
+ formData.append('file', file)
+ formData.append('containerTags', JSON.stringify([collection]))
+ formData.append('metadata', JSON.stringify({
+ originalName: file.name,
+ fileType: file.type,
+ uploadedAt: new Date().toISOString(),
+ ...metadata
+ }))
+
+ const response = await fetch('/api/upload-document', {
+ method: 'POST',
+ body: formData
+ })
+
+ if (!response.ok) {
+ throw new Error(`Upload failed: ${response.statusText}`)
+ }
+
+ return await response.json()
+ } catch (error) {
+ console.error('Document upload error:', error)
+ throw error
+ }
+ }
+
+ async uploadURL({ url, collection, metadata = {} }: { url: string, collection: string, metadata?: Record<string, any> }) {
+ try {
+ const result = await client.memories.add({
+ content: url,
+ containerTag: collection,
+ metadata: {
+ type: 'url',
+ originalUrl: url,
+ uploadedAt: new Date().toISOString(),
+ ...metadata
+ }
+ })
+
+ return result
+ } catch (error) {
+ console.error('URL upload error:', error)
+ throw error
+ }
+ }
+
+ async getDocumentStatus(documentId: string) {
+ try {
+ const memory = await client.memories.get(documentId)
+ return {
+ id: memory.id,
+ status: memory.status,
+ title: memory.title,
+ progress: memory.metadata?.progress || 0
+ }
+ } catch (error) {
+ console.error('Status check error:', error)
+ throw error
+ }
+ }
+
+ async listDocuments(collection: string) {
+ try {
+ const memories = await client.memories.list({
+ containerTags: [collection],
+ limit: 50,
+ sort: 'updatedAt',
+ order: 'desc'
+ })
+
+ return memories.memories.map(memory => ({
+ id: memory.id,
+ title: memory.title || memory.metadata?.originalName || 'Untitled',
+ type: memory.metadata?.fileType || memory.metadata?.type || 'unknown',
+ uploadedAt: memory.metadata?.uploadedAt,
+ status: memory.status,
+ url: memory.metadata?.originalUrl
+ }))
+ } catch (error) {
+ console.error('List documents error:', error)
+ throw error
+ }
+ }
+ }
+ ```
+
+ ```typescript app/api/upload-document/route.ts
+ import { NextRequest, NextResponse } from 'next/server'
+ import { Supermemory } from 'supermemory'
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ })
+
+ export async function POST(request: NextRequest) {
+ try {
+ const formData = await request.formData()
+ const file = formData.get('file') as File
+ const containerTags = JSON.parse(formData.get('containerTags') as string)
+ const metadata = JSON.parse(formData.get('metadata') as string || '{}')
+
+ if (!file) {
+ return NextResponse.json({ error: 'No file provided' }, { status: 400 })
+ }
+
+ // Convert File to Buffer for Supermemory
+ const bytes = await file.arrayBuffer()
+ const buffer = Buffer.from(bytes)
+
+ const result = await client.memories.uploadFile({
+ file: buffer,
+ filename: file.name,
+ containerTags,
+ metadata
+ })
+
+ return NextResponse.json({
+ success: true,
+ documentId: result.id,
+ message: 'Document uploaded successfully'
+ })
+
+ } catch (error) {
+ console.error('Upload error:', error)
+ return NextResponse.json(
+ { error: 'Upload failed', details: error.message },
+ { status: 500 }
+ )
+ }
+ }
+ ```
+ </Tab>
+
+ <Tab title="Python">
+ ```python document_processor.py
+ from supermemory import Supermemory
+ import os
+ from typing import Dict, List, Any, Optional
+ import requests
+ from datetime import datetime
+
+ class DocumentProcessor:
+ def __init__(self):
+ self.client = Supermemory(api_key=os.getenv("SUPERMEMORY_API_KEY"))
+
+ def upload_file(self, file_path: str, collection: str, metadata: Dict[str, Any] = None) -> Dict:
+ """Upload a local file to Supermemory"""
+ if metadata is None:
+ metadata = {}
+
+ try:
+ with open(file_path, 'rb') as file:
+ result = self.client.memories.upload_file(
+ file=file,
+ container_tags=[collection],
+ metadata={
+ 'originalName': os.path.basename(file_path),
+ 'fileType': os.path.splitext(file_path)[1],
+ 'uploadedAt': datetime.now().isoformat(),
+ **metadata
+ }
+ )
+ return result
+ except Exception as e:
+ print(f"File upload error: {e}")
+ raise
+
+ def upload_url(self, url: str, collection: str, metadata: Dict[str, Any] = None) -> Dict:
+ """Upload URL content to Supermemory"""
+ if metadata is None:
+ metadata = {}
+
+ try:
+ result = self.client.memories.add(
+ content=url,
+ container_tag=collection,
+ metadata={
+ 'type': 'url',
+ 'originalUrl': url,
+ 'uploadedAt': datetime.now().isoformat(),
+ **metadata
+ }
+ )
+ return result
+ except Exception as e:
+ print(f"URL upload error: {e}")
+ raise
+
+ def get_document_status(self, document_id: str) -> Dict:
+ """Check document processing status"""
+ try:
+ memory = self.client.memories.get(document_id)
+ return {
+ 'id': memory.id,
+ 'status': memory.status,
+ 'title': memory.title,
+ 'progress': memory.metadata.get('progress', 0) if memory.metadata else 0
+ }
+ except Exception as e:
+ print(f"Status check error: {e}")
+ raise
+
+ def list_documents(self, collection: str) -> List[Dict]:
+ """List all documents in a collection"""
+ try:
+ memories = self.client.memories.list(
+ container_tags=[collection],
+ limit=50,
+ sort='updatedAt',
+ order='desc'
+ )
+
+ return [
+ {
+ 'id': memory.id,
+ 'title': (memory.title or
+ memory.metadata.get('originalName') or
+ 'Untitled' if memory.metadata else 'Untitled'),
+ 'type': (memory.metadata.get('fileType') or
+ memory.metadata.get('type') or
+ 'unknown' if memory.metadata else 'unknown'),
+ 'uploadedAt': memory.metadata.get('uploadedAt') if memory.metadata else None,
+ 'status': memory.status,
+ 'url': memory.metadata.get('originalUrl') if memory.metadata else None
+ }
+ for memory in memories.memories
+ ]
+ except Exception as e:
+ print(f"List documents error: {e}")
+ raise
+ ```
+ </Tab>
+</Tabs>
+
+### Step 2: Q&A API with Citations
+
+<Tabs>
+ <Tab title="Next.js API Route">
+ ```typescript app/api/qa/route.ts
+ import { streamText } from 'ai'
+ import { createOpenAI } from '@ai-sdk/openai'
+ import { Supermemory } from 'supermemory'
+
+ const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+ })
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ })
+
+ export async function POST(request: Request) {
+ const { question, collection, conversationHistory = [] } = await request.json()
+
+ try {
+ // Search for relevant documents
+ const searchResults = await client.search.documents({
+ q: question,
+ containerTags: [collection],
+ limit: 8,
+ rerank: true,
+ includeFullDocs: false,
+ includeSummary: true,
+ onlyMatchingChunks: false,
+ documentThreshold: 0.6,
+ chunkThreshold: 0.7
+ })
+
+ if (searchResults.results.length === 0) {
+ return Response.json({
+ answer: "I couldn't find any relevant information in the uploaded documents to answer your question.",
+ sources: [],
+ confidence: 0
+ })
+ }
+
+ // Prepare context from search results
+ const context = searchResults.results.map((result, index) => {
+ const chunks = result.chunks
+ .filter(chunk => chunk.isRelevant)
+ .slice(0, 3)
+ .map(chunk => chunk.content)
+ .join('\n\n')
+
+ return `[Document ${index + 1}: "${result.title}"]\n${chunks}`
+ }).join('\n\n---\n\n')
+
+ // Prepare sources for citation
+ const sources = searchResults.results.map((result, index) => ({
+ id: result.documentId,
+ title: result.title,
+ type: result.type,
+ relevantChunks: result.chunks.filter(chunk => chunk.isRelevant).length,
+ score: result.score,
+ citationNumber: index + 1
+ }))
+
+ const messages = [
+ ...conversationHistory,
+ {
+ role: 'user' as const,
+ content: question
+ }
+ ]
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ system: `You are a helpful document Q&A assistant. Answer questions based ONLY on the provided document context.
+
+CONTEXT FROM DOCUMENTS:
+${context}
+
+INSTRUCTIONS:
+1. Answer the question using ONLY the information from the provided documents
+2. Include specific citations in your response using [Document X] format
+3. If the documents don't contain enough information, say so clearly
+4. Be accurate and quote directly when possible
+5. If multiple documents support a point, cite all relevant ones
+6. Maintain a helpful, professional tone
+
+CITATION FORMAT:
+- Use [Document 1], [Document 2], etc. to cite sources
+- Place citations after the relevant information
+- Example: "The process involves three steps [Document 1]. However, some experts recommend a four-step approach [Document 3]."
+
+If the question cannot be answered from the provided documents, respond with: "I don't have enough information in the provided documents to answer this question accurately."`,
+ temperature: 0.1,
+ maxTokens: 1000
+ })
+
+ return result.toAIStreamResponse({
+ data: {
+ sources,
+ searchResultsCount: searchResults.results.length,
+ totalResults: searchResults.total
+ }
+ })
+
+ } catch (error) {
+ console.error('Q&A error:', error)
+ return Response.json(
+ { error: 'Failed to process question', details: error.message },
+ { status: 500 }
+ )
+ }
+ }
+ ```
+ </Tab>
+
+ <Tab title="Python FastAPI">
+ ```python qa_api.py
+ from fastapi import FastAPI, HTTPException
+ from fastapi.responses import StreamingResponse
+ from pydantic import BaseModel
+ from typing import List, Dict, Any, Optional
+ import openai
+ from supermemory import Supermemory
+ import json
+ import os
+
+ app = FastAPI()
+
+ openai_client = openai.AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ supermemory_client = Supermemory(api_key=os.getenv("SUPERMEMORY_API_KEY"))
+
+ class QARequest(BaseModel):
+ question: str
+ collection: str
+ conversationHistory: List[Dict[str, str]] = []
+
+ class QAResponse(BaseModel):
+ answer: str
+ sources: List[Dict[str, Any]]
+ confidence: float
+ searchResultsCount: int
+
+ @app.post("/qa")
+ async def answer_question(request: QARequest):
+ try:
+ # Search for relevant documents
+ search_results = supermemory_client.search.documents(
+ q=request.question,
+ container_tags=[request.collection],
+ limit=8,
+ rerank=True,
+ include_full_docs=False,
+ include_summary=True,
+ only_matching_chunks=False,
+ document_threshold=0.6,
+ chunk_threshold=0.7
+ )
+
+ if not search_results.results:
+ return QAResponse(
+ answer="I couldn't find any relevant information in the uploaded documents to answer your question.",
+ sources=[],
+ confidence=0,
+ searchResultsCount=0
+ )
+
+ # Prepare context from search results
+ context_parts = []
+ sources = []
+
+ for index, result in enumerate(search_results.results):
+ relevant_chunks = [
+ chunk.content for chunk in result.chunks
+ if chunk.is_relevant
+ ][:3]
+
+ chunk_text = '\n\n'.join(relevant_chunks)
+ context_parts.append(f'[Document {index + 1}: "{result.title}"]\n{chunk_text}')
+
+ sources.append({
+ 'id': result.document_id,
+ 'title': result.title,
+ 'type': result.type,
+ 'relevantChunks': len([c for c in result.chunks if c.is_relevant]),
+ 'score': result.score,
+ 'citationNumber': index + 1
+ })
+
+ context = '\n\n---\n\n'.join(context_parts)
+
+ # Prepare messages
+ messages = [
+ {
+ "role": "system",
+ "content": f"""You are a helpful document Q&A assistant. Answer questions based ONLY on the provided document context.
+
+CONTEXT FROM DOCUMENTS:
+{context}
+
+INSTRUCTIONS:
+1. Answer the question using ONLY the information from the provided documents
+2. Include specific citations in your response using [Document X] format
+3. If the documents don't contain enough information, say so clearly
+4. Be accurate and quote directly when possible
+5. If multiple documents support a point, cite all relevant ones
+6. Maintain a helpful, professional tone
+
+CITATION FORMAT:
+- Use [Document 1], [Document 2], etc. to cite sources
+- Place citations after the relevant information
+- Example: "The process involves three steps [Document 1]. However, some experts recommend a four-step approach [Document 3]."
+
+If the question cannot be answered from the provided documents, respond with: "I don't have enough information in the provided documents to answer this question accurately." """
+ }
+ ]
+
+ # Add conversation history
+ messages.extend(request.conversationHistory)
+ messages.append({"role": "user", "content": request.question})
+
+ # Get AI response
+ response = await openai_client.chat.completions.create(
+ model="gpt-4-turbo",
+ messages=messages,
+ temperature=0.1,
+ max_tokens=1000
+ )
+
+ answer = response.choices[0].message.content
+
+ return QAResponse(
+ answer=answer,
+ sources=sources,
+ confidence=min(search_results.results[0].score if search_results.results else 0, 1.0),
+ searchResultsCount=len(search_results.results)
+ )
+
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=f"Failed to process question: {str(e)}")
+
+ if __name__ == "__main__":
+ import uvicorn
+ uvicorn.run(app, host="0.0.0.0", port=8000)
+ ```
+ </Tab>
+</Tabs>
+
+### Step 3: Frontend Interface
+
+```tsx app/qa/page.tsx
+'use client'
+
+import { useState, useRef } from 'react'
+import { useChat } from 'ai/react'
+import { DocumentProcessor } from '@/lib/document-processor'
+
+interface Document {
+ id: string
+ title: string
+ type: string
+ status: string
+ uploadedAt: string
+}
+
+interface Source {
+ id: string
+ title: string
+ citationNumber: number
+ score: number
+ relevantChunks: number
+}
+
+export default function DocumentQA() {
+ const [collection, setCollection] = useState('default-docs')
+ const [documents, setDocuments] = useState<Document[]>([])
+ const [sources, setSources] = useState<Source[]>([])
+ const [isUploading, setIsUploading] = useState(false)
+ const [uploadProgress, setUploadProgress] = useState<Record<string, number>>({})
+ const fileInputRef = useRef<HTMLInputElement>(null)
+
+ const processor = new DocumentProcessor()
+
+ const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
+ api: '/api/qa',
+ body: {
+ collection
+ },
+ onFinish: (message, { data }) => {
+ if (data?.sources) {
+ setSources(data.sources)
+ }
+ }
+ })
+
+ const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const files = event.target.files
+ if (!files || files.length === 0) return
+
+ setIsUploading(true)
+ const newProgress: Record<string, number> = {}
+
+ try {
+ for (const file of Array.from(files)) {
+ newProgress[file.name] = 0
+ setUploadProgress({ ...newProgress })
+
+ await processor.uploadDocument({
+ file,
+ collection,
+ metadata: {
+ uploadedBy: 'user',
+ category: 'qa-document'
+ }
+ })
+
+ newProgress[file.name] = 100
+ setUploadProgress({ ...newProgress })
+ }
+
+ // Refresh document list
+ await loadDocuments()
+
+ // Clear file input
+ if (fileInputRef.current) {
+ fileInputRef.current.value = ''
+ }
+
+ } catch (error) {
+ console.error('Upload failed:', error)
+ alert('Upload failed: ' + error.message)
+ } finally {
+ setIsUploading(false)
+ setUploadProgress({})
+ }
+ }
+
+ const loadDocuments = async () => {
+ try {
+ const docs = await processor.listDocuments(collection)
+ setDocuments(docs)
+ } catch (error) {
+ console.error('Failed to load documents:', error)
+ }
+ }
+
+ const formatSources = (sources: Source[]) => {
+ if (!sources || sources.length === 0) return null
+
+ return (
+ <div className="mt-4 p-4 bg-gray-50 border border-gray-200 rounded-lg">
+ <h3 className="text-sm font-semibold text-gray-700 mb-2">Sources:</h3>
+ <div className="space-y-2">
+ {sources.map((source) => (
+ <div key={source.id} className="flex items-center space-x-2 text-sm">
+ <span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs font-mono">
+ Document {source.citationNumber}
+ </span>
+ <span className="text-gray-700">{source.title}</span>
+ <span className="text-gray-500">
+ ({source.relevantChunks} relevant chunks, {(source.score * 100).toFixed(1)}% match)
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="max-w-6xl mx-auto p-6">
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
+ {/* Document Management Panel */}
+ <div className="lg:col-span-1">
+ <div className="bg-white border border-gray-200 rounded-lg p-6">
+ <h2 className="text-lg font-semibold mb-4">Document Collection</h2>
+
+ {/* Collection Selector */}
+ <div className="mb-4">
+ <label className="block text-sm font-medium text-gray-700 mb-2">
+ Collection Name
+ </label>
+ <input
+ type="text"
+ value={collection}
+ onChange={(e) => setCollection(e.target.value)}
+ className="w-full p-2 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
+ placeholder="e.g., company-docs"
+ />
+ </div>
+
+ {/* File Upload */}
+ <div className="mb-4">
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept=".pdf,.docx,.txt,.md"
+ onChange={handleFileUpload}
+ className="hidden"
+ />
+ <button
+ onClick={() => fileInputRef.current?.click()}
+ disabled={isUploading}
+ className="w-full p-3 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-400 focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
+ >
+ {isUploading ? 'Uploading...' : 'Upload Documents'}
+ </button>
+ </div>
+
+ {/* Upload Progress */}
+ {Object.keys(uploadProgress).length > 0 && (
+ <div className="mb-4 space-y-2">
+ {Object.entries(uploadProgress).map(([filename, progress]) => (
+ <div key={filename} className="text-sm">
+ <div className="flex justify-between">
+ <span className="truncate">{filename}</span>
+ <span>{progress}%</span>
+ </div>
+ <div className="w-full bg-gray-200 rounded-full h-2">
+ <div
+ className="bg-blue-600 h-2 rounded-full transition-all duration-300"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Document List */}
+ <div className="max-h-64 overflow-y-auto">
+ {documents.map((doc) => (
+ <div key={doc.id} className="mb-2 p-2 bg-gray-50 rounded text-sm">
+ <div className="font-medium truncate">{doc.title}</div>
+ <div className="text-gray-500 text-xs">
+ {doc.type} • {doc.status}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ <button
+ onClick={loadDocuments}
+ className="w-full mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
+ >
+ Refresh Documents
+ </button>
+ </div>
+ </div>
+
+ {/* Q&A Interface */}
+ <div className="lg:col-span-2">
+ <div className="bg-white border border-gray-200 rounded-lg p-6">
+ <h2 className="text-lg font-semibold mb-4">Ask Questions</h2>
+
+ {/* Messages */}
+ <div className="h-96 overflow-y-auto mb-4 space-y-4">
+ {messages.length === 0 && (
+ <div className="text-gray-500 text-center py-8">
+ Upload documents and ask questions to get started!
+
+ <div className="mt-4 text-sm">
+ <p className="font-medium">Try asking:</p>
+ <ul className="mt-2 space-y-1">
+ <li>"What are the main findings?"</li>
+ <li>"Summarize the key points"</li>
+ <li>"What does section 3 say about...?"</li>
+ </ul>
+ </div>
+ </div>
+ )}
+
+ {messages.map((message) => (
+ <div
+ key={message.id}
+ className={`p-4 rounded-lg ${
+ message.role === 'user'
+ ? 'bg-blue-500 text-white ml-8'
+ : 'bg-gray-100 mr-8'
+ }`}
+ >
+ <div className="whitespace-pre-wrap">{message.content}</div>
+
+ {message.role === 'assistant' && sources.length > 0 && (
+ formatSources(sources)
+ )}
+ </div>
+ ))}
+
+ {isLoading && (
+ <div className="bg-gray-100 p-4 rounded-lg mr-8">
+ <div className="flex items-center space-x-2">
+ <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
+ <span>Searching documents and generating answer...</span>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Input */}
+ <form onSubmit={handleSubmit} className="flex gap-2">
+ <input
+ value={input}
+ onChange={handleInputChange}
+ placeholder="Ask a question about your documents..."
+ className="flex-1 p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
+ disabled={isLoading || documents.length === 0}
+ />
+ <button
+ type="submit"
+ disabled={isLoading || !input.trim() || documents.length === 0}
+ className="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ Ask
+ </button>
+ </form>
+
+ {documents.length === 0 && (
+ <p className="text-sm text-gray-500 mt-2">
+ Upload documents first to enable questions
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
+```
+
+## Testing Your Q&A System
+
+### Step 4: Test Document Processing
+
+1. **Upload Test Documents**:
+ - Upload a PDF manual or research paper
+ - Add a few web articles via URL
+ - Upload some text files with different topics
+
+2. **Test Question Types**:
+ ```
+ Factual: "What is the definition of X mentioned in the documents?"
+ Analytical: "What are the pros and cons of approach Y?"
+ Comparative: "How does method A compare to method B?"
+ Summarization: "Summarize the main findings"
+ ```
+
+3. **Verify Citations**:
+ - Check that citations appear in responses
+ - Verify citation numbers match source list
+ - Ensure sources show relevant metadata
+
+## Production Considerations
+
+### Performance Optimization
+
+```typescript
+// Implement caching for frequently asked questions
+const cacheKey = `qa:${collection}:${hashQuery(question)}`
+const cachedResponse = await redis.get(cacheKey)
+
+if (cachedResponse) {
+ return JSON.parse(cachedResponse)
+}
+
+// Cache response for 1 hour
+await redis.setex(cacheKey, 3600, JSON.stringify(response))
+```
+
+### Advanced Features
+
+1. **Follow-up Questions**:
+ ```typescript
+ // Track conversation context
+ const conversationHistory = messages.slice(-6) // Last 3 exchanges
+ ```
+
+2. **Answer Confidence Scoring**:
+ ```typescript
+ const confidence = calculateConfidence({
+ searchScore: searchResults.results[0]?.score || 0,
+ resultCount: searchResults.results.length,
+ chunkRelevance: avgChunkRelevance
+ })
+ ```
+
+3. **Multi-language Support**:
+ ```typescript
+ // Detect document language and adapt search
+ const detectedLanguage = await detectLanguage(question)
+ const searchResults = await client.search.documents({
+ q: question,
+ filters: {
+ AND: [{ key: 'language', value: detectedLanguage }]
+ }
+ })
+ ```
+
+This recipe provides a complete foundation for building document Q&A systems with accurate citations and source tracking.
+
+---
+
+*Customize this recipe based on your specific document types and use cases.* \ No newline at end of file
diff --git a/apps/docs/cookbook/inf-chat-blog.mdx b/apps/docs/cookbook/inf-chat-blog.mdx
new file mode 100644
index 00000000..f5c2fcbe
--- /dev/null
+++ b/apps/docs/cookbook/inf-chat-blog.mdx
@@ -0,0 +1,4 @@
+---
+title: "Extending context windows in LLMs"
+url: "https://supermemory.ai/blog/extending-context-windows-in-llms/"
+---
diff --git a/apps/docs/cookbook/overview.mdx b/apps/docs/cookbook/overview.mdx
new file mode 100644
index 00000000..be320f56
--- /dev/null
+++ b/apps/docs/cookbook/overview.mdx
@@ -0,0 +1,64 @@
+---
+title: "Cookbook"
+description: "Complete examples and recipes for building with Supermemory"
+sidebarTitle: "Overview"
+---
+
+The Supermemory Cookbook provides complete, production-ready examples that show how to build real applications with Supermemory. Each recipe includes full implementation details, best practices, and common patterns.
+
+## Available Recipes
+
+<CardGroup cols={2}>
+ <Card title="Personal AI Assistant" icon="bot" href="/cookbook/personal-assistant">
+ Build an AI assistant that remembers user preferences and context across conversations
+ </Card>
+
+ <Card title="Document Q&A System" icon="file-text" href="/cookbook/document-qa">
+ Create a chatbot that answers questions from your documents with citations
+ </Card>
+
+ <Card title="Customer Support Bot" icon="headphones" href="/cookbook/customer-support">
+ Build a support system that remembers customer history and provides personalized help
+ </Card>
+
+ <Card title="AI SDK Integration" icon="triangle" href="/cookbook/ai-sdk-integration">
+ Complete examples using Vercel AI SDK with Supermemory tools
+ </Card>
+</CardGroup>
+
+## Coming Soon
+
+We're working on more comprehensive recipes. Have a suggestion? [Let us know!](mailto:[email protected])
+
+<CardGroup cols={2}>
+ <Card title="Research Assistant" icon="search" color="#gray">
+ Organize and search through research papers and notes
+ </Card>
+
+ <Card title="Learning Platform" icon="users" color="#gray">
+ Build a personalized learning system with user isolation
+ </Card>
+
+ <Card title="Code Documentation Bot" icon="code" color="#gray">
+ Create an AI assistant for your codebase and documentation
+ </Card>
+
+ <Card title="Meeting Intelligence" icon="calendar" color="#gray">
+ Process and search through meeting recordings and notes
+ </Card>
+</CardGroup>
+
+
+## Getting Help
+
+Can't find what you're looking for?
+
+- Browse [Search Examples](/search/examples/document-search) for specific feature usage
+- Check the [AI SDK Examples](/cookbook/ai-sdk-integration) for complete implementations
+- Reach out to [support](mailto:[email protected]) for help
+
+## Contributing Recipes
+
+Have a great Supermemory use case? We'd love to add it to the cookbook!
+
+[Suggest a recipe →](mailto:[email protected]?subject=Cookbook%20Recipe%20Suggestion)
diff --git a/apps/docs/cookbook/perplexity-supermemory.mdx b/apps/docs/cookbook/perplexity-supermemory.mdx
new file mode 100644
index 00000000..04bf0f2a
--- /dev/null
+++ b/apps/docs/cookbook/perplexity-supermemory.mdx
@@ -0,0 +1,4 @@
+---
+title: "Perplexity with memory"
+url: "https://supermemory.ai/blog/build-your-own-perplexity-in-15-minutes-with-supermemory/"
+---
diff --git a/apps/docs/cookbook/personal-assistant.mdx b/apps/docs/cookbook/personal-assistant.mdx
new file mode 100644
index 00000000..edaeed83
--- /dev/null
+++ b/apps/docs/cookbook/personal-assistant.mdx
@@ -0,0 +1,770 @@
+---
+title: "Personal AI Assistant"
+description: "Build an AI assistant that remembers user preferences, habits, and context across conversations"
+---
+
+Build a personal AI assistant that learns and remembers everything about the user - their preferences, habits, work context, and conversation history. This recipe shows how to create a truly personalized AI experience using Supermemory's memory tools.
+
+## What You'll Build
+
+A personal AI assistant that:
+- **Remembers user preferences** (dietary restrictions, work schedule, communication style)
+- **Learns from conversations** and improves responses over time
+- **Maintains context** across multiple chat sessions
+- **Provides personalized recommendations** based on user history
+- **Handles multiple conversation topics** while maintaining context
+
+## Prerequisites
+
+- Node.js 18+ or Python 3.8+
+- Supermemory API key
+- OpenAI or Anthropic API key
+- Basic understanding of chat applications
+
+## Implementation
+
+### Step 1: Project Setup
+
+<Tabs>
+ <Tab title="Next.js (TypeScript)">
+ ```bash
+ npx create-next-app@latest personal-ai --typescript --tailwind --eslint
+ cd personal-ai
+ npm install @supermemory/tools ai openai
+ ```
+
+ Create your environment variables:
+ ```bash .env.local
+ SUPERMEMORY_API_KEY=your_supermemory_key
+ OPENAI_API_KEY=your_openai_key
+ ```
+ </Tab>
+
+ <Tab title="Python">
+ ```bash
+ mkdir personal-ai && cd personal-ai
+ python -m venv venv
+ source venv/bin/activate # On Windows: venv\Scripts\activate
+ pip install supermemory openai fastapi uvicorn python-multipart
+ ```
+
+ Create your environment variables:
+ ```bash .env
+ SUPERMEMORY_API_KEY=your_supermemory_key
+ OPENAI_API_KEY=your_openai_key
+ ```
+ </Tab>
+</Tabs>
+
+### Step 2: Core Assistant Logic
+
+<Tabs>
+ <Tab title="Next.js API Route">
+ ```typescript app/api/chat/route.ts
+ import { streamText } from 'ai'
+ import { createOpenAI } from '@ai-sdk/openai'
+ import { supermemoryTools } from '@supermemory/tools/ai-sdk'
+
+ const openai = createOpenAI({
+ apiKey: process.env.OPENAI_API_KEY!
+ })
+
+ export async function POST(request: Request) {
+ const { messages, userId = 'default-user' } = await request.json()
+
+ const result = await streamText({
+ model: openai('gpt-4-turbo'),
+ messages,
+ tools: supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
+ headers: {
+ 'x-sm-user-id': userId,
+ }
+ }),
+ system: `You are a highly personalized AI assistant. Your primary goal is to learn about the user and provide increasingly personalized help over time.
+
+ MEMORY MANAGEMENT:
+ 1. When users share personal information, preferences, or context, immediately use addMemory to store it
+ 2. Before responding to requests, search your memories for relevant context about the user
+ 3. Use past conversations to inform current responses
+ 4. Remember user's communication style, preferences, and frequently discussed topics
+
+ PERSONALITY:
+ - Adapt your communication style to match the user's preferences
+ - Reference past conversations naturally when relevant
+ - Proactively offer help based on learned patterns
+ - Be genuinely helpful while respecting privacy
+
+ EXAMPLES OF WHAT TO REMEMBER:
+ - Work schedule and role
+ - Dietary preferences/restrictions
+ - Communication preferences (formal/casual)
+ - Frequent topics of interest
+ - Goals and projects they're working on
+ - Family/personal context they share
+ - Preferred tools and workflows
+ - Time zone and availability
+
+ Always search memories before responding to provide personalized, contextual help.`
+ })
+
+ return result.toAIStreamResponse()
+ }
+ ```
+ </Tab>
+
+ <Tab title="Python FastAPI">
+ ```python main.py
+ from fastapi import FastAPI, HTTPException
+ from fastapi.responses import StreamingResponse
+ import openai
+ from supermemory import Supermemory
+ import json
+ import os
+ from typing import List, Dict, Any
+ import asyncio
+
+ app = FastAPI()
+
+ openai_client = openai.AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ supermemory_client = Supermemory(api_key=os.getenv("SUPERMEMORY_API_KEY"))
+
+ SYSTEM_PROMPT = """You are a highly personalized AI assistant. Your primary goal is to learn about the user and provide increasingly personalized help over time.
+
+ MEMORY MANAGEMENT:
+ 1. When users share personal information, preferences, or context, immediately store it
+ 2. Before responding to requests, search for relevant context about the user
+ 3. Use past conversations to inform current responses
+ 4. Remember user's communication style, preferences, and frequently discussed topics
+
+ PERSONALITY:
+ - Adapt your communication style to match the user's preferences
+ - Reference past conversations naturally when relevant
+ - Proactively offer help based on learned patterns
+ - Be genuinely helpful while respecting privacy
+
+ Always search memories before responding to provide personalized, contextual help."""
+
+ async def search_user_memories(query: str, user_id: str) -> str:
+ """Search user's memories for relevant context"""
+ try:
+ results = supermemory_client.search.memories(
+ q=query,
+ container_tag=f"user_{user_id}",
+ limit=5
+ )
+
+ if results.results:
+ context = "\n".join([r.memory for r in results.results])
+ return f"Relevant memories about the user:\n{context}"
+ return "No relevant memories found."
+ except Exception as e:
+ return f"Error searching memories: {e}"
+
+ async def add_user_memory(content: str, user_id: str):
+ """Add new information to user's memory"""
+ try:
+ supermemory_client.memories.add(
+ content=content,
+ container_tag=f"user_{user_id}",
+ metadata={"type": "personal_info", "timestamp": "auto"}
+ )
+ except Exception as e:
+ print(f"Error adding memory: {e}")
+
+ @app.post("/chat")
+ async def chat_endpoint(data: dict):
+ messages = data.get("messages", [])
+ user_id = data.get("userId", "default-user")
+
+ if not messages:
+ raise HTTPException(status_code=400, detail="No messages provided")
+
+ # Get user's last message for memory search
+ user_message = messages[-1]["content"] if messages else ""
+
+ # Search for relevant memories
+ memory_context = await search_user_memories(user_message, user_id)
+
+ # Add system message with memory context
+ enhanced_messages = [
+ {"role": "system", "content": f"{SYSTEM_PROMPT}\n\n{memory_context}"}
+ ] + messages
+
+ try:
+ response = await openai_client.chat.completions.create(
+ model="gpt-4-turbo",
+ messages=enhanced_messages,
+ stream=True,
+ temperature=0.7
+ )
+
+ async def generate():
+ full_response = ""
+ async for chunk in response:
+ if chunk.choices[0].delta.content:
+ content = chunk.choices[0].delta.content
+ full_response += content
+ yield f"data: {json.dumps({'content': content})}\n\n"
+
+ # After response is complete, analyze for memory-worthy content
+ if "remember" in user_message.lower() or any(word in user_message.lower() for word in ["prefer", "like", "dislike", "work", "schedule", "diet"]):
+ await add_user_memory(user_message, user_id)
+
+ return StreamingResponse(generate(), media_type="text/plain")
+
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+ if __name__ == "__main__":
+ import uvicorn
+ uvicorn.run(app, host="0.0.0.0", port=8000)
+ ```
+ </Tab>
+</Tabs>
+
+### Step 3: Frontend Interface
+
+<Tabs>
+ <Tab title="Next.js Chat Component">
+ ```tsx app/page.tsx
+ 'use client'
+
+ import { useChat } from 'ai/react'
+ import { useState, useEffect } from 'react'
+
+ export default function PersonalAssistant() {
+ const [userId, setUserId] = useState('')
+ const [userName, setUserName] = useState('')
+
+ const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
+ api: '/api/chat',
+ body: {
+ userId
+ }
+ })
+
+ // Generate or retrieve user ID
+ useEffect(() => {
+ const storedUserId = localStorage.getItem('personal-ai-user-id')
+ const storedUserName = localStorage.getItem('personal-ai-user-name')
+
+ if (storedUserId) {
+ setUserId(storedUserId)
+ setUserName(storedUserName || '')
+ } else {
+ const newUserId = `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
+ localStorage.setItem('personal-ai-user-id', newUserId)
+ setUserId(newUserId)
+ }
+ }, [])
+
+ const handleNameSubmit = (e: React.FormEvent) => {
+ e.preventDefault()
+ if (userName.trim()) {
+ localStorage.setItem('personal-ai-user-name', userName)
+ // Send introduction message
+ handleSubmit(e, {
+ data: {
+ content: `Hi! My name is ${userName}. I'm looking for a personal AI assistant that can learn about me and help me with various tasks.`
+ }
+ })
+ }
+ }
+
+ return (
+ <div className="flex flex-col h-screen max-w-4xl mx-auto p-4">
+ {/* Header */}
+ <div className="bg-gradient-to-r from-blue-500 to-purple-600 text-white p-6 rounded-lg mb-6">
+ <h1 className="text-2xl font-bold">Personal AI Assistant</h1>
+ <p className="text-blue-100">
+ {userName ? `Hello ${userName}!` : 'Your AI that learns and remembers'}
+ </p>
+ </div>
+
+ {/* Name Setup */}
+ {!userName && (
+ <div className="bg-white border border-gray-200 rounded-lg p-6 mb-6">
+ <form onSubmit={handleNameSubmit} className="flex gap-2">
+ <input
+ type="text"
+ value={userName}
+ onChange={(e) => setUserName(e.target.value)}
+ placeholder="What should I call you?"
+ className="flex-1 p-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
+ />
+ <button
+ type="submit"
+ className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+ Get Started
+ </button>
+ </form>
+ </div>
+ )}
+
+ {/* Messages */}
+ <div className="flex-1 overflow-y-auto space-y-4 mb-4">
+ {messages.length === 0 && userName && (
+ <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
+ <p className="text-gray-600">
+ Hi {userName}! I'm your personal AI assistant. I'll learn about your preferences,
+ work style, and interests as we chat. Feel free to share anything you'd like me to remember!
+ </p>
+ <div className="mt-3 text-sm text-gray-500">
+ <p><strong>Try saying:</strong></p>
+ <ul className="list-disc list-inside mt-1 space-y-1">
+ <li>"I work as a software engineer and prefer concise responses"</li>
+ <li>"Remember that I'm vegetarian and allergic to nuts"</li>
+ <li>"I usually work from 9-5 EST and take lunch at noon"</li>
+ </ul>
+ </div>
+ </div>
+ )}
+
+ {messages.map((message) => (
+ <div
+ key={message.id}
+ className={`p-4 rounded-lg ${
+ message.role === 'user'
+ ? 'bg-blue-500 text-white ml-auto max-w-2xl'
+ : 'bg-white border border-gray-200 max-w-2xl'
+ }`}
+ >
+ <div className="flex items-start space-x-2">
+ {message.role === 'assistant' && (
+ <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white text-sm font-bold">
+ AI
+ </div>
+ )}
+ <div className="flex-1">
+ <p className="whitespace-pre-wrap">{message.content}</p>
+ </div>
+ </div>
+ </div>
+ ))}
+
+ {isLoading && (
+ <div className="bg-white border border-gray-200 rounded-lg p-4 max-w-2xl">
+ <div className="flex items-center space-x-2">
+ <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white text-sm font-bold">
+ AI
+ </div>
+ <div className="flex space-x-1">
+ <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
+ <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></div>
+ <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Input */}
+ {userName && (
+ <form onSubmit={handleSubmit} className="flex gap-2">
+ <input
+ value={input}
+ onChange={handleInputChange}
+ placeholder="Tell me something about yourself, or ask for help..."
+ className="flex-1 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
+ disabled={isLoading}
+ />
+ <button
+ type="submit"
+ disabled={isLoading || !input.trim()}
+ className="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ Send
+ </button>
+ </form>
+ )}
+ </div>
+ )
+ }
+ ```
+ </Tab>
+
+ <Tab title="Python Streamlit">
+ ```python streamlit_app.py
+ import streamlit as st
+ import requests
+ import json
+ import uuid
+
+ st.set_page_config(page_title="Personal AI Assistant", page_icon="🤖", layout="wide")
+
+ # Initialize session state
+ if 'messages' not in st.session_state:
+ st.session_state.messages = []
+ if 'user_id' not in st.session_state:
+ st.session_state.user_id = f"user_{uuid.uuid4().hex[:8]}"
+ if 'user_name' not in st.session_state:
+ st.session_state.user_name = None
+
+ # Header
+ st.title("🤖 Personal AI Assistant")
+ st.markdown("*Your AI that learns and remembers*")
+
+ # Sidebar for user info
+ with st.sidebar:
+ st.header("👤 User Profile")
+
+ if not st.session_state.user_name:
+ name = st.text_input("What should I call you?")
+ if st.button("Get Started") and name:
+ st.session_state.user_name = name
+ st.session_state.messages.append({
+ "role": "user",
+ "content": f"Hi! My name is {name}. I'm looking for a personal AI assistant."
+ })
+ st.rerun()
+ else:
+ st.write(f"**Name:** {st.session_state.user_name}")
+ st.write(f"**User ID:** {st.session_state.user_id[:12]}...")
+
+ if st.button("Reset Conversation"):
+ st.session_state.messages = []
+ st.rerun()
+
+ st.markdown("---")
+ st.markdown("""
+ ### 💡 Try saying:
+ - "I work as a software engineer and prefer concise responses"
+ - "Remember that I'm vegetarian"
+ - "I usually work from 9-5 EST"
+ """)
+
+ # Main chat interface
+ if st.session_state.user_name:
+ # Display messages
+ for message in st.session_state.messages:
+ with st.chat_message(message["role"]):
+ st.markdown(message["content"])
+
+ # Chat input
+ if prompt := st.chat_input("Tell me something about yourself, or ask for help..."):
+ # Add user message
+ st.session_state.messages.append({"role": "user", "content": prompt})
+
+ with st.chat_message("user"):
+ st.markdown(prompt)
+
+ # Get AI response
+ with st.chat_message("assistant"):
+ with st.spinner("Thinking..."):
+ try:
+ response = requests.post(
+ "http://localhost:8000/chat",
+ json={
+ "messages": st.session_state.messages,
+ "userId": st.session_state.user_id
+ },
+ timeout=30
+ )
+
+ if response.status_code == 200:
+ # Handle streaming response
+ full_response = ""
+ for line in response.iter_lines():
+ if line:
+ try:
+ data = json.loads(line.decode('utf-8').replace('data: ', ''))
+ if 'content' in data:
+ full_response += data['content']
+ except:
+ continue
+
+ st.markdown(full_response)
+ st.session_state.messages.append({
+ "role": "assistant",
+ "content": full_response
+ })
+ else:
+ st.error(f"Error: {response.status_code}")
+ except Exception as e:
+ st.error(f"Connection error: {e}")
+
+ else:
+ st.info("👆 Please enter your name in the sidebar to get started!")
+
+ # Run with: streamlit run streamlit_app.py
+ ```
+ </Tab>
+</Tabs>
+
+## Testing Your Assistant
+
+### Step 4: Test Memory Formation
+
+Try these conversation flows to test memory capabilities:
+
+1. **Personal Preferences**:
+ ```
+ User: "Hi! I'm Sarah, a product manager at a tech startup. I prefer brief, actionable responses and I'm always busy with user research."
+
+ Assistant: [Should remember name, role, communication preference]
+
+ User: "What's a good way to prioritize features?"
+
+ Assistant: [Should reference that you're a PM and prefer brief responses]
+ ```
+
+2. **Dietary & Lifestyle**:
+ ```
+ User: "Remember that I'm vegan and I work out every morning at 6 AM."
+
+ User: "Suggest a quick breakfast for tomorrow."
+
+ Assistant: [Should suggest vegan options that work for pre/post workout]
+ ```
+
+3. **Work Context**:
+ ```
+ User: "I'm working on a React project and I prefer TypeScript over JavaScript."
+
+ User: "Help me with state management."
+
+ Assistant: [Should suggest TypeScript-specific solutions]
+ ```
+
+### Step 5: Verify Memory Storage
+
+Check that memories are being stored properly:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript scripts/check-memories.ts
+ import { Supermemory } from '@supermemory/tools'
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ })
+
+ async function checkUserMemories(userId: string) {
+ try {
+ const memories = await client.memories.list({
+ containerTags: [userId],
+ limit: 20,
+ sort: 'updatedAt',
+ order: 'desc'
+ })
+
+ console.log(`Found ${memories.memories.length} memories for ${userId}:`)
+ memories.memories.forEach((memory, i) => {
+ console.log(`${i + 1}. ${memory.content.substring(0, 100)}...`)
+ })
+
+ // Test search
+ const searchResults = await client.search.memories({
+ q: "preferences work",
+ containerTag: userId,
+ limit: 5
+ })
+
+ console.log('\nSearch Results:')
+ searchResults.results.forEach((result, i) => {
+ console.log(`${i + 1}. (${result.similarity}) ${result.memory.substring(0, 100)}...`)
+ })
+
+ } catch (error) {
+ console.error('Error:', error)
+ }
+ }
+
+ // Run: npx ts-node scripts/check-memories.ts USER_ID_HERE
+ checkUserMemories(process.argv[2] || 'default-user')
+ ```
+ </Tab>
+
+ <Tab title="Python">
+ ```python check_memories.py
+ from supermemory import Supermemory
+ import os
+ import sys
+
+ client = Supermemory(api_key=os.getenv("SUPERMEMORY_API_KEY"))
+
+ def check_user_memories(user_id):
+ try:
+ # List all memories for user
+ memories = client.memories.list(
+ container_tags=[user_id],
+ limit=20,
+ sort="updatedAt",
+ order="desc"
+ )
+
+ print(f"Found {len(memories.memories)} memories for {user_id}:")
+ for i, memory in enumerate(memories.memories):
+ print(f"{i + 1}. {memory.content[:100]}...")
+
+ # Test search
+ search_results = client.search.memories(
+ q="preferences work",
+ container_tag=user_id,
+ limit=5
+ )
+
+ print('\nSearch Results:')
+ for i, result in enumerate(search_results.results):
+ print(f"{i + 1}. ({result.similarity}) {result.memory[:100]}...")
+
+ except Exception as error:
+ print(f'Error: {error}')
+
+ # Run: python check_memories.py USER_ID_HERE
+ user_id = sys.argv[1] if len(sys.argv) > 1 else 'default-user'
+ check_user_memories(user_id)
+ ```
+ </Tab>
+</Tabs>
+
+## Production Considerations
+
+### Security & Privacy
+
+1. **User Isolation**:
+ ```typescript
+ // Always use user-specific container tags
+ const tools = supermemoryTools(apiKey, {
+ headers: {
+ 'x-sm-user-id': userId
+ }
+ })
+ ```
+
+2. **Memory Encryption**:
+ ```typescript
+ // For sensitive data, consider client-side encryption
+ const encryptedContent = encrypt(sensitiveData, userKey)
+ await client.memories.add({
+ content: encryptedContent,
+ containerTag: userId,
+ metadata: { encrypted: true }
+ })
+ ```
+
+### Performance Optimization
+
+1. **Memory Search Optimization**:
+ ```typescript
+ // Use appropriate thresholds for speed vs accuracy
+ const quickSearch = await client.search.memories({
+ q: userQuery,
+ containerTag: userId,
+ threshold: 0.6, // Balanced
+ rerank: false, // Skip for speed
+ limit: 3 // Fewer results
+ })
+ ```
+
+2. **Caching Strategy**:
+ ```typescript
+ // Cache frequently accessed user context
+ const userContext = await redis.get(`user_context:${userId}`)
+ if (!userContext) {
+ const memories = await client.search.memories({
+ q: "user preferences work style",
+ containerTag: userId,
+ limit: 10
+ })
+ await redis.setex(`user_context:${userId}`, 300, JSON.stringify(memories))
+ }
+ ```
+
+### Monitoring & Analytics
+
+```typescript
+// Track memory formation and retrieval
+const analytics = {
+ memoriesCreated: await redis.incr(`memories_created:${userId}`),
+ searchesPerformed: await redis.incr(`searches:${userId}`),
+ conversationLength: messages.length
+}
+
+// Log for analysis
+console.log('User Interaction:', {
+ userId,
+ action: 'chat_response',
+ memoriesFound: searchResults.results.length,
+ responseTime: Date.now() - startTime,
+ ...analytics
+})
+```
+
+## Extensions & Customization
+
+### 1. Add Personality Profiles
+
+```typescript
+const personalityProfiles = {
+ professional: "Respond in a formal, business-appropriate tone",
+ casual: "Use a friendly, conversational tone with occasional humor",
+ technical: "Provide detailed technical explanations with examples",
+ concise: "Keep responses brief and to the point"
+}
+
+// Add to system prompt based on user preference
+const userProfile = await getUserProfile(userId)
+const systemPrompt = `${basePrompt}\n\nCommunication Style: ${personalityProfiles[userProfile.style]}`
+```
+
+### 2. Smart Notifications
+
+```typescript
+// Proactive suggestions based on user patterns
+const shouldSuggest = await analyzeUserPatterns(userId)
+if (shouldSuggest.type === 'daily_standup') {
+ return {
+ message: "Based on your schedule, would you like me to help prepare for your 9 AM standup?",
+ suggestedActions: ["Review yesterday's progress", "Prepare today's goals"]
+ }
+}
+```
+
+### 3. Multi-Modal Memory
+
+```typescript
+// Handle images and documents
+if (message.attachments) {
+ for (const attachment of message.attachments) {
+ await client.memories.uploadFile({
+ file: attachment,
+ containerTag: userId,
+ metadata: {
+ type: 'user_shared',
+ context: message.content
+ }
+ })
+ }
+}
+```
+
+## Next Steps
+
+- **Scale to multiple users**: Add user authentication and proper isolation
+- **Add voice interaction**: Integrate with speech-to-text/text-to-speech APIs
+- **Mobile app**: Create React Native or Flutter mobile version
+- **Integrations**: Connect to calendar, email, task management tools
+- **Advanced AI features**: Add emotion detection, conversation summarization
+
+## Troubleshooting
+
+**Memory not persisting?**
+- Check that `x-sm-user-id` header is consistent
+- Verify API key has write permissions
+- Ensure container tags are properly set
+
+**Responses not personalized?**
+- Increase search limit to find more relevant memories
+- Lower threshold to cast a wider net
+- Check that memories are being added with proper context
+
+**Performance issues?**
+- Reduce search limits for faster responses
+- Implement caching for frequent searches
+- Use appropriate thresholds to balance speed vs accuracy
+
+---
+
+*This recipe provides the foundation for a personal AI assistant. Customize it based on your specific needs and use cases.*
diff --git a/apps/docs/deployment/self-hosting.mdx b/apps/docs/deployment/self-hosting.mdx
new file mode 100644
index 00000000..7f7db4d3
--- /dev/null
+++ b/apps/docs/deployment/self-hosting.mdx
@@ -0,0 +1,243 @@
+---
+title: 'Self Hosting'
+description: 'Deploy your own instance of the supermemory API on Cloudflare Workers'
+---
+
+<Warning>
+This guide is intended for **enterprise customers only** who have specifically opted for self-hosting as part of their enterprise plan. If you're on a standard plan, please use our hosted API at [console.supermemory.ai](https://console.supermemory.ai).
+</Warning>
+
+## Prerequisites
+
+Before you start, you'll need to gather several API keys and set up accounts with various services. This comprehensive guide will walk you through obtaining each required component.
+
+### Enterprise Deployment Package
+
+Your enterprise deployment package is provided by the supermemory team and contains:
+- Your unique Host ID (`NEXT_PUBLIC_HOST_ID`)
+- The compiled JavaScript bundle
+- The deployment script
+
+Contact your supermemory enterprise representative to receive your deployment package.
+
+### Cloudflare
+
+
+#### Create Account
+
+1. Go to [cloudflare.com](https://dash.cloudflare.com/sign-up) and create an account
+3. Your **Account ID** is the long randon string in the URL bar
+
+#### Create API Token
+
+1. Navigate to [Cloudflare API Tokens](https://dash.cloudflare.com/?to=/:account/api-tokens)
+2. Click **"Create Token"**
+3. Use the **"Custom token"** template
+4. Configure the token with these permissions:
+ - **Account:AI Gateway:Edit**
+ - **Account:Hyperdrive:Edit**
+ - **Account:Workers KV Storage:Edit**
+ - **Account:Workers R2 Storage:Edit**
+7. Click **"Continue to summary"** → **"Create Token"**
+8. **Important**: Copy and securely store the token immediately (it won't be shown again)
+
+#### Enable Workers
+
+1. In your Cloudflare dashboard, go to **Workers & Pages**
+2. If prompted, accept the Workers terms of service
+3. Choose a subdomain for your workers (e.g., `yourcompany.workers.dev`)
+
+Your `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` are now ready.
+
+### Database
+
+You'll need to provide a PostgreSQL connection string via the `DATABASE_URL` environment variable.
+
+The database must:
+- Support the **pgvector extension** for vector operations
+- Be accessible from Cloudflare Workers
+- Support SSL connections
+- Allow connections from Cloudflare's IP ranges
+
+Your connection string should follow this format:
+```
+postgresql://username:password@hostname:port/database
+```
+
+### LLM Providers
+
+#### OpenAI
+
+1. Go to [platform.openai.com](https://platform.openai.com)
+2. Sign in or create an account
+3. Navigate to **API Keys** in the left sidebar
+4. Click **"Create new secret key"**
+5. Name your key (e.g., "supermemory Self-Hosted")
+6. Copy the key and store it securely
+7. Add billing information if you haven't already
+
+#### Anthropic
+
+1. Go to [console.anthropic.com](https://console.anthropic.com)
+2. Create an account and complete verification
+3. Navigate to **API Keys**
+4. Click **"Create Key"**
+5. Name your key and copy it securely
+
+#### Gemini
+
+1. Go to [Google AI Studio](https://aistudio.google.com)
+2. Sign in with your Google account
+3. Click **"Get API key"** → **"Create API key"**
+4. Choose an existing Google Cloud project or create a new one
+5. Copy your API key
+
+#### Groq
+
+1. Go to [console.groq.com](https://console.groq.com)
+2. Sign up for an account
+3. Navigate to **API Keys**
+4. Click **"Create API Key"**
+5. Name your key and copy it
+
+
+
+{/* TODO: Add OAuth documentation */}
+{/* ### Authentication Providers
+#### GitHub OAuth (Optional)
+
+1. Go to [GitHub Developer Settings](https://github.com/settings/developers)
+2. Click **"New OAuth App"**
+3. Fill in the application details:
+ - **Application name**: Your app name
+ - **Homepage URL**: Your API domain (e.g., `https://api.yourdomain.com`)
+ - **Authorization callback URL**: `https://api.yourdomain.com/api/auth/callback/github`
+4. Click **"Register application"**
+5. Note the **Client ID** and generate a **Client Secret**
+6. Use these for `AUTH_GITHUB_ID` and `AUTH_GITHUB_SECRET`
+
+#### Google OAuth (Optional)
+
+1. Go to [Google Cloud Console](https://console.cloud.google.com)
+2. Create a new project or select an existing one
+3. Enable the **Google+ API**
+4. Go to **Credentials** → **Create Credentials** → **OAuth client ID**
+5. Choose **Web application**
+6. Add your domain to **Authorized JavaScript origins**
+7. Add `https://api.yourdomain.com/api/auth/callback/google` to **Authorized redirect URIs**
+8. Copy the **Client ID** and **Client secret**
+9. Use these for `AUTH_GOOGLE_ID` and `AUTH_GOOGLE_SECRET` */}
+
+### Email Service Setup
+
+#### Resend
+
+1. Go to [resend.com](https://resend.com) and create an account
+2. Navigate to **API Keys**
+3. Click **"Create API Key"**
+4. Name your key (e.g., "supermemory Production")
+5. Copy the key for `RESEND_API_KEY`
+6. Verify your sending domain in the **Domains** section
+
+### Connectors (Optional)
+
+#### Google Drive
+
+1. Go to [Google Cloud Console](https://console.cloud.google.com)
+2. Create or select a project
+3. Enable the **Google Drive API**
+4. Go to **Credentials** → **Create Credentials** → **OAuth client ID**
+5. Configure the OAuth consent screen if required
+6. Choose **Web application**
+7. Add authorized redirect URIs for your domain
+8. Copy `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`
+
+#### Microsoft OneDrive
+
+1. Go to [Azure Portal](https://portal.azure.com)
+2. Navigate to **Microsoft Entra ID** → **App registrations**
+3. Click **"New registration"**
+4. Name your app and set redirect URI
+5. Go to **Certificates & secrets** → **New client secret**
+6. Copy the **Application (client) ID** and **Client secret**
+7. Use for `MICROSOFT_CLIENT_ID` and `MICROSOFT_CLIENT_SECRET`
+
+#### Notion
+
+1. Go to [Notion Developers](https://developers.notion.com)
+2. Click **"Create new integration"**
+3. Fill in the integration details
+4. Copy the **Internal Integration Token**
+5. Set up OAuth if needed for user connections
+6. Use for `NOTION_CLIENT_ID` and `NOTION_CLIENT_SECRET`
+
+---
+
+## Setup deployment files
+
+Extract the deployment package provided by the supermemory team to your preferred directory:
+
+```bash
+# Extract the deployment package
+$ unzip supermemory-enterprise-deployment.zip
+$ cd supermemory-deployment
+```
+
+---
+
+## Configure environment variables
+
+The deployment script reads **all** environment variables from your shell at runtime. We ship an example file that lists the full set supported by the worker.
+
+```bash
+# Copy the template and start editing
+$ cp packages/alchemy/env.example .env
+
+# Open the file in your editor of choice and fill in the blanks
+$ $EDITOR .env
+```
+
+Below is a quick reference.
+**Required** values are mandatory for a successful deploy – leave optional ones empty if you don't need the related feature.
+
+| Name | Required? | Description |
+|------|-----------|-------------|
+| `NODE_ENV` | ✅ | `development`, `staging` or `production`. |
+| `NEXT_PUBLIC_HOST_ID` | ✅ | Your unique Host ID provided by the supermemory team. |
+| `BETTER_AUTH_SECRET` | ✅ | Random 32-byte string – run `openssl rand -base64 32`. |
+| `BETTER_AUTH_URL` | ✅ | Public base URL for the API (no trailing `/`). Example: `https://api.example.com`. |
+| `DATABASE_URL` | ✅ | Postgres connection string (e.g. `postgres://user:pass@host:5432/db`). |
+| `CLOUDFLARE_ACCOUNT_ID` | ✅ | Your Cloudflare account ID. |
+| `CLOUDFLARE_API_TOKEN` | ✅ | Token created in *Prerequisites*. |
+| `OPENAI_API_KEY` | ✅ | Key from [platform.openai.com](https://platform.openai.com). |
+| `RESEND_API_KEY` | ✅ | E-mail provider key if you plan to send e-mails. |
+| `ANTHROPIC_API_KEY` | | Needed to use Claude models. |
+| `GEMINI_API_KEY` | | Key for Google Gemini models. |
+| `GROQ_API_KEY` | | Key for Groq models. |
+| `AUTH_GITHUB_ID` / `AUTH_GITHUB_SECRET` | | Enable GitHub OAuth login. |
+| `AUTH_GOOGLE_ID` / `AUTH_GOOGLE_SECRET` | | Enable Google OAuth login. |
+| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | | Needed for Google Drive connector. |
+| `MICROSOFT_CLIENT_ID` / `MICROSOFT_CLIENT_SECRET` | | Needed for OneDrive connector. |
+| `NOTION_CLIENT_ID` / `NOTION_CLIENT_SECRET` | | Needed for Notion connector. |
+| `CLOUDFLARE_AI_GATEWAY_NAME` / `CLOUDFLARE_AI_GATEWAY_TOKEN` | | Only if you want to route requests through an AI Gateway. |
+| `SENTRY_DSN` | | If you use Sentry for error reporting. |
+
+---
+
+## Deploy
+
+With your `.env` in place, run the deployment script:
+
+```bash
+# Run the deployment script provided in your package
+$ bun ./deploy.ts
+```
+
+
+---
+
+## Updating Your Deployment
+
+To update your supermemory deployment, follow the same process as the initial deployment described in the **Deploy** section above. You can reuse your existing `.env` file and add/remove any new environment variables as needed.
+
+--- \ No newline at end of file
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
new file mode 100644
index 00000000..92bbabee
--- /dev/null
+++ b/apps/docs/docs.json
@@ -0,0 +1,260 @@
+{
+ "$schema": "https://mintlify.com/docs.json",
+ "api": {
+ "examples": {
+ "defaults": "required",
+ "languages": ["javascript", "python", "curl"]
+ },
+ "openapi": "https://api.supermemory.ai/v3/openapi"
+ },
+ "colors": {
+ "dark": "#1E3A8A",
+ "light": "#3B82F6",
+ "primary": "#1E3A8A"
+ },
+ "contextual": {
+ "options": ["copy", "view", "chatgpt", "claude"]
+ },
+ "favicon": "/favicon.png",
+ "fonts": {
+ "body": {
+ "family": "Space Grotesk",
+ "format": "woff2"
+ },
+ "heading": {
+ "family": "Space Grotesk",
+ "format": "woff2"
+ }
+ },
+ "footer": {
+ "socials": {
+ "github": "https://github.com/supermemoryai",
+ "linkedin": "https://linkedin.com/company/supermemoryai",
+ "x": "https://x.com/supermemoryai"
+ }
+ },
+ "icons": { "library": "lucide" },
+ "logo": {
+ "dark": "/logo/dark.svg",
+ "light": "/logo/light.svg"
+ },
+ "name": "supermemory | Memory API for the AI era",
+ "navbar": {
+ "links": [
+ {
+ "href": "mailto:[email protected]",
+ "label": "Support"
+ }
+ ],
+ "primary": {
+ "href": "https://console.supermemory.ai",
+ "label": "Dashboard",
+ "type": "button"
+ }
+ },
+ "navigation": {
+ "tabs": [
+ {
+ "pages": ["introduction"],
+ "tab": "Welcome"
+ },
+ {
+ "icon": "code",
+ "anchors": [
+ {
+ "anchor": "Your Dashboard",
+ "href": "https://console.supermemory.ai",
+ "icon": "play"
+ },
+ {
+ "anchor": "Developer Platform",
+ "pages": [
+ {
+ "group": "Getting Started",
+ "pages": ["intro", "routervsapi", "quickstart"]
+ },
+ {
+ "group": "Memory API",
+ "pages": [
+ "how-it-works",
+ {
+ "group": "Add Memories",
+ "icon": "plus",
+ "pages": [
+ "add-memories/overview",
+ "add-memories/parameters",
+ "memory-api/ingesting",
+ {
+ "group": "Examples",
+ "pages": [
+ "add-memories/examples/basic",
+ "add-memories/examples/file-upload"
+ ]
+ }
+ ]
+ },
+ {
+ "group": "Search Memories",
+ "icon": "search",
+ "pages": [
+ "search/overview",
+ "search/parameters",
+ "search/response-schema",
+ "search/query-rewriting",
+ "search/reranking",
+ {
+ "group": "Examples",
+ "pages": [
+ "search/examples/document-search",
+ "search/examples/memory-search"
+ ]
+ }
+ ]
+ },
+ "search/filtering",
+ "memory-api/track-progress",
+ {
+ "group": "List Memories",
+ "icon": "list",
+ "pages": [
+ "list-memories/overview",
+ {
+ "group": "Examples",
+ "pages": [
+ "list-memories/examples/basic",
+ "list-memories/examples/filtering",
+ "list-memories/examples/pagination",
+ "list-memories/examples/monitoring"
+ ]
+ }
+ ]
+ },
+ "update-delete-memories/overview",
+ {
+ "group": "Connectors",
+ "icon": "link",
+ "pages": [
+ "connectors/overview",
+ "connectors/notion",
+ "connectors/google-drive",
+ "connectors/onedrive",
+ "connectors/troubleshooting"
+ ]
+ },
+ "/org-settings",
+ "/analytics",
+ "overview/use-cases"
+ ]
+ },
+ {
+ "group": "Memory Router",
+ "icon": "route",
+ "pages": [
+ "memory-router/overview",
+ "memory-router/usage",
+ "memory-router/with-memory-api"
+ ]
+ },
+ {
+ "group": "Deployment",
+ "pages": ["deployment/self-hosting"]
+ }
+ ]
+ }
+ ],
+ "tab": "Developer Platform"
+ },
+ {
+ "icon": "plug",
+ "anchors": [
+ {
+ "anchor": "SDKs",
+ "pages": [
+ "memory-api/sdks/overview",
+ {
+ "group": "Supermemory SDKs",
+ "pages": [
+ "memory-api/sdks/native",
+ "memory-api/sdks/supermemory-npm",
+ "memory-api/sdks/supermemory-pypi"
+ ]
+ },
+ {
+ "group": "OpenAI SDK",
+ "icon": "sparkles",
+ "pages": ["memory-api/sdks/openai-plugins", "ai-sdk/npm"]
+ },
+ {
+ "group": "AI SDK",
+ "icon": "triangle",
+ "pages": [
+ "ai-sdk/overview",
+ "ai-sdk/memory-tools",
+ "ai-sdk/infinite-chat",
+ "ai-sdk/npm"
+ ]
+ }
+ ]
+ }
+ ],
+ "tab": "SDKs"
+ },
+ {
+ "icon": "book-open",
+ "anchors": [
+ {
+ "anchor": "API Reference",
+ "icon": "unplug",
+ "openapi": "https://api.supermemory.ai/v3/openapi"
+ }
+ ],
+ "tab": "API Reference"
+ },
+ {
+ "icon": "chef-hat",
+ "anchors": [
+ {
+ "anchor": "Cookbook",
+ "icon": "chef-hat",
+ "pages": [
+ "cookbook/overview",
+ {
+ "group": "Quick Start Recipes",
+ "pages": [
+ "cookbook/personal-assistant",
+ "cookbook/document-qa",
+ "cookbook/customer-support",
+ "cookbook/ai-sdk-integration",
+ "cookbook/perplexity-supermemory",
+ "cookbook/chat-with-gdrive",
+ "cookbook/inf-chat-blog"
+ ]
+ }
+ ]
+ }
+ ],
+ "tab": "Cookbook"
+ },
+
+ {
+ "icon": "list-ordered",
+ "anchors": [
+ {
+ "anchor": "Changelog",
+ "pages": ["changelog/overview", "changelog/developer-platform"]
+ }
+ ],
+ "tab": "Changelog"
+ }
+ ]
+ },
+ "redirects": [
+ {
+ "destination": "/introduction",
+ "permanent": false,
+ "source": "/"
+ }
+ ],
+ "styling": { "eyebrows": "breadcrumbs" },
+ "theme": "mint"
+}
diff --git a/apps/docs/favicon.png b/apps/docs/favicon.png
new file mode 100644
index 00000000..4c3dd878
--- /dev/null
+++ b/apps/docs/favicon.png
Binary files differ
diff --git a/apps/docs/how-it-works.mdx b/apps/docs/how-it-works.mdx
new file mode 100644
index 00000000..318324b1
--- /dev/null
+++ b/apps/docs/how-it-works.mdx
@@ -0,0 +1,152 @@
+---
+title: "How Supermemory Works"
+description: "Understanding the knowledge graph architecture that powers intelligent memory"
+icon: "brain"
+---
+
+
+Supermemory isn't just another document storage system. It's designed to mirror how human memory actually works - forming connections, evolving over time, and generating insights from accumulated knowledge.
+
+![](/images/graph-view.png)
+
+## The Mental Model
+
+Traditional systems store files. Supermemory creates a living knowledge graph.
+
+<CardGroup cols={2}>
+ <Card title="Traditional Systems" icon="folder">
+ - Static files in folders
+ - No connections between content
+ - Search matches keywords
+ - Information stays frozen
+ </Card>
+
+ <Card title="Supermemory" icon="network">
+ - Dynamic knowledge graph
+ - Rich relationships between memories
+ - Semantic understanding
+ - Information evolves and connects
+ </Card>
+</CardGroup>
+
+## Documents vs Memories
+
+Understanding this distinction is crucial to using Supermemory effectively.
+
+### Documents: Your Raw Input
+
+Documents are what you provide - the raw materials:
+- PDF files you upload
+- Web pages you save
+- Text you paste
+- Images with text
+- Videos to transcribe
+
+Think of documents as books you hand to Supermemory.
+
+### Memories: Intelligent Knowledge Units
+
+Memories are what Supermemory creates - the understanding:
+- Semantic chunks with meaning
+- Embedded for similarity search
+- Connected through relationships
+- Dynamically updated over time
+
+Think of memories as the insights and connections your brain makes after reading those books.
+
+<Note>
+**Key Insight**: When you upload a 50-page PDF, Supermemory doesn't just store it. It breaks it into hundreds of interconnected memories, each understanding its context and relationships to your other knowledge.
+</Note>
+
+
+## Memory Relationships
+
+![](/images/memories-inferred.png)
+
+The graph connects memories through three types of relationships:
+
+### Updates: Information Changes
+
+When new information contradicts or updates existing knowledge, Supermemory creates an "update" relationship.
+
+<CodeGroup>
+```text Original Memory
+"You work at Supermemory as a content engineer"
+```
+
+```text New Memory (Updates Original)
+"You now work at Supermemory as the CMO"
+```
+</CodeGroup>
+
+The system tracks which memory is latest with an `isLatest` field, ensuring searches return current information.
+
+### Extends: Information Enriches
+
+When new information adds to existing knowledge without replacing it, Supermemory creates an "extends" relationship.
+
+Continuing our "working at supermemory" analogy, a memory about what you work on would extend the memory about your role given above.
+
+<CodeGroup>
+```text Original Memory
+"You work at Supermemory as the CMO"
+```
+
+```text New Memory (Extension) - Separate From Previous
+"Your work consists of ensuring the docs are up to date, making marketing campaigns, SEO, etc."
+```
+</CodeGroup>
+
+Both memories remain valid and searchable, providing richer context.
+
+### Derives: Information Infers
+
+The most sophisticated relationship - when Supermemory infers new connections from patterns in your knowledge.
+
+<CodeGroup>
+```text Memory 1
+"Dhravya is the founder of Supermemory"
+```
+
+```text Memory 2
+"Dhravya frequently discusses AI and machine learning innovations"
+```
+
+```text Derived Memory
+"Supermemory is likely an AI-focused company"
+```
+</CodeGroup>
+
+These inferences help surface insights you might not have explicitly stated.
+
+## Processing Pipeline
+
+Understanding the pipeline helps you optimize your usage:
+
+| Stage | What Happens |
+|-------|-------------|
+| **Queued** | Document waiting to process
+| **Extracting** | Content being extracted |
+| **Chunking** | Creating memory chunks |
+| **Embedding** | Generating vectors |
+| **Indexing** | Building relationships |
+| **Done** | Fully searchable |
+
+<Note>
+**Tip**: Larger documents and videos take longer. A 100-page PDF might take 1-2 minutes, while a 1-hour video could take 5-10 minutes.
+</Note>
+
+
+## Next Steps
+
+Now that you understand how Supermemory works:
+
+<CardGroup cols={2}>
+ <Card title="Add Memories" icon="plus" href="/add-memories/overview">
+ Start adding content to your knowledge graph
+ </Card>
+
+ <Card title="Search Memories" icon="search" href="/search/overview">
+ Learn to query your knowledge effectively
+ </Card>
+</CardGroup>
diff --git a/apps/docs/images/Screenshot 2025-06-19 at 3.50.20 PM.png b/apps/docs/images/Screenshot 2025-06-19 at 3.50.20 PM.png
new file mode 100644
index 00000000..4e110427
--- /dev/null
+++ b/apps/docs/images/Screenshot 2025-06-19 at 3.50.20 PM.png
Binary files differ
diff --git a/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (2).png b/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (2).png
new file mode 100644
index 00000000..12141246
--- /dev/null
+++ b/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (2).png
Binary files differ
diff --git a/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (3).png b/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (3).png
new file mode 100644
index 00000000..a278db3e
--- /dev/null
+++ b/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (3).png
Binary files differ
diff --git a/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM.png b/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM.png
new file mode 100644
index 00000000..7b265488
--- /dev/null
+++ b/apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM.png
Binary files differ
diff --git a/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (2).png b/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (2).png
new file mode 100644
index 00000000..12141246
--- /dev/null
+++ b/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (2).png
Binary files differ
diff --git a/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (3).png b/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (3).png
new file mode 100644
index 00000000..a278db3e
--- /dev/null
+++ b/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (3).png
Binary files differ
diff --git a/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM.png b/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM.png
new file mode 100644
index 00000000..4c853197
--- /dev/null
+++ b/apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM.png
Binary files differ
diff --git a/apps/docs/images/connectors-flow.png b/apps/docs/images/connectors-flow.png
new file mode 100644
index 00000000..bcee681c
--- /dev/null
+++ b/apps/docs/images/connectors-flow.png
Binary files differ
diff --git a/apps/docs/images/create-api.png b/apps/docs/images/create-api.png
new file mode 100644
index 00000000..41af061f
--- /dev/null
+++ b/apps/docs/images/create-api.png
Binary files differ
diff --git a/apps/docs/images/dev-platform-api-keys.png b/apps/docs/images/dev-platform-api-keys.png
new file mode 100644
index 00000000..011689ca
--- /dev/null
+++ b/apps/docs/images/dev-platform-api-keys.png
Binary files differ
diff --git a/apps/docs/images/dev-platform-copy-key.png b/apps/docs/images/dev-platform-copy-key.png
new file mode 100644
index 00000000..5e9039cb
--- /dev/null
+++ b/apps/docs/images/dev-platform-copy-key.png
Binary files differ
diff --git a/apps/docs/images/dev-platform-create-key.png b/apps/docs/images/dev-platform-create-key.png
new file mode 100644
index 00000000..84df9637
--- /dev/null
+++ b/apps/docs/images/dev-platform-create-key.png
Binary files differ
diff --git a/apps/docs/images/dev-platform-login.png b/apps/docs/images/dev-platform-login.png
new file mode 100644
index 00000000..1ab67e4f
--- /dev/null
+++ b/apps/docs/images/dev-platform-login.png
Binary files differ
diff --git a/apps/docs/images/doc-to-memory-process.png b/apps/docs/images/doc-to-memory-process.png
new file mode 100644
index 00000000..b0ffbc50
--- /dev/null
+++ b/apps/docs/images/doc-to-memory-process.png
Binary files differ
diff --git a/apps/docs/images/graph-view.png b/apps/docs/images/graph-view.png
new file mode 100644
index 00000000..749b90cc
--- /dev/null
+++ b/apps/docs/images/graph-view.png
Binary files differ
diff --git a/apps/docs/images/hero-dark.svg b/apps/docs/images/hero-dark.svg
new file mode 100644
index 00000000..b2c2bcee
--- /dev/null
+++ b/apps/docs/images/hero-dark.svg
@@ -0,0 +1,32 @@
+<svg width="2344" height="969" viewBox="0 0 2344 969" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_2392_147)">
+<rect width="2344" height="969" rx="100" fill="#0F1114"/>
+<g opacity="0.4" filter="url(#filter0_f_2392_147)">
+<rect x="-2772.03" y="1936.79" width="7287.1" height="929.709" transform="rotate(-30 -2772.03 1936.79)" fill="#369DFD"/>
+</g>
+<g filter="url(#filter1_d_2392_147)">
+<path d="M854.654 430.165L832.896 432.517C832.678 430.295 832.003 428.226 830.87 426.31C829.738 424.393 828.039 422.868 825.774 421.736C823.552 420.56 820.677 419.972 817.149 419.972C812.008 419.972 807.5 421.126 803.623 423.435C799.746 425.743 797.546 428.705 797.024 432.321C796.544 435.022 797.198 437.222 798.984 438.92C800.77 440.619 804.08 442.057 808.916 443.233L825.512 446.892C834.66 448.939 841.238 452.25 845.245 456.824C849.296 461.398 850.712 467.387 849.492 474.793C848.447 480.978 845.746 486.423 841.39 491.128C837.034 495.789 831.458 499.426 824.663 502.04C817.911 504.653 810.418 505.96 802.186 505.96C789.684 505.96 780.057 503.368 773.305 498.185C766.597 492.957 763.264 485.77 763.308 476.622L786.569 474.401C786.83 478.931 788.42 482.35 791.339 484.659C794.258 486.924 798.309 488.079 803.492 488.122C809.329 488.166 814.252 486.946 818.259 484.463C822.311 481.937 824.597 478.866 825.12 475.25C825.556 472.549 824.881 470.349 823.095 468.651C821.352 466.952 818.238 465.601 813.751 464.599L797.285 461.006C787.963 458.958 781.32 455.495 777.356 450.616C773.436 445.694 772.107 439.487 773.37 431.994C774.416 425.896 776.964 420.647 781.015 416.247C785.11 411.804 790.359 408.384 796.762 405.989C803.166 403.549 810.331 402.33 818.259 402.33C830.195 402.33 839.19 404.834 845.245 409.844C851.3 414.853 854.436 421.627 854.654 430.165ZM931.376 461.79L941.112 403.636H964.765L948.038 504H925.104L928.109 486.162H927.064C923.927 491.781 919.441 496.377 913.604 499.949C907.81 503.521 901.145 505.307 893.609 505.307C887.032 505.307 881.478 503.848 876.947 500.929C872.417 497.967 869.194 493.676 867.277 488.057C865.404 482.394 865.121 475.555 866.427 467.54L877.143 403.636H900.797L890.734 463.881C889.732 470.241 890.647 475.294 893.479 479.04C896.354 482.786 900.622 484.659 906.285 484.659C909.77 484.659 913.277 483.81 916.805 482.111C920.377 480.412 923.492 477.885 926.149 474.531C928.806 471.134 930.549 466.886 931.376 461.79ZM962.474 541.636L985.605 403.636H1008.87L1006.19 420.233H1007.56C1009.13 417.794 1011.24 415.202 1013.9 412.457C1016.6 409.67 1020.02 407.295 1024.16 405.335C1028.29 403.331 1033.33 402.33 1039.25 402.33C1046.96 402.33 1053.6 404.312 1059.18 408.276C1064.75 412.196 1068.74 418.011 1071.14 425.722C1073.58 433.388 1073.88 442.797 1072.05 453.949C1070.22 464.97 1066.85 474.335 1061.92 482.045C1057 489.756 1051.1 495.636 1044.22 499.688C1037.33 503.739 1029.95 505.764 1022.06 505.764C1016.31 505.764 1011.68 504.806 1008.15 502.889C1004.66 500.973 1002.03 498.664 1000.24 495.963C998.455 493.219 997.126 490.627 996.255 488.188H995.21L986.323 541.636H962.474ZM1000.44 453.818C999.392 460.309 999.37 465.993 1000.37 470.872C1001.42 475.751 1003.49 479.562 1006.58 482.307C1009.67 485.008 1013.72 486.358 1018.73 486.358C1023.96 486.358 1028.53 484.964 1032.45 482.176C1036.42 479.345 1039.71 475.49 1042.32 470.611C1044.98 465.688 1046.85 460.091 1047.94 453.818C1048.94 447.589 1048.94 442.057 1047.94 437.222C1046.94 432.386 1044.91 428.597 1041.86 425.852C1038.81 423.108 1034.68 421.736 1029.45 421.736C1024.35 421.736 1019.8 423.064 1015.79 425.722C1011.83 428.379 1008.54 432.103 1005.93 436.895C1003.31 441.687 1001.48 447.328 1000.44 453.818ZM1124.35 505.96C1114.29 505.96 1105.97 503.869 1099.39 499.688C1092.81 495.462 1088.2 489.494 1085.54 481.784C1082.93 474.03 1082.49 464.904 1084.23 454.406C1085.93 444.082 1089.39 435.022 1094.62 427.224C1099.85 419.384 1106.38 413.285 1114.22 408.929C1122.11 404.529 1130.82 402.33 1140.36 402.33C1146.55 402.33 1152.23 403.331 1157.41 405.335C1162.6 407.295 1166.98 410.345 1170.55 414.483C1174.12 418.621 1176.58 423.892 1177.93 430.295C1179.28 436.655 1179.22 444.235 1177.73 453.034L1176.62 460.287H1094.29L1096.84 444.344H1156.43C1157.22 439.813 1156.96 435.784 1155.65 432.256C1154.34 428.684 1152.16 425.874 1149.12 423.827C1146.07 421.779 1142.25 420.756 1137.68 420.756C1133.02 420.756 1128.66 421.954 1124.61 424.349C1120.61 426.702 1117.23 429.751 1114.48 433.497C1111.74 437.243 1110 441.186 1109.26 445.324L1106.58 460.614C1105.62 466.886 1105.84 472.005 1107.23 475.969C1108.63 479.933 1111.07 482.851 1114.55 484.724C1118.04 486.598 1122.43 487.534 1127.75 487.534C1131.23 487.534 1134.46 487.055 1137.42 486.097C1140.38 485.138 1143.02 483.701 1145.33 481.784C1147.68 479.824 1149.64 477.428 1151.21 474.597L1172.83 477.08C1170.44 482.917 1166.93 488.013 1162.31 492.369C1157.7 496.682 1152.16 500.036 1145.72 502.432C1139.31 504.784 1132.19 505.96 1124.35 505.96ZM1185.75 504L1202.48 403.636H1225.41L1222.6 420.364H1223.65C1226.39 414.57 1230.27 410.105 1235.28 406.969C1240.33 403.789 1245.73 402.199 1251.48 402.199C1252.83 402.199 1254.29 402.264 1255.86 402.395C1257.43 402.482 1258.78 402.634 1259.91 402.852L1256.25 424.611C1255.25 424.262 1253.68 423.957 1251.55 423.696C1249.46 423.391 1247.39 423.239 1245.34 423.239C1241.03 423.239 1237.02 424.175 1233.32 426.048C1229.66 427.878 1226.57 430.426 1224.04 433.693C1221.51 436.96 1219.88 440.728 1219.14 444.997L1209.4 504H1185.75ZM1255.27 504L1272 403.636H1294.67L1291.79 420.69H1293.04C1296.09 414.94 1300.29 410.454 1305.65 407.23C1311 403.963 1317.04 402.33 1323.75 402.33C1330.5 402.33 1335.94 403.985 1340.08 407.295C1344.26 410.562 1346.83 415.027 1347.79 420.69H1348.84C1351.97 415.071 1356.46 410.606 1362.3 407.295C1368.18 403.985 1374.78 402.33 1382.1 402.33C1391.24 402.33 1398.26 405.248 1403.14 411.085C1408.01 416.922 1409.52 425.438 1407.64 436.634L1396.41 504H1372.75L1383.47 440.293C1384.43 434.063 1383.47 429.511 1380.59 426.636C1377.76 423.718 1373.95 422.259 1369.16 422.259C1363.45 422.259 1358.7 424.023 1354.91 427.551C1351.17 431.08 1348.86 435.697 1347.99 441.403L1337.47 504H1314.27L1325.12 439.312C1325.9 434.129 1324.99 429.991 1322.37 426.898C1319.8 423.805 1316.01 422.259 1311 422.259C1307.61 422.259 1304.36 423.13 1301.27 424.872C1298.18 426.615 1295.54 429.054 1293.36 432.19C1291.23 435.283 1289.83 438.877 1289.18 442.972L1278.99 504H1255.27ZM1460.83 505.96C1450.76 505.96 1442.44 503.869 1435.87 499.688C1429.29 495.462 1424.67 489.494 1422.01 481.784C1419.4 474.03 1418.97 464.904 1420.71 454.406C1422.41 444.082 1425.87 435.022 1431.1 427.224C1436.32 419.384 1442.86 413.285 1450.7 408.929C1458.58 404.529 1467.3 402.33 1476.84 402.33C1483.02 402.33 1488.71 403.331 1493.89 405.335C1499.07 407.295 1503.45 410.345 1507.02 414.483C1510.6 418.621 1513.06 423.892 1514.41 430.295C1515.76 436.655 1515.69 444.235 1514.21 453.034L1513.1 460.287H1430.77L1433.32 444.344H1492.91C1493.69 439.813 1493.43 435.784 1492.13 432.256C1490.82 428.684 1488.64 425.874 1485.59 423.827C1482.54 421.779 1478.73 420.756 1474.16 420.756C1469.5 420.756 1465.14 421.954 1461.09 424.349C1457.08 426.702 1453.71 429.751 1450.96 433.497C1448.22 437.243 1446.47 441.186 1445.73 445.324L1443.05 460.614C1442.1 466.886 1442.31 472.005 1443.71 475.969C1445.1 479.933 1447.54 482.851 1451.03 484.724C1454.51 486.598 1458.91 487.534 1464.22 487.534C1467.71 487.534 1470.93 487.055 1473.9 486.097C1476.86 485.138 1479.49 483.701 1481.8 481.784C1484.15 479.824 1486.11 477.428 1487.68 474.597L1509.31 477.08C1506.91 482.917 1503.41 488.013 1498.79 492.369C1494.17 496.682 1488.64 500.036 1482.19 502.432C1475.79 504.784 1468.67 505.96 1460.83 505.96ZM1522.29 504L1539.02 403.636H1561.69L1558.82 420.69H1560.06C1563.11 414.94 1567.31 410.454 1572.67 407.23C1578.03 403.963 1584.06 402.33 1590.77 402.33C1597.52 402.33 1602.97 403.985 1607.1 407.295C1611.29 410.562 1613.86 415.027 1614.81 420.69H1615.86C1619 415.071 1623.48 410.606 1629.32 407.295C1635.2 403.985 1641.8 402.33 1649.12 402.33C1658.27 402.33 1665.28 405.248 1670.16 411.085C1675.04 416.922 1676.54 425.438 1674.67 436.634L1663.43 504H1639.77L1650.49 440.293C1651.45 434.063 1650.49 429.511 1647.62 426.636C1644.78 423.718 1640.97 422.259 1636.18 422.259C1630.47 422.259 1625.73 424.023 1621.94 427.551C1618.19 431.08 1615.88 435.697 1615.01 441.403L1604.49 504H1581.29L1592.14 439.312C1592.93 434.129 1592.01 429.991 1589.4 426.898C1586.83 423.805 1583.04 422.259 1578.03 422.259C1574.63 422.259 1571.38 423.13 1568.29 424.872C1565.2 426.615 1562.56 429.054 1560.39 432.19C1558.25 435.283 1556.86 438.877 1556.2 442.972L1546.01 504H1522.29ZM1727.72 505.96C1717.83 505.96 1709.6 503.782 1703.02 499.426C1696.49 495.07 1691.89 488.95 1689.23 481.065C1686.58 473.181 1686.1 464.033 1687.8 453.622C1689.49 443.342 1692.89 434.347 1697.99 426.636C1703.13 418.926 1709.6 412.958 1717.4 408.733C1725.24 404.464 1734.01 402.33 1743.73 402.33C1753.62 402.33 1761.83 404.529 1768.36 408.929C1774.9 413.285 1779.49 419.405 1782.15 427.29C1784.85 435.174 1785.35 444.366 1783.65 454.864C1782 465.1 1778.58 474.052 1773.39 481.719C1768.25 489.385 1761.78 495.353 1753.99 499.622C1746.19 503.848 1737.43 505.96 1727.72 505.96ZM1729.68 487.011C1735.17 487.011 1739.98 485.53 1744.12 482.568C1748.3 479.562 1751.72 475.533 1754.38 470.48C1757.08 465.384 1758.95 459.721 1760 453.491C1760.96 447.48 1760.98 442.035 1760.06 437.156C1759.15 432.234 1757.19 428.335 1754.18 425.46C1751.22 422.542 1747.1 421.082 1741.83 421.082C1736.34 421.082 1731.49 422.607 1727.26 425.656C1723.08 428.662 1719.66 432.713 1717 437.81C1714.35 442.863 1712.52 448.504 1711.51 454.733C1710.51 460.744 1710.47 466.189 1711.38 471.068C1712.3 475.947 1714.26 479.824 1717.26 482.699C1720.27 485.574 1724.41 487.011 1729.68 487.011ZM1791.94 504L1808.67 403.636H1831.61L1828.8 420.364H1829.84C1832.59 414.57 1836.46 410.105 1841.47 406.969C1846.53 403.789 1851.93 402.199 1857.68 402.199C1859.03 402.199 1860.49 402.264 1862.06 402.395C1863.62 402.482 1864.97 402.634 1866.11 402.852L1862.45 424.611C1861.45 424.262 1859.88 423.957 1857.74 423.696C1855.65 423.391 1853.58 423.239 1851.54 423.239C1847.22 423.239 1843.22 424.175 1839.51 426.048C1835.85 427.878 1832.76 430.426 1830.23 433.693C1827.71 436.96 1826.07 440.728 1825.33 444.997L1815.6 504H1791.94ZM1873.01 541.636C1869.79 541.636 1866.85 541.375 1864.19 540.852C1861.58 540.373 1859.51 539.807 1857.98 539.153L1866.61 520.727C1869.88 521.729 1872.82 522.165 1875.43 522.034C1878.09 521.947 1880.53 521.054 1882.75 519.355C1885.01 517.7 1887.23 514.977 1889.41 511.188L1892.42 505.764L1873.21 403.636H1897.38L1907.84 479.562H1908.88L1944.76 403.636H1970.83L1912.09 516.023C1909.25 521.468 1905.97 526.085 1902.22 529.875C1898.47 533.708 1894.18 536.627 1889.35 538.631C1884.56 540.634 1879.11 541.636 1873.01 541.636Z" fill="white"/>
+</g>
+<path d="M481.982 251C506.33 251 513.5 270.609 513.5 294.75V379.125H554.473V346.711C554.473 330.963 560.782 315.861 572.013 304.726L578.531 298.263C577.246 295.264 576.536 291.964 576.536 288.5C576.536 274.693 587.825 263.5 601.75 263.5C615.675 263.5 626.964 274.693 626.964 288.5C626.964 302.307 615.675 313.5 601.75 313.5C598.256 313.5 594.928 312.795 591.903 311.522L585.385 317.984C577.701 325.603 573.384 335.936 573.384 346.711V379.125H641.404C645.145 369.963 654.204 363.5 664.786 363.5C678.711 363.5 690 374.693 690 388.5C690 402.307 678.711 413.5 664.786 413.5C654.204 413.5 645.145 407.037 641.404 397.875H513.5V454.125H578.369C582.109 444.963 591.168 438.5 601.75 438.5C615.675 438.5 626.964 449.693 626.964 463.5C626.964 477.307 615.675 488.5 601.75 488.5C591.168 488.5 582.109 482.037 578.368 472.875H513.5V529.125H568.255C584.137 529.125 599.369 535.381 610.599 546.516L642.331 577.978C645.357 576.705 648.685 576 652.179 576C666.104 576 677.393 587.193 677.393 601C677.393 614.807 666.104 626 652.179 626C638.253 626 626.964 614.807 626.964 601C626.964 597.536 627.675 594.236 628.96 591.237L597.227 559.774C589.543 552.155 579.121 547.875 568.255 547.875H513.5V607.25C513.5 631.391 506.33 651 481.982 651C459.211 651 440.457 633.891 438.094 611.859C433.996 612.953 429.662 613.5 425.25 613.5C397.435 613.5 374.821 591.078 374.821 563.5C374.821 557.719 375.846 552.094 377.658 546.937C353.862 538.031 337 515.219 337 488.5C337 463.578 351.735 442.016 373.088 432.016C366.233 423.5 362.214 412.719 362.214 401C362.214 377.016 379.234 357.016 401.927 352.094C400.666 347.797 400.036 343.187 400.036 338.5C400.036 315.141 416.267 295.453 438.094 289.984C440.457 268.109 459.211 251 481.982 251Z" fill="white"/>
+</g>
+<defs>
+<filter id="filter0_f_2392_147" x="-3653.3" y="-2588.03" width="8538.21" height="6211.24" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
+<feGaussianBlur stdDeviation="440.634" result="effect1_foregroundBlur_2392_147"/>
+</filter>
+<filter id="filter1_d_2392_147" x="751.242" y="402.199" width="1219.59" height="147.438" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dx="-8" dy="4"/>
+<feGaussianBlur stdDeviation="2"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.41 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_2392_147"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_2392_147" result="shape"/>
+</filter>
+<clipPath id="clip0_2392_147">
+<rect width="2344" height="969" rx="100" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/apps/docs/images/hero-light.svg b/apps/docs/images/hero-light.svg
new file mode 100644
index 00000000..4d347b2a
--- /dev/null
+++ b/apps/docs/images/hero-light.svg
@@ -0,0 +1,32 @@
+<svg width="2344" height="969" viewBox="0 0 2344 969" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_2397_133)">
+<rect width="2344" height="969" rx="100" fill="white"/>
+<g filter="url(#filter0_d_2397_133)">
+<path d="M854.654 430.165L832.896 432.517C832.678 430.295 832.003 428.226 830.87 426.31C829.738 424.393 828.039 422.868 825.774 421.736C823.552 420.56 820.677 419.972 817.149 419.972C812.008 419.972 807.5 421.126 803.623 423.435C799.746 425.743 797.546 428.705 797.024 432.321C796.544 435.022 797.198 437.222 798.984 438.92C800.77 440.619 804.08 442.057 808.916 443.233L825.512 446.892C834.66 448.939 841.238 452.25 845.245 456.824C849.296 461.398 850.712 467.387 849.492 474.793C848.447 480.978 845.746 486.423 841.39 491.128C837.034 495.789 831.458 499.426 824.663 502.04C817.911 504.653 810.418 505.96 802.186 505.96C789.684 505.96 780.057 503.368 773.305 498.185C766.597 492.957 763.264 485.77 763.308 476.622L786.569 474.401C786.83 478.931 788.42 482.35 791.339 484.659C794.258 486.924 798.309 488.079 803.492 488.122C809.329 488.166 814.252 486.946 818.259 484.463C822.311 481.937 824.597 478.866 825.12 475.25C825.556 472.549 824.881 470.349 823.095 468.651C821.352 466.952 818.238 465.601 813.751 464.599L797.285 461.006C787.963 458.958 781.32 455.495 777.356 450.616C773.436 445.694 772.107 439.487 773.37 431.994C774.416 425.896 776.964 420.647 781.015 416.247C785.11 411.804 790.359 408.384 796.762 405.989C803.166 403.549 810.331 402.33 818.259 402.33C830.195 402.33 839.19 404.834 845.245 409.844C851.3 414.853 854.436 421.627 854.654 430.165ZM931.376 461.79L941.112 403.636H964.765L948.038 504H925.104L928.109 486.162H927.064C923.927 491.781 919.441 496.377 913.604 499.949C907.81 503.521 901.145 505.307 893.609 505.307C887.032 505.307 881.478 503.848 876.947 500.929C872.417 497.967 869.194 493.676 867.277 488.057C865.404 482.394 865.121 475.555 866.427 467.54L877.143 403.636H900.797L890.734 463.881C889.732 470.241 890.647 475.294 893.479 479.04C896.354 482.786 900.622 484.659 906.285 484.659C909.77 484.659 913.277 483.81 916.805 482.111C920.377 480.412 923.492 477.885 926.149 474.531C928.806 471.134 930.549 466.886 931.376 461.79ZM962.474 541.636L985.605 403.636H1008.87L1006.19 420.233H1007.56C1009.13 417.794 1011.24 415.202 1013.9 412.457C1016.6 409.67 1020.02 407.295 1024.16 405.335C1028.29 403.331 1033.33 402.33 1039.25 402.33C1046.96 402.33 1053.6 404.312 1059.18 408.276C1064.75 412.196 1068.74 418.011 1071.14 425.722C1073.58 433.388 1073.88 442.797 1072.05 453.949C1070.22 464.97 1066.85 474.335 1061.92 482.045C1057 489.756 1051.1 495.636 1044.22 499.688C1037.33 503.739 1029.95 505.764 1022.06 505.764C1016.31 505.764 1011.68 504.806 1008.15 502.889C1004.66 500.973 1002.03 498.664 1000.24 495.963C998.455 493.219 997.126 490.627 996.255 488.188H995.21L986.323 541.636H962.474ZM1000.44 453.818C999.392 460.309 999.37 465.993 1000.37 470.872C1001.42 475.751 1003.49 479.562 1006.58 482.307C1009.67 485.008 1013.72 486.358 1018.73 486.358C1023.96 486.358 1028.53 484.964 1032.45 482.176C1036.42 479.345 1039.71 475.49 1042.32 470.611C1044.98 465.688 1046.85 460.091 1047.94 453.818C1048.94 447.589 1048.94 442.057 1047.94 437.222C1046.94 432.386 1044.91 428.597 1041.86 425.852C1038.81 423.108 1034.68 421.736 1029.45 421.736C1024.35 421.736 1019.8 423.064 1015.79 425.722C1011.83 428.379 1008.54 432.103 1005.93 436.895C1003.31 441.687 1001.48 447.328 1000.44 453.818ZM1124.35 505.96C1114.29 505.96 1105.97 503.869 1099.39 499.688C1092.81 495.462 1088.2 489.494 1085.54 481.784C1082.93 474.03 1082.49 464.904 1084.23 454.406C1085.93 444.082 1089.39 435.022 1094.62 427.224C1099.85 419.384 1106.38 413.285 1114.22 408.929C1122.11 404.529 1130.82 402.33 1140.36 402.33C1146.55 402.33 1152.23 403.331 1157.41 405.335C1162.6 407.295 1166.98 410.345 1170.55 414.483C1174.12 418.621 1176.58 423.892 1177.93 430.295C1179.28 436.655 1179.22 444.235 1177.73 453.034L1176.62 460.287H1094.29L1096.84 444.344H1156.43C1157.22 439.813 1156.96 435.784 1155.65 432.256C1154.34 428.684 1152.16 425.874 1149.12 423.827C1146.07 421.779 1142.25 420.756 1137.68 420.756C1133.02 420.756 1128.66 421.954 1124.61 424.349C1120.61 426.702 1117.23 429.751 1114.48 433.497C1111.74 437.243 1110 441.186 1109.26 445.324L1106.58 460.614C1105.62 466.886 1105.84 472.005 1107.23 475.969C1108.63 479.933 1111.07 482.851 1114.55 484.724C1118.04 486.598 1122.43 487.534 1127.75 487.534C1131.23 487.534 1134.46 487.055 1137.42 486.097C1140.38 485.138 1143.02 483.701 1145.33 481.784C1147.68 479.824 1149.64 477.428 1151.21 474.597L1172.83 477.08C1170.44 482.917 1166.93 488.013 1162.31 492.369C1157.7 496.682 1152.16 500.036 1145.72 502.432C1139.31 504.784 1132.19 505.96 1124.35 505.96ZM1185.75 504L1202.48 403.636H1225.41L1222.6 420.364H1223.65C1226.39 414.57 1230.27 410.105 1235.28 406.969C1240.33 403.789 1245.73 402.199 1251.48 402.199C1252.83 402.199 1254.29 402.264 1255.86 402.395C1257.43 402.482 1258.78 402.634 1259.91 402.852L1256.25 424.611C1255.25 424.262 1253.68 423.957 1251.55 423.696C1249.46 423.391 1247.39 423.239 1245.34 423.239C1241.03 423.239 1237.02 424.175 1233.32 426.048C1229.66 427.878 1226.57 430.426 1224.04 433.693C1221.51 436.96 1219.88 440.728 1219.14 444.997L1209.4 504H1185.75ZM1255.27 504L1272 403.636H1294.67L1291.79 420.69H1293.04C1296.09 414.94 1300.29 410.454 1305.65 407.23C1311 403.963 1317.04 402.33 1323.75 402.33C1330.5 402.33 1335.94 403.985 1340.08 407.295C1344.26 410.562 1346.83 415.027 1347.79 420.69H1348.84C1351.97 415.071 1356.46 410.606 1362.3 407.295C1368.18 403.985 1374.78 402.33 1382.1 402.33C1391.24 402.33 1398.26 405.248 1403.14 411.085C1408.01 416.922 1409.52 425.438 1407.64 436.634L1396.41 504H1372.75L1383.47 440.293C1384.43 434.063 1383.47 429.511 1380.59 426.636C1377.76 423.718 1373.95 422.259 1369.16 422.259C1363.45 422.259 1358.7 424.023 1354.91 427.551C1351.17 431.08 1348.86 435.697 1347.99 441.403L1337.47 504H1314.27L1325.12 439.312C1325.9 434.129 1324.99 429.991 1322.37 426.898C1319.8 423.805 1316.01 422.259 1311 422.259C1307.61 422.259 1304.36 423.13 1301.27 424.872C1298.18 426.615 1295.54 429.054 1293.36 432.19C1291.23 435.283 1289.83 438.877 1289.18 442.972L1278.99 504H1255.27ZM1460.83 505.96C1450.76 505.96 1442.44 503.869 1435.87 499.688C1429.29 495.462 1424.67 489.494 1422.01 481.784C1419.4 474.03 1418.97 464.904 1420.71 454.406C1422.41 444.082 1425.87 435.022 1431.1 427.224C1436.32 419.384 1442.86 413.285 1450.7 408.929C1458.58 404.529 1467.3 402.33 1476.84 402.33C1483.02 402.33 1488.71 403.331 1493.89 405.335C1499.07 407.295 1503.45 410.345 1507.02 414.483C1510.6 418.621 1513.06 423.892 1514.41 430.295C1515.76 436.655 1515.69 444.235 1514.21 453.034L1513.1 460.287H1430.77L1433.32 444.344H1492.91C1493.69 439.813 1493.43 435.784 1492.13 432.256C1490.82 428.684 1488.64 425.874 1485.59 423.827C1482.54 421.779 1478.73 420.756 1474.16 420.756C1469.5 420.756 1465.14 421.954 1461.09 424.349C1457.08 426.702 1453.71 429.751 1450.96 433.497C1448.22 437.243 1446.47 441.186 1445.73 445.324L1443.05 460.614C1442.1 466.886 1442.31 472.005 1443.71 475.969C1445.1 479.933 1447.54 482.851 1451.03 484.724C1454.51 486.598 1458.91 487.534 1464.22 487.534C1467.71 487.534 1470.93 487.055 1473.9 486.097C1476.86 485.138 1479.49 483.701 1481.8 481.784C1484.15 479.824 1486.11 477.428 1487.68 474.597L1509.31 477.08C1506.91 482.917 1503.41 488.013 1498.79 492.369C1494.17 496.682 1488.64 500.036 1482.19 502.432C1475.79 504.784 1468.67 505.96 1460.83 505.96ZM1522.29 504L1539.02 403.636H1561.69L1558.82 420.69H1560.06C1563.11 414.94 1567.31 410.454 1572.67 407.23C1578.03 403.963 1584.06 402.33 1590.77 402.33C1597.52 402.33 1602.97 403.985 1607.1 407.295C1611.29 410.562 1613.86 415.027 1614.81 420.69H1615.86C1619 415.071 1623.48 410.606 1629.32 407.295C1635.2 403.985 1641.8 402.33 1649.12 402.33C1658.27 402.33 1665.28 405.248 1670.16 411.085C1675.04 416.922 1676.54 425.438 1674.67 436.634L1663.43 504H1639.77L1650.49 440.293C1651.45 434.063 1650.49 429.511 1647.62 426.636C1644.78 423.718 1640.97 422.259 1636.18 422.259C1630.47 422.259 1625.73 424.023 1621.94 427.551C1618.19 431.08 1615.88 435.697 1615.01 441.403L1604.49 504H1581.29L1592.14 439.312C1592.93 434.129 1592.01 429.991 1589.4 426.898C1586.83 423.805 1583.04 422.259 1578.03 422.259C1574.63 422.259 1571.38 423.13 1568.29 424.872C1565.2 426.615 1562.56 429.054 1560.39 432.19C1558.25 435.283 1556.86 438.877 1556.2 442.972L1546.01 504H1522.29ZM1727.72 505.96C1717.83 505.96 1709.6 503.782 1703.02 499.426C1696.49 495.07 1691.89 488.95 1689.23 481.065C1686.58 473.181 1686.1 464.033 1687.8 453.622C1689.49 443.342 1692.89 434.347 1697.99 426.636C1703.13 418.926 1709.6 412.958 1717.4 408.733C1725.24 404.464 1734.01 402.33 1743.73 402.33C1753.62 402.33 1761.83 404.529 1768.36 408.929C1774.9 413.285 1779.49 419.405 1782.15 427.29C1784.85 435.174 1785.35 444.366 1783.65 454.864C1782 465.1 1778.58 474.052 1773.39 481.719C1768.25 489.385 1761.78 495.353 1753.99 499.622C1746.19 503.848 1737.43 505.96 1727.72 505.96ZM1729.68 487.011C1735.17 487.011 1739.98 485.53 1744.12 482.568C1748.3 479.562 1751.72 475.533 1754.38 470.48C1757.08 465.384 1758.95 459.721 1760 453.491C1760.96 447.48 1760.98 442.035 1760.06 437.156C1759.15 432.234 1757.19 428.335 1754.18 425.46C1751.22 422.542 1747.1 421.082 1741.83 421.082C1736.34 421.082 1731.49 422.607 1727.26 425.656C1723.08 428.662 1719.66 432.713 1717 437.81C1714.35 442.863 1712.52 448.504 1711.51 454.733C1710.51 460.744 1710.47 466.189 1711.38 471.068C1712.3 475.947 1714.26 479.824 1717.26 482.699C1720.27 485.574 1724.41 487.011 1729.68 487.011ZM1791.94 504L1808.67 403.636H1831.61L1828.8 420.364H1829.84C1832.59 414.57 1836.46 410.105 1841.47 406.969C1846.53 403.789 1851.93 402.199 1857.68 402.199C1859.03 402.199 1860.49 402.264 1862.06 402.395C1863.62 402.482 1864.97 402.634 1866.11 402.852L1862.45 424.611C1861.45 424.262 1859.88 423.957 1857.74 423.696C1855.65 423.391 1853.58 423.239 1851.54 423.239C1847.22 423.239 1843.22 424.175 1839.51 426.048C1835.85 427.878 1832.76 430.426 1830.23 433.693C1827.71 436.96 1826.07 440.728 1825.33 444.997L1815.6 504H1791.94ZM1873.01 541.636C1869.79 541.636 1866.85 541.375 1864.19 540.852C1861.58 540.373 1859.51 539.807 1857.98 539.153L1866.61 520.727C1869.88 521.729 1872.82 522.165 1875.43 522.034C1878.09 521.947 1880.53 521.054 1882.75 519.355C1885.01 517.7 1887.23 514.977 1889.41 511.188L1892.42 505.764L1873.21 403.636H1897.38L1907.84 479.562H1908.88L1944.76 403.636H1970.83L1912.09 516.023C1909.25 521.468 1905.97 526.085 1902.22 529.875C1898.47 533.708 1894.18 536.627 1889.35 538.631C1884.56 540.634 1879.11 541.636 1873.01 541.636Z" fill="black"/>
+</g>
+<path d="M481.982 251C506.33 251 513.5 270.609 513.5 294.75V379.125H554.473V346.711C554.473 330.963 560.782 315.861 572.013 304.726L578.531 298.263C577.246 295.264 576.536 291.964 576.536 288.5C576.536 274.693 587.825 263.5 601.75 263.5C615.675 263.5 626.964 274.693 626.964 288.5C626.964 302.307 615.675 313.5 601.75 313.5C598.256 313.5 594.928 312.795 591.903 311.522L585.385 317.984C577.701 325.603 573.384 335.936 573.384 346.711V379.125H641.404C645.145 369.963 654.204 363.5 664.786 363.5C678.711 363.5 690 374.693 690 388.5C690 402.307 678.711 413.5 664.786 413.5C654.204 413.5 645.145 407.037 641.404 397.875H513.5V454.125H578.369C582.109 444.963 591.168 438.5 601.75 438.5C615.675 438.5 626.964 449.693 626.964 463.5C626.964 477.307 615.675 488.5 601.75 488.5C591.168 488.5 582.109 482.037 578.368 472.875H513.5V529.125H568.255C584.137 529.125 599.369 535.381 610.599 546.516L642.331 577.978C645.357 576.705 648.685 576 652.179 576C666.104 576 677.393 587.193 677.393 601C677.393 614.807 666.104 626 652.179 626C638.253 626 626.964 614.807 626.964 601C626.964 597.536 627.675 594.236 628.96 591.237L597.227 559.774C589.543 552.155 579.121 547.875 568.255 547.875H513.5V607.25C513.5 631.391 506.33 651 481.982 651C459.21 651 440.457 633.891 438.094 611.859C433.996 612.953 429.662 613.5 425.25 613.5C397.435 613.5 374.821 591.078 374.821 563.5C374.821 557.719 375.846 552.094 377.658 546.937C353.862 538.031 337 515.219 337 488.5C337 463.578 351.735 442.016 373.088 432.016C366.233 423.5 362.214 412.719 362.214 401C362.214 377.016 379.234 357.016 401.927 352.094C400.666 347.797 400.036 343.187 400.036 338.5C400.036 315.141 416.267 295.453 438.094 289.984C440.457 268.109 459.21 251 481.982 251Z" fill="black"/>
+<g opacity="0.4" filter="url(#filter1_f_2397_133)">
+<rect x="-3176" y="2574.55" width="7287.1" height="929.709" transform="rotate(-30 -3176 2574.55)" fill="#369DFD"/>
+</g>
+</g>
+<defs>
+<filter id="filter0_d_2397_133" x="751.242" y="402.199" width="1219.59" height="147.438" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dx="-8" dy="4"/>
+<feGaussianBlur stdDeviation="2"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.41 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_2397_133"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_2397_133" result="shape"/>
+</filter>
+<filter id="filter1_f_2397_133" x="-4057.27" y="-1950.27" width="8538.21" height="6211.24" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
+<feGaussianBlur stdDeviation="440.634" result="effect1_foregroundBlur_2397_133"/>
+</filter>
+<clipPath id="clip0_2397_133">
+<rect width="2344" height="969" rx="100" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/apps/docs/images/infinite-context.png b/apps/docs/images/infinite-context.png
new file mode 100644
index 00000000..40ff670c
--- /dev/null
+++ b/apps/docs/images/infinite-context.png
Binary files differ
diff --git a/apps/docs/images/memories-inferred.png b/apps/docs/images/memories-inferred.png
new file mode 100644
index 00000000..85781894
--- /dev/null
+++ b/apps/docs/images/memories-inferred.png
Binary files differ
diff --git a/apps/docs/images/opts/Connectors.png b/apps/docs/images/opts/Connectors.png
new file mode 100644
index 00000000..615b01ff
--- /dev/null
+++ b/apps/docs/images/opts/Connectors.png
Binary files differ
diff --git a/apps/docs/images/opts/Memory_API.png b/apps/docs/images/opts/Memory_API.png
new file mode 100644
index 00000000..99550e83
--- /dev/null
+++ b/apps/docs/images/opts/Memory_API.png
Binary files differ
diff --git a/apps/docs/images/opts/Model_Enhancer.png b/apps/docs/images/opts/Model_Enhancer.png
new file mode 100644
index 00000000..e5ffefac
--- /dev/null
+++ b/apps/docs/images/opts/Model_Enhancer.png
Binary files differ
diff --git a/apps/docs/images/opts/Supermemory_MCP.png b/apps/docs/images/opts/Supermemory_MCP.png
new file mode 100644
index 00000000..0d21e076
--- /dev/null
+++ b/apps/docs/images/opts/Supermemory_MCP.png
Binary files differ
diff --git a/apps/docs/images/overview-image.png b/apps/docs/images/overview-image.png
new file mode 100644
index 00000000..f2527516
--- /dev/null
+++ b/apps/docs/images/overview-image.png
Binary files differ
diff --git a/apps/docs/images/pipeline.png b/apps/docs/images/pipeline.png
new file mode 100644
index 00000000..5b4e22c7
--- /dev/null
+++ b/apps/docs/images/pipeline.png
Binary files differ
diff --git a/apps/docs/images/process.png b/apps/docs/images/process.png
new file mode 100644
index 00000000..25596902
--- /dev/null
+++ b/apps/docs/images/process.png
Binary files differ
diff --git a/apps/docs/images/processing.png b/apps/docs/images/processing.png
new file mode 100644
index 00000000..dca6e4dd
--- /dev/null
+++ b/apps/docs/images/processing.png
Binary files differ
diff --git a/apps/docs/images/query-rewriting.png b/apps/docs/images/query-rewriting.png
new file mode 100644
index 00000000..9261c266
--- /dev/null
+++ b/apps/docs/images/query-rewriting.png
Binary files differ
diff --git a/apps/docs/images/rerank.png b/apps/docs/images/rerank.png
new file mode 100644
index 00000000..b40c6461
--- /dev/null
+++ b/apps/docs/images/rerank.png
Binary files differ
diff --git a/apps/docs/images/sm-header.png b/apps/docs/images/sm-header.png
new file mode 100644
index 00000000..f643a5ad
--- /dev/null
+++ b/apps/docs/images/sm-header.png
Binary files differ
diff --git a/apps/docs/images/transparent-proxy.png b/apps/docs/images/transparent-proxy.png
new file mode 100644
index 00000000..7dd34246
--- /dev/null
+++ b/apps/docs/images/transparent-proxy.png
Binary files differ
diff --git a/apps/docs/intro.mdx b/apps/docs/intro.mdx
new file mode 100644
index 00000000..ef09151f
--- /dev/null
+++ b/apps/docs/intro.mdx
@@ -0,0 +1,63 @@
+---
+title: "Overview — What is Supermemory?"
+sidebarTitle: "Overview"
+description = "Add long-term memory to your LLMs with three integration paths: AI SDK, Memory API, or Memory Router."
+---
+
+Supermemory gives your LLMs long-term memory. Instead of stateless text generation, they recall the right facts from your files, chats, and tools, so responses stay consistent, contextual, and personal.
+
+
+## How does it work? (at a glance)
+
+![](/images/overview-image.png)
+
+- You send Supermemory text, files, and chats.
+- Supermemory [intelligently indexes them](/how-it-works) and builds a semantic understanding graph on top of an entity (e.g., a user, a document, a project, an organization).
+- At query time, we fetch only the most relevant context and pass it to your models.
+
+We offer three ways to add memory to your LLMs:
+
+### Memory API — full control
+
+- Ingest text, files, and chats (supports multi-modal); search & filter; re-rank results.
+- Modelled after the actual human brain's working with smart forgetting, decay, recency bias, context rewriting, etc.
+- API + SDKs for Node & Python; designed to scale in production.
+
+<Info>
+ You can reference the full API documentation for the Memory API [here](/api-reference/manage-memories/add-memory).
+</Info>
+
+### AI SDK
+
+- Native Vercel AI SDK integration with `@supermemory/tools/ai-sdk`
+- Memory tools for agents or infinite chat for automatic context
+- Works with streamText, generateText, and all AI SDK features
+
+```typescript
+import { streamText } from "ai"
+import { supermemoryTools } from "@supermemory/tools/ai-sdk"
+
+const result = await streamText({
+ model: anthropic("claude-3"),
+ tools: supermemoryTools("YOUR_KEY")
+})
+```
+
+<Info>
+The AI SDK is recommended for new projects using Vercel AI SDK. The Router works best for existing **chat applications**, whereas the Memory API works as a **complete memory database** with granular control.
+</Info>
+
+
+### Memory Router — drop-in proxy with minimal code
+
+- Keep your existing LLM client; just append `api.supermemory.ai/v3/` to your base URL.
+- Automatic chunking and token management that fits your context window.
+- Adds minimal latency on top of existing LLM requests.
+
+<Note>
+All three approaches share the **same memory pool** when using the same user ID. You can mix and match based on your needs.
+</Note>
+
+## Next steps
+
+Head to the [**Router vs API**](/routervsapi) guide to understand the technical differences between the two and pick what’s best for you with a simple 4-question flow.
diff --git a/apps/docs/introduction.mdx b/apps/docs/introduction.mdx
new file mode 100644
index 00000000..a56eb603
--- /dev/null
+++ b/apps/docs/introduction.mdx
@@ -0,0 +1,66 @@
+---
+title: "Introduction"
+description: "supermemory is the Memory API for the AI era"
+mode: "custom"
+---
+
+export const HeroCard = ({ imageUrl, title, description, href }) => {
+ return (
+ <a className="group flex flex-col h-full rounded-lg overflow-hidden hover:shadow-lg transition-all duration-300 border border-gray-100 dark:border-zinc-800 hover:border-gray-200 dark:hover:border-zinc-700" href={href}>
+ <div className="overflow-hidden">
+ <img
+ src={imageUrl}
+ className="w-full h-48 object-cover transform group-hover:scale-105 transition-all duration-500"
+ alt={title}
+ />
+ </div>
+ <div className="p-6">
+ <h3 className="text-xl font-semibold text-gray-900 dark:text-zinc-50">{title}</h3>
+ <p className="mt-3 text-gray-600 dark:text-zinc-400">{description}</p>
+ </div>
+ </a>
+ )
+}
+
+<div className="relative pb-12">
+
+ <div className="px-4 py-16 lg:py-32 max-w-4xl mx-auto">
+ <h1 className="text-5xl font-bold text-center text-gray-900 dark:text-zinc-50 tracking-tight">
+ supermemory <span className="text-primary font-medium">[docs]</span>
+ </h1>
+
+ <p className="max-w-2xl mx-auto px-4 mt-6 text-xl text-center text-gray-600 dark:text-zinc-400 leading-relaxed">
+ Meet the memory API for the AI era — <span className="font-medium">scalable</span>, <span className="font-medium">powerful</span>, <span className="font-medium">affordable</span>, and <span className="font-medium">production-ready</span>.
+ </p>
+
+ <div className="mt-16 lg:mt-20 grid sm:grid-cols-2 gap-8">
+ <HeroCard
+ imageUrl="https://imagedelivery.net/_Zs8NCbSWCQ8-iurXrWjBg/40fe287e-b392-4bd6-9fc5-128ef674ca00/public"
+ title="Memory APIs"
+ description="Use our hyper fast, scalable and composable APIs for memory and RAG"
+ href="/how-it-works"
+ />
+
+ <HeroCard
+ imageUrl="https://imagedelivery.net/_Zs8NCbSWCQ8-iurXrWjBg/eda8b2fd-9633-4e93-c6bd-10b44be75e00/public"
+ title="Model Enhancer (Infinite chat)"
+ description="One line to add memory to your app. Supercharge your LLM with supermemory's intelligent context management."
+ href="/memory-router/overview"
+ />
+
+ <HeroCard
+ imageUrl="https://imagedelivery.net/_Zs8NCbSWCQ8-iurXrWjBg/abcc107d-7271-4acf-a9a2-90ad7a6f2000/public"
+ title="SDKs"
+ description="Use supermemory with your favorite tools and platforms seamlessly."
+ href="/memory-api/sdks/overview"
+ />
+
+ <HeroCard
+ imageUrl="https://imagedelivery.net/_Zs8NCbSWCQ8-iurXrWjBg/9af9572c-9f8d-42d8-f7d0-503a5f87a300/public"
+ title="Cookbooks"
+ description="Get started with supermemory with tutorials and examples"
+ href="/cookbook/overview"
+ />
+ </div>
+ </div>
+</div>
diff --git a/apps/docs/list-memories/examples/basic.mdx b/apps/docs/list-memories/examples/basic.mdx
new file mode 100644
index 00000000..c4358c44
--- /dev/null
+++ b/apps/docs/list-memories/examples/basic.mdx
@@ -0,0 +1,87 @@
+---
+title: "Basic Listing"
+description: "Simple memory retrieval across languages"
+---
+
+Simple memory retrieval examples for getting started with the list memories endpoint.
+
+## Basic Usage
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ import Supermemory from 'supermemory';
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ });
+
+ const response = await client.memories.list({ limit: 10 });
+ console.log(response);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ from supermemory import Supermemory
+ import os
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+ response = client.memories.list(limit=10)
+ print(response)
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"limit": 10}'
+ ```
+ </Tab>
+</Tabs>
+
+## With Custom Parameters
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const response = await client.memories.list({
+ containerTags: ["user_123"],
+ limit: 20,
+ sort: "updatedAt",
+ order: "desc"
+ });
+
+ console.log(`Found ${response.memories.length} memories`);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ response = client.memories.list(
+ container_tags=["user_123"],
+ limit=20,
+ sort="updatedAt",
+ order="desc"
+ )
+
+ print(f"Found {len(response.memories)} memories")
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user_123"],
+ "limit": 20,
+ "sort": "updatedAt",
+ "order": "desc"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+<Info>
+ Start with small `limit` values (10-20) when testing to avoid overwhelming responses.
+</Info>
diff --git a/apps/docs/list-memories/examples/filtering.mdx b/apps/docs/list-memories/examples/filtering.mdx
new file mode 100644
index 00000000..97394fa9
--- /dev/null
+++ b/apps/docs/list-memories/examples/filtering.mdx
@@ -0,0 +1,508 @@
+---
+title: "Filtering Memories"
+description: "Filter memories by container tags and metadata using SQL-based filtering"
+---
+
+Filter memories using container tags and metadata. The filtering system uses SQL query construction, so you need to structure your filters like database queries.
+
+## Filter by Container Tags
+
+Container tags use exact array matching - memories must have the exact same tags in the same order.
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Single tag - matches memories with exactly ["user_123"]
+ const userMemories = await client.memories.list({
+ containerTags: ["user_123"]
+ });
+
+ // Multiple tags - matches memories with exactly ["user_123", "project_ai"]
+ const projectMemories = await client.memories.list({
+ containerTags: ["user_123", "project_ai"]
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Single tag
+ user_memories = client.memories.list(container_tags=["user_123"])
+
+ # Multiple tags (exact match)
+ project_memories = client.memories.list(
+ container_tags=["user_123", "project_ai"]
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Single tag
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user_123"]}'
+
+ # Multiple tags
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"containerTags": ["user_123", "project_ai"]}'
+ ```
+ </Tab>
+</Tabs>
+
+## Metadata Filtering with SQL Logic
+
+The `filters` parameter allows filtering by metadata fields using SQL-like query structures. Since we use SQL query construction in the backend, you need to structure your filters like database queries with explicit AND/OR logic.
+
+### Why This Structure?
+
+In SQL databases, `AND` has higher precedence than `OR`. Without explicit grouping, a query like:
+```
+category = 'programming' OR framework = 'react' AND difficulty = 'advanced'
+```
+
+Is interpreted as:
+```
+category = 'programming' OR (framework = 'react' AND difficulty = 'advanced')
+```
+
+The JSON structure forces explicit grouping to prevent unexpected results.
+
+<Info>
+**Filter Structure Rules:**
+- Always wrap conditions in `AND` or `OR` arrays (even single conditions)
+- Use `JSON.stringify()` to convert the filter object to a string
+- Each condition needs `key`, `value`, and `negate` properties
+- `negate: false` for normal matching, `negate: true` for exclusion
+</Info>
+
+### Simple Metadata Filter
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Filter by single metadata field
+ const programmingMemories = await client.memories.list({
+ filters: JSON.stringify({
+ AND: [
+ { key: "category", value: "programming", negate: false }
+ ]
+ })
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ import json
+
+ # Filter by single metadata field
+ programming_memories = client.memories.list(
+ filters=json.dumps({
+ "AND": [
+ {"key": "category", "value": "programming", "negate": False}
+ ]
+ })
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "filters": "{\"AND\":[{\"key\":\"category\",\"value\":\"programming\",\"negate\":false}]}"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Multiple Conditions (AND Logic)
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // All conditions must match
+ const reactTutorials = await client.memories.list({
+ filters: JSON.stringify({
+ AND: [
+ { key: "category", value: "tutorial", negate: false },
+ { key: "framework", value: "react", negate: false },
+ { key: "difficulty", value: "beginner", negate: false }
+ ]
+ })
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # All conditions must match
+ react_tutorials = client.memories.list(
+ filters=json.dumps({
+ "AND": [
+ {"key": "category", "value": "tutorial", "negate": False},
+ {"key": "framework", "value": "react", "negate": False},
+ {"key": "difficulty", "value": "beginner", "negate": False}
+ ]
+ })
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "filters": "{\"AND\":[{\"key\":\"category\",\"value\":\"tutorial\",\"negate\":false},{\"key\":\"framework\",\"value\":\"react\",\"negate\":false}]}"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Alternative Conditions (OR Logic)
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Any condition can match
+ const frontendMemories = await client.memories.list({
+ filters: JSON.stringify({
+ OR: [
+ { key: "framework", value: "react", negate: false },
+ { key: "framework", value: "vue", negate: false },
+ { key: "framework", value: "angular", negate: false }
+ ]
+ })
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Any condition can match
+ frontend_memories = client.memories.list(
+ filters=json.dumps({
+ "OR": [
+ {"key": "framework", "value": "react", "negate": False},
+ {"key": "framework", "value": "vue", "negate": False},
+ {"key": "framework", "value": "angular", "negate": False}
+ ]
+ })
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "filters": "{\"OR\":[{\"key\":\"framework\",\"value\":\"react\",\"negate\":false},{\"key\":\"framework\",\"value\":\"vue\",\"negate\":false}]}"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Complex Nested Logic
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Complex logic: programming AND (react OR advanced difficulty)
+ const advancedContent = await client.memories.list({
+ filters: JSON.stringify({
+ AND: [
+ { key: "category", value: "programming", negate: false },
+ {
+ OR: [
+ { key: "framework", value: "react", negate: false },
+ { key: "difficulty", value: "advanced", negate: false }
+ ]
+ }
+ ]
+ })
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Complex logic: programming AND (react OR advanced difficulty)
+ advanced_content = client.memories.list(
+ filters=json.dumps({
+ "AND": [
+ {"key": "category", "value": "programming", "negate": False},
+ {
+ "OR": [
+ {"key": "framework", "value": "react", "negate": False},
+ {"key": "difficulty", "value": "advanced", "negate": False}
+ ]
+ }
+ ]
+ })
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "filters": "{\"AND\":[{\"key\":\"category\",\"value\":\"programming\",\"negate\":false},{\"OR\":[{\"key\":\"framework\",\"value\":\"react\",\"negate\":false},{\"key\":\"difficulty\",\"value\":\"advanced\",\"negate\":false}]}]}"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Array Contains Filtering
+
+Filter memories that contain specific values in array fields like participants, tags, or team members.
+
+### Basic Array Contains
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Find memories where john.doe participated
+ const meetingMemories = await client.memories.list({
+ filters: JSON.stringify({
+ AND: [
+ {
+ key: "participants",
+ value: "john.doe",
+ filterType: "array_contains",
+ negate: false
+ }
+ ]
+ })
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Find memories where john.doe participated
+ meeting_memories = client.memories.list(
+ filters=json.dumps({
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains",
+ "negate": False
+ }
+ ]
+ })
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "filters": "{\"AND\":[{\"key\":\"participants\",\"value\":\"john.doe\",\"filterType\":\"array_contains\",\"negate\":false}]}"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Array Contains with Exclusion
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Find memories that don't include a specific team member
+ const filteredMemories = await client.memories.list({
+ filters: JSON.stringify({
+ AND: [
+ {
+ key: "reviewers",
+ value: "external.consultant",
+ filterType: "array_contains",
+ negate: true // Exclude memories with external consultants
+ },
+ {
+ key: "project_tags",
+ value: "internal-only",
+ filterType: "array_contains",
+ negate: false
+ }
+ ]
+ })
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Find memories that don't include a specific team member
+ filtered_memories = client.memories.list(
+ filters=json.dumps({
+ "AND": [
+ {
+ "key": "reviewers",
+ "value": "external.consultant",
+ "filterType": "array_contains",
+ "negate": True # Exclude memories with external consultants
+ },
+ {
+ "key": "project_tags",
+ "value": "internal-only",
+ "filterType": "array_contains",
+ "negate": False
+ }
+ ]
+ })
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "filters": "{\"AND\":[{\"key\":\"reviewers\",\"value\":\"external.consultant\",\"filterType\":\"array_contains\",\"negate\":true},{\"key\":\"project_tags\",\"value\":\"internal-only\",\"filterType\":\"array_contains\",\"negate\":false}]}"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Multiple Array Contains (OR Logic)
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Find memories involving any of several team leads
+ const leadershipMemories = await client.memories.list({
+ filters: JSON.stringify({
+ OR: [
+ {
+ key: "attendees",
+ value: "engineering.lead",
+ filterType: "array_contains"
+ },
+ {
+ key: "attendees",
+ value: "product.lead",
+ filterType: "array_contains"
+ },
+ {
+ key: "attendees",
+ value: "design.lead",
+ filterType: "array_contains"
+ }
+ ]
+ }),
+ sort: "updatedAt",
+ order: "desc"
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Find memories involving any of several team leads
+ leadership_memories = client.memories.list(
+ filters=json.dumps({
+ "OR": [
+ {
+ "key": "attendees",
+ "value": "engineering.lead",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "attendees",
+ "value": "product.lead",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "attendees",
+ "value": "design.lead",
+ "filterType": "array_contains"
+ }
+ ]
+ }),
+ sort="updatedAt",
+ order="desc"
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "filters": "{\"OR\":[{\"key\":\"attendees\",\"value\":\"engineering.lead\",\"filterType\":\"array_contains\"},{\"key\":\"attendees\",\"value\":\"product.lead\",\"filterType\":\"array_contains\"},{\"key\":\"attendees\",\"value\":\"design.lead\",\"filterType\":\"array_contains\"}]}",
+ "sort": "updatedAt",
+ "order": "desc"
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Combined Container Tags + Metadata Filtering
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const filteredMemories = await client.memories.list({
+ containerTags: ["user_123"],
+ filters: JSON.stringify({
+ AND: [
+ { key: "category", value: "tutorial", negate: false },
+ { key: "framework", value: "react", negate: false }
+ ]
+ }),
+ sort: "updatedAt",
+ order: "desc",
+ limit: 50
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ filtered_memories = client.memories.list(
+ container_tags=["user_123"],
+ filters=json.dumps({
+ "AND": [
+ {"key": "category", "value": "tutorial", "negate": False},
+ {"key": "framework", "value": "react", "negate": False}
+ ]
+ }),
+ sort="updatedAt",
+ order="desc",
+ limit=50
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user_123"],
+ "filters": "{\"AND\":[{\"key\":\"category\",\"value\":\"tutorial\",\"negate\":false},{\"key\":\"framework\",\"value\":\"react\",\"negate\":false}]}",
+ "sort": "updatedAt",
+ "order": "desc",
+ "limit": 50
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+<Warning>
+**Common Mistakes:**
+- Using bare condition objects: `{"key": "category", "value": "programming"}`
+- Forgetting JSON.stringify: passing objects instead of strings
+- Missing negate property: always include `"negate": false` or `"negate": true`
+</Warning>
+
+<Note>
+**Container Tags vs Metadata Filtering:**
+- Container tags: Exact array matching for organizational grouping
+- Metadata filters: SQL-like queries on custom metadata fields with complex logic
+- Both can be combined for powerful filtering capabilities
+</Note>
diff --git a/apps/docs/list-memories/examples/monitoring.mdx b/apps/docs/list-memories/examples/monitoring.mdx
new file mode 100644
index 00000000..1ad0341e
--- /dev/null
+++ b/apps/docs/list-memories/examples/monitoring.mdx
@@ -0,0 +1,118 @@
+---
+title: "Status Monitoring"
+description: "Monitor memory processing status and completion rates"
+---
+
+Monitor memory processing status and track completion rates using the list endpoint.
+
+## Status Overview
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const response = await client.memories.list({ limit: 100 });
+
+ const statusCounts = response.memories.reduce((acc: any, memory) => {
+ acc[memory.status] = (acc[memory.status] || 0) + 1;
+ return acc;
+ }, {});
+
+ console.log('Status breakdown:', statusCounts);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ response = client.memories.list(limit=100)
+
+ status_counts = {}
+ for memory in response.memories:
+ status = memory.status
+ status_counts[status] = status_counts.get(status, 0) + 1
+
+ print("Status breakdown:", status_counts)
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"limit": 100}' | \
+ jq '.memories | group_by(.status) | map({status: .[0].status, count: length})'
+ ```
+ </Tab>
+</Tabs>
+
+## Filter Processing Memories
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const response = await client.memories.list({ limit: 100 });
+
+ const processing = response.memories.filter(m =>
+ ['queued', 'extracting', 'chunking', 'embedding', 'indexing'].includes(m.status)
+ );
+
+ console.log(`${processing.length} memories currently processing`);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ response = client.memories.list(limit=100)
+
+ processing_statuses = ['queued', 'extracting', 'chunking', 'embedding', 'indexing']
+ processing = [m for m in response.memories if m.status in processing_statuses]
+
+ print(f"{len(processing)} memories currently processing")
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"limit": 100}' | \
+ jq '.memories[] | select(.status | IN("queued", "extracting", "chunking", "embedding", "indexing"))'
+ ```
+ </Tab>
+</Tabs>
+
+## Failed Memories
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const failedMemories = await client.memories.list({
+ filters: "status:failed",
+ limit: 50
+ });
+
+ failedMemories.memories.forEach(memory => {
+ console.log(`Failed: ${memory.id} - ${memory.title || 'Untitled'}`);
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ failed_memories = client.memories.list(filters="status:failed", limit=50)
+
+ for memory in failed_memories.memories:
+ title = memory.title or 'Untitled'
+ print(f"Failed: {memory.id} - {title}")
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"filters": "status:failed", "limit": 50}' | \
+ jq '.memories[] | {id, title, status}'
+ ```
+ </Tab>
+</Tabs>
+
+<Note>
+ For real-time monitoring of individual memories, use the [Track Processing Status](/api/track-progress) guide.
+</Note>
diff --git a/apps/docs/list-memories/examples/pagination.mdx b/apps/docs/list-memories/examples/pagination.mdx
new file mode 100644
index 00000000..56004b89
--- /dev/null
+++ b/apps/docs/list-memories/examples/pagination.mdx
@@ -0,0 +1,110 @@
+---
+title: "Pagination"
+description: "Handle large memory collections with pagination"
+---
+
+Handle large memory collections efficiently using pagination to process data in manageable chunks.
+
+## Basic Pagination
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Get first page
+ const page1 = await client.memories.list({
+ limit: 20,
+ page: 1
+ });
+
+ // Get next page
+ const page2 = await client.memories.list({
+ limit: 20,
+ page: 2
+ });
+
+ console.log(`Page 1: ${page1.memories.length} memories`);
+ console.log(`Page 2: ${page2.memories.length} memories`);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Get first page
+ page1 = client.memories.list(limit=20, page=1)
+
+ # Get next page
+ page2 = client.memories.list(limit=20, page=2)
+
+ print(f"Page 1: {len(page1.memories)} memories")
+ print(f"Page 2: {len(page2.memories)} memories")
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Get first page
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"limit": 20, "page": 1}'
+
+ # Get next page
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"limit": 20, "page": 2}'
+ ```
+ </Tab>
+</Tabs>
+
+## Loop Through Pages
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ let currentPage = 1;
+ let hasMore = true;
+
+ while (hasMore) {
+ const response = await client.memories.list({
+ page: currentPage,
+ limit: 50
+ });
+
+ console.log(`Page ${currentPage}: ${response.memories.length} memories`);
+
+ hasMore = currentPage < response.pagination.totalPages;
+ currentPage++;
+ }
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ current_page = 1
+ has_more = True
+
+ while has_more:
+ response = client.memories.list(page=current_page, limit=50)
+
+ print(f"Page {current_page}: {len(response.memories)} memories")
+
+ has_more = current_page < response.pagination.total_pages
+ current_page += 1
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Manual pagination with bash loop
+ for page in {1..5}; do
+ echo "=== Page $page ==="
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d "{\"page\": $page, \"limit\": 20}" | \
+ jq '.memories | length'
+ done
+ ```
+ </Tab>
+</Tabs>
+
+<Info>
+ Use larger `limit` values (50-100) for pagination to reduce the number of API calls needed.
+</Info>
diff --git a/apps/docs/list-memories/overview.mdx b/apps/docs/list-memories/overview.mdx
new file mode 100644
index 00000000..d1631030
--- /dev/null
+++ b/apps/docs/list-memories/overview.mdx
@@ -0,0 +1,153 @@
+---
+title: "List Memories"
+description: "Retrieve paginated memories with filtering and sorting options"
+sidebarTitle: "Overview"
+---
+
+
+Retrieve paginated memories with filtering and sorting options from your Supermemory account.
+
+## Quick Start
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ import Supermemory from 'supermemory';
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ });
+
+ const memories = await client.memories.list({ limit: 10 });
+ console.log(memories);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ from supermemory import Supermemory
+ import os
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+ memories = client.memories.list(limit=10)
+ print(f"Found {len(memories.memories)} memories")
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents/list" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"limit": 10}'
+ ```
+ </Tab>
+</Tabs>
+
+## Response Schema
+
+The endpoint returns a structured response containing your memories and pagination information:
+
+```json
+{
+ "memories": [
+ {
+ "id": "abc123",
+ "connectionId": null,
+ "createdAt": "2024-01-15T10:30:00.000Z",
+ "updatedAt": "2024-01-15T10:35:00.000Z",
+ "customId": "ml-basics-001",
+ "title": "Introduction to Machine Learning",
+ "summary": "This document introduces machine learning as a subset of artificial intelligence...",
+ "status": "done",
+ "type": "text",
+ "metadata": {
+ "category": "education",
+ "priority": "high",
+ "source": "research-notes"
+ },
+ "containerTags": ["user_123", "ai-research"]
+ }
+ ],
+ "pagination": {
+ "currentPage": 1,
+ "totalPages": 3,
+ "totalItems": 25,
+ "limit": 10
+ }
+}
+```
+
+### Memory Object Fields
+
+<Accordion title="Core Fields" defaultOpen>
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `id` | string | Unique identifier for the memory |
+| `status` | ProcessingStatus | Current processing status (`queued`, `extracting`, `chunking`, `embedding`, `indexing`, `done`, `failed`) |
+| `type` | MemoryType | Content type (`text`, `pdf`, `webpage`, `video`, `image`, etc.) |
+| `title` | string \| null | Auto-generated or custom title |
+| `summary` | string \| null | AI-generated summary of content |
+| `createdAt` | string | ISO 8601 creation timestamp |
+| `updatedAt` | string | ISO 8601 last update timestamp |
+
+</Accordion>
+
+<Accordion title="Optional Fields">
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `customId` | string \| null | Your custom identifier for the memory |
+| `connectionId` | string \| null | ID of connector that created this memory |
+| `metadata` | object \| null | Custom key-value metadata you provided |
+| `containerTags` | string[] | Tags for organizing and filtering memories |
+
+</Accordion>
+
+## Key Parameters
+
+All parameters are optional and sent in the request body since this endpoint uses `POST`:
+
+<ParamField path="limit" type="number/string" default="50">
+ **Number of items per page.** Controls how many memories are returned in a single request. Maximum recommended: 200 for optimal performance.
+</ParamField>
+
+<ParamField path="page" type="number/string" default="1">
+ **Page number to fetch (1-indexed).** Use with `limit` to paginate through large result sets.
+</ParamField>
+
+<ParamField path="containerTags" type="string[]">
+ **Filter by tags.** Memories must match ALL provided tags. Use for filtering by user ID, project, or custom organization tags.
+</ParamField>
+
+<ParamField path="sort" type="string" default="createdAt">
+ **Sort field.** Options: `"createdAt"` (when memory was added) or `"updatedAt"` (when memory was last modified).
+</ParamField>
+
+<ParamField path="order" type="string" default="desc">
+ **Sort direction.** Use `"desc"` for newest first, `"asc"` for oldest first.
+</ParamField>
+
+<ParamField path="filters" type="string">
+ **Advanced filtering.** Filter based on metadata with advanced SQL logic.
+</ParamField>
+
+## Examples
+
+<CardGroup cols={2}>
+ <Card title="Basic Listing" icon="list" href="/list-memories/examples/basic">
+ Simple memory retrieval with default settings
+ </Card>
+ <Card title="Filtering" icon="filter" href="/list-memories/examples/filtering">
+ Filter by tags, status, and other criteria
+ </Card>
+ <Card title="Pagination" icon="arrow-right" href="/list-memories/examples/pagination">
+ Handle large datasets with pagination
+ </Card>
+ <Card title="Status Monitoring" icon="chart-line" href="/list-memories/examples/monitoring">
+ Track processing status across memories
+ </Card>
+</CardGroup>
+
+<Note>
+ The `/v3/documents/list` endpoint uses **POST** method, not GET. This allows for complex filtering parameters in the request body.
+</Note>
diff --git a/apps/docs/logo/dark.svg b/apps/docs/logo/dark.svg
new file mode 100644
index 00000000..b950a8a3
--- /dev/null
+++ b/apps/docs/logo/dark.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 206 168"><path fill="#FFFFFF" d="M205.864 66.263h-76.401V0h-24.684v71.897c0 7.636 3.021 14.97 8.391 20.373l62.383 62.777 17.454-17.564-46.076-46.365h58.948v-24.84l-.015-.015ZM12.872 30.517l46.075 46.365H0v24.84h76.4v66.264h24.685V96.089c0-7.637-3.021-14.97-8.39-20.374l-62.37-62.762-17.453 17.564Z"/></svg> \ No newline at end of file
diff --git a/apps/docs/logo/light.svg b/apps/docs/logo/light.svg
new file mode 100644
index 00000000..77eeea54
--- /dev/null
+++ b/apps/docs/logo/light.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 206 168"><path fill="#1E293B" d="M205.864 66.263h-76.401V0h-24.684v71.897c0 7.636 3.021 14.97 8.391 20.373l62.383 62.777 17.454-17.564-46.076-46.365h58.948v-24.84l-.015-.015ZM12.872 30.517l46.075 46.365H0v24.84h76.4v66.264h24.685V96.089c0-7.637-3.021-14.97-8.39-20.374l-62.37-62.762-17.453 17.564Z"/></svg> \ No newline at end of file
diff --git a/apps/docs/memory-api/connectors/advanced/bring-your-own-key.mdx b/apps/docs/memory-api/connectors/advanced/bring-your-own-key.mdx
new file mode 100644
index 00000000..3d63cb46
--- /dev/null
+++ b/apps/docs/memory-api/connectors/advanced/bring-your-own-key.mdx
@@ -0,0 +1,138 @@
+---
+title: 'Bring Your Own Key (BYOK)'
+description: 'Configure your own OAuth application credentials for enhanced security and control'
+---
+
+By default, supermemory uses its own OAuth applications to connect to third-party providers. However, you can configure your own OAuth application credentials for enhanced security and control. This is particularly useful for enterprise customers who want to maintain control over their data access.
+
+<Danger>
+ Some providers like Google Drive require extensive verification and approval before you can use custom keys.
+</Danger>
+
+### Setting up Custom Provider Keys
+
+To configure custom OAuth credentials for your organization, use the `PATCH /v3/settings` endpoint:
+
+1. Set up your OAuth application on the provider's developer console.
+
+Google: https://console.developers.google.com/apis/credentials/oauthclient \
+Notion: https://www.notion.so/my-integrations \
+OneDrive: https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsMenu
+
+2. If using Google drive,
+
+- Select the application type as `Web application`
+- **Enable the Google drive api in "APIs and Services" in the Cloud Console**
+
+3. Configure the redirect URL, set it to:
+
+```
+https://api.supermemory.ai/v3/connections/auth/callback/{provider}
+```
+
+For example, if you are using Google Drive, the redirect URL would be:
+
+```
+https://api.supermemory.ai/v3/connections/auth/callback/google-drive
+```
+
+4. Configure the client ID and client secret in the `PATCH /v3/settings` endpoint.
+
+<CodeGroup>
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env['SUPERMEMORY_API_KEY'],
+});
+
+// Example: Configure Google Drive custom OAuth credentials
+const settings = await client.settings.update({
+ googleCustomKeyEnabled: true,
+ googleDriveClientId: "your-google-client-id",
+ googleDriveClientSecret: "your-google-client-secret"
+});
+
+// Example: Configure Notion custom OAuth credentials
+const settings = await client.settings.update({
+ notionCustomKeyEnabled: true,
+ notionClientId: "your-notion-client-id",
+ notionClientSecret: "your-notion-client-secret"
+});
+
+// Example: Configure OneDrive custom OAuth credentials
+const settings = await client.settings.update({
+ onedriveCustomKeyEnabled: true,
+ onedriveClientId: "your-onedrive-client-id",
+ onedriveClientSecret: "your-onedrive-client-secret"
+});
+```
+
+```python Python
+from supermemory import supermemory
+
+client = supermemory(
+ api_key=os.environ.get("SUPERMEMORY_API_KEY"), # This is the default and can be omitted
+)
+
+# Example: Configure Google Drive custom OAuth credentials
+settings = client.settings.update(
+ google_custom_key_enabled=True,
+ google_client_id="your-google-client-id",
+ google_client_secret="your-google-client-secret"
+)
+
+# Example: Configure Notion custom OAuth credentials
+settings = client.settings.update(
+ notion_custom_key_enabled=True,
+ notion_client_id="your-notion-client-id",
+ notion_client_secret="your-notion-client-secret"
+)
+
+# Example: Configure OneDrive custom OAuth credentials
+settings = client.settings.update(
+ onedrive_custom_key_enabled=True,
+ onedrive_client_id="your-onedrive-client-id",
+ onedrive_client_secret="your-onedrive-client-secret"
+)
+```
+
+```bash cURL
+# Example: Configure Google Drive custom OAuth credentials
+curl --request PATCH \
+ --url https://api.supermemory.ai/v3/settings \
+ --header 'Authorization: Bearer <token>' \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "googleDriveCustomKeyEnabled": true,
+ "googleDriveClientId": "your-google-client-id",
+ "googleDriveClientSecret": "your-google-client-secret"
+}'
+
+# Example: Configure Notion custom OAuth credentials
+curl --request PATCH \
+ --url https://api.supermemory.ai/v3/settings \
+ --header 'Authorization: Bearer <token>' \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "notionCustomKeyEnabled": true,
+ "notionClientId": "your-notion-client-id",
+ "notionClientSecret": "your-notion-client-secret"
+}'
+
+# Example: Configure OneDrive custom OAuth credentials
+curl --request PATCH \
+ --url https://api.supermemory.ai/v3/settings \
+ --header 'Authorization: Bearer <token>' \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "onedriveCustomKeyEnabled": true,
+ "onedriveClientId": "your-onedrive-client-id",
+ "onedriveClientSecret": "your-onedrive-client-secret"
+}'
+```
+</CodeGroup>
+
+<Warning>
+ Once you enable custom keys for a provider, all new connections for that provider will use your custom OAuth application. Existing connections WILL need to be re-authorized.
+</Warning> \ No newline at end of file
diff --git a/apps/docs/memory-api/connectors/creating-connection.mdx b/apps/docs/memory-api/connectors/creating-connection.mdx
new file mode 100644
index 00000000..39abc47a
--- /dev/null
+++ b/apps/docs/memory-api/connectors/creating-connection.mdx
@@ -0,0 +1,85 @@
+---
+title: 'Creating connections'
+description: 'Create a connection to sync your content with supermemory'
+---
+
+To create a connection, just make a `POST` request to `/v3/connections/{provider}`
+
+<CodeGroup>
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env['SUPERMEMORY_API_KEY'], // This is the default and can be omitted
+});
+
+const connection = await client.connections.create('notion');
+
+console.debug(connection.authLink);
+```
+
+```python Python
+import requests
+
+url = "https://api.supermemory.ai/v3/connections/{provider}"
+
+payload = {
+ "redirectUrl": "<string>",
+ "containerTags": ["<string>"],
+ "metadata": {},
+ "documentLimit": 5000
+}
+headers = {
+ "Authorization": "Bearer <token>",
+ "Content-Type": "application/json"
+}
+
+response = requests.request("POST", url, json=payload, headers=headers)
+
+print(response.text)
+```
+
+```bash cURL
+curl --request POST \
+ --url https://api.supermemory.ai/v3/connections/{provider} \
+ --header 'Authorization: Bearer <token>' \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "redirectUrl": "<string>",
+ "containerTags": [
+ "<string>"
+ ],
+ "metadata": {},
+ "documentLimit": 5000
+}'
+```
+</CodeGroup>
+
+### Parameters
+
+- `provider`: The provider to connect to. Currently supported providers are `notion`, `google-drive`, `one-drive`
+- `redirectUrl`: The URL to redirect to after the connection is created (your app URL)
+- `containerTags`: Optional. For partitioning users, organizations, etc. in your app.
+ - Example: `["user_123", "project_alpha"]`
+- `metadata`: Optional. Any metadata you want to associate with the connection.
+ - This metadata is added to every document synced from this connection.
+- `documentLimit`: Optional. The maximum number of documents to sync from this connection.
+ - Default: 10,000
+ - This can be used to limit costs and sync a set number of documents for a specific user.
+
+
+## Response
+
+supermemory sends a response with the following schema:
+```json
+{
+ "id": "<string>",
+ "authLink": "<string>",
+ "expiresIn": "<string>",
+ "redirectsTo": "<string>"
+}
+```
+
+You can use the `authLink` to redirect the user to the provider's login page.
+
+Next up, managing connections.
diff --git a/apps/docs/memory-api/connectors/google-drive.mdx b/apps/docs/memory-api/connectors/google-drive.mdx
new file mode 100644
index 00000000..8413fdd2
--- /dev/null
+++ b/apps/docs/memory-api/connectors/google-drive.mdx
@@ -0,0 +1,27 @@
+---
+title: 'Google Drive'
+description: 'Sync your Google Drive content with supermemory'
+---
+
+supermemory syncs Google Drive documents automatically and instantaneously.
+
+## Supported file types
+
+- Google Docs
+- Google Slides
+- Google Sheets
+
+## Conversions
+
+To import items, supermemory converts documents into markdown, and then ingests them into supermemory.
+This conversion is lossy, and some formatting may be lost.
+
+## Sync frequency
+
+supermemory syncs documents:
+- **A document is modified or created (Webhook recieved)**
+ - Note that not all providers are synced via webhook (Instant sync right now)
+ - `Google-Drive` and `Notion` documents are synced instantaneously
+- Every **four hours**
+- On **Manual Sync** (API call)
+ - You can call `/v3/connections/{provider}/sync` to sync documents manually
diff --git a/apps/docs/memory-api/connectors/overview.mdx b/apps/docs/memory-api/connectors/overview.mdx
new file mode 100644
index 00000000..8727b68c
--- /dev/null
+++ b/apps/docs/memory-api/connectors/overview.mdx
@@ -0,0 +1,26 @@
+---
+title: 'Connectors Overview'
+sidebarTitle: 'Overview'
+description: 'Sync external connections like Google Drive, Notion, OneDrive with supermemory'
+---
+
+supermemory can sync external connections like Google Drive, Notion, OneDrive with more coming soon.
+
+### The Flow
+
+1. Make a `POST` request to `/v3/connections/{provider}`
+2. supermemory will return an `authLink` which you can redirect the user to
+3. The user will be redirected to the provider's login page
+4. User is redirected back to your app's `redirectUrl`
+
+![Connectors Flow](/images/connectors-flow.png)
+
+## Sync frequency
+
+supermemory syncs documents:
+- **A document is modified or created (Webhook recieved)**
+ - Note that not all providers are synced via webhook (Instant sync right now)
+ - `Google-Drive` and `Notion` documents are synced instantaneously
+- Every **four hours**
+- On **Manual Sync** (API call)
+ - You can call `/v3/connections/{provider}/sync` to sync documents manually
diff --git a/apps/docs/memory-api/creation/adding-memories.mdx b/apps/docs/memory-api/creation/adding-memories.mdx
new file mode 100644
index 00000000..9b34b3bb
--- /dev/null
+++ b/apps/docs/memory-api/creation/adding-memories.mdx
@@ -0,0 +1,376 @@
+---
+title: "Adding Memories"
+description: "Learn how to add content to supermemory"
+icon: "plus"
+---
+
+<Accordion title="Best Practices" icon="sparkles">
+1. **Content Organization**
+ - **Use `containerTags` for grouping/partitioning**
+ - Optional tags (array of strings) to group memories.
+ - Can be a user ID, project ID, or any other identifier.
+ - Allows filtering for memories that share specific tags.
+ - Example: `["user_123", "project_alpha"]`
+
+ Read more about [filtering](/memory-api/features/filtering)
+
+2. **Performance Tips**
+ - **Batch Operations**
+ - You can add multiple items in parallel
+ - Use different `containerTags` for different spaces
+ - Don't wait for processing to complete unless needed
+
+ - **Search Optimization**
+ ```json
+ {
+ "q": "error logs",
+ "documentThreshold": 0.7, // Higher = more precise
+ "limit": 5, // Keep it small
+ "onlyMatchingChunks": true // Skip extra context if not needed
+ }
+ ```
+
+3. **URL Content**
+ - Send clean URLs without tracking parameters
+ - Use article URLs, not homepage URLs
+ - Check URL accessibility before sending
+
+</Accordion>
+
+## Basic Usage
+
+To add a memory, send a POST request to `/add` with your content:
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/documents \
+ --request POST \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ --data '{
+ "customId": "xyz-my-db-id",
+ "content": "This is the content of my memory",
+ "metadata": {
+ "category": "technology",
+ "tag_1": "ai",
+ "tag_2": "machine-learning",
+ },
+ "containerTags": ["user_123", "project_xyz"]
+}'
+```
+
+```typescript Typescript
+await client.memory.create({
+ customId: "xyz-mydb-id",
+ content: "This is the content of my memory",
+ metadata: {
+ category: "technology",
+ tag_1": "ai",
+ tag_2": "machine-learning",
+ },
+ containerTags: ["user_123", "project_xyz"]
+})
+```
+
+```python Python
+client.memory.create(
+ customId="xyz-mydb-id",
+ content="documents related to python",
+ metadata={
+ "category": "datascience",
+ "tag_1": "ai",
+ "tag_2": "machine-learning",
+ },
+ containerTags=["user_123", "project_xyz"]
+)
+```
+
+</CodeGroup>
+
+The API will return a response with an ID and initial status:
+
+```json
+{
+ "id": "mem_abc123",
+ "status": "queued"
+}
+```
+
+<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": "https://example.com/article",
+ "metadata": {
+ "source": "web", # Just example metadata
+ "category": "technology" # NOT required
+ },
+ "containerTags": ["user_456", "research_papers"]
+ }'
+```
+
+```typescript Typescript
+await client.memory.create({
+ content: "https://example.com/article",
+ userId: "user_456",
+ metadata: {
+ source: "web", // Just example metadata
+ category: "technology", // NOT required
+ },
+ containerTags: ["user_456", "research_papers"],
+});
+```
+
+```python Python
+client.memory.create(
+ content="https://example.com/article",
+ userId="user_456",
+ metadata={
+ "source": "web",
+ "category": "technology"
+ },
+ containerTags=["user_456", "research_papers"]
+)
+```
+
+</CodeGroup>
+
+
+## Metadata and Organization
+
+You can add rich metadata to organize your content:
+
+```json
+{
+ "metadata": {
+ "source": "string", // String
+ "priority": 1234, // Custom numeric field
+ "custom_field": "any" // Any custom field
+ }
+}
+```
+
+
+## Partitioning by user
+
+You can attribute and partition your data by providing a `userId`:
+
+<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 space-specific content",
+ "userId": "space_123",
+ "metadata": {
+ "category": "space-content"
+ }
+ }'
+```
+
+```typescript Typescript
+await client.memory.create({
+ content: "This is space-specific content",
+ userId: "space_123",
+ metadata: {
+ category: "space-content",
+ },
+});
+```
+
+```python Python
+client.memory.create(
+ content="This is space-specific content",
+ userId="space_123",
+ metadata={
+ "category": "space-content"
+ }
+)
+```
+
+</CodeGroup>
+
+<Note>
+ When searching, if you provide a `userId`, only memories from that space will
+ be returned.
+</Note>
+
+## Grouping
+
+You can group memories by providing an array of `containerTags`:
+
+<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 space-specific content",
+ "containerTags": ["user_123", "project_xyz"]
+ }'
+```
+
+```typescript Typescript
+await client.memory.create({
+ content: "This is space-specific content",
+ containerTags: ["user_123", "project_xyz"],
+});
+```
+
+```python Python
+client.memory.create(
+ content="This is space-specific content",
+ containerTags=["user_123", "project_xyz"]
+)
+```
+
+</CodeGroup>
+
+## Checking Status
+
+Check status using the memory ID:
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/documents/mem_abc123 \
+ --request GET \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY'
+```
+
+```typescript Typescript
+await client.memory.get("mem_abc123");
+```
+
+```python Python
+client.memory.get("mem_abc123")
+```
+
+</CodeGroup>
+
+<Warning>
+
+Memories are deleted after 2 minutes if an irrecoverable error occurs.
+
+</Warning>
+
+## File Uploads
+
+For file uploads, use the dedicated file upload endpoint. You can include `containerTags` directly in the form data:
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/documents/file \
+ --request POST \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ --form 'file=@/path/to/your/file.pdf' \
+ --form 'containerTags=["user_123", "project_xyz"]'
+```
+
+```typescript Typescript
+const formData = new FormData();
+formData.append("file", fileBlob);
+formData.append("containerTags", JSON.stringify(["user_123", "project_xyz"]));
+
+const response = await fetch("https://api.supermemory.ai/v3/documents/file", {
+ method: "POST",
+ headers: {
+ Authorization: "Bearer SUPERMEMORY_API_KEY",
+ },
+ body: formData,
+});
+```
+
+```python Python
+import requests
+import json
+
+with open('/path/to/your/file.pdf', 'rb') as f:
+ files = {'file': f}
+ data = {'containerTags': json.dumps(["user_123", "project_xyz"])}
+ response = requests.post(
+ 'https://api.supermemory.ai/v3/documents/file',
+ headers={'Authorization': 'Bearer SUPERMEMORY_API_KEY'},
+ files=files,
+ data=data
+ )
+```
+
+</CodeGroup>
+
+### Adding Additional Metadata to Files
+
+If you need to add additional metadata (like title or description) after upload, you can use the PATCH endpoint:
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/documents/MEMORY_ID \
+ --request PATCH \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ --data '{
+ "metadata": {
+ "title": "My Document",
+ "description": "Important project document"
+ }
+ }'
+```
+
+```typescript Typescript
+await fetch(`https://api.supermemory.ai/v3/documents/${memoryId}`, {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: "Bearer SUPERMEMORY_API_KEY",
+ },
+ body: JSON.stringify({
+ metadata: {
+ title: "My Document",
+ description: "Important project document",
+ },
+ }),
+});
+```
+
+```python Python
+import requests
+
+requests.patch(
+ f'https://api.supermemory.ai/v3/documents/{memory_id}',
+ headers={
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer SUPERMEMORY_API_KEY'
+ },
+ json={
+ 'metadata': {
+ 'title': 'My Document',
+ 'description': 'Important project document'
+ }
+ }
+)
+```
+
+</CodeGroup>
+
+<Note>
+ The file upload endpoint returns immediately with a memory ID and processing
+ status. The file will be processed asynchronously, and you can check its
+ status using the GET endpoint.
+</Note>
+
+## Next Steps
+
+Explore more advanced features in our [API Reference](/api-reference/manage-memories/add-memory)
diff --git a/apps/docs/memory-api/creation/status.mdx b/apps/docs/memory-api/creation/status.mdx
new file mode 100644
index 00000000..44a53656
--- /dev/null
+++ b/apps/docs/memory-api/creation/status.mdx
@@ -0,0 +1,14 @@
+---
+title: "Processing Status"
+description: "Learn about the stages of content processing"
+---
+
+After adding content, you can check its processing status:
+
+1. `queued`: Content is queued for processing
+2. `extracting`: Extracting content from source
+3. `chunking`: Splitting content into semantic chunks
+4. `embedding`: Generating vector embeddings
+5. `indexing`: Adding to search index
+6. `done`: Processing complete
+7. `failed`: Processing failed \ No newline at end of file
diff --git a/apps/docs/memory-api/features/auto-multi-modal.mdx b/apps/docs/memory-api/features/auto-multi-modal.mdx
new file mode 100644
index 00000000..df20c318
--- /dev/null
+++ b/apps/docs/memory-api/features/auto-multi-modal.mdx
@@ -0,0 +1,181 @@
+---
+title: "Auto Multi Modal"
+description: "supermemory automatically detects the content type of the document you are adding."
+icon: "sparkles"
+---
+
+supermemory is natively multi-modal, and can automatically detect the content type of the document you are adding.
+
+We use the best of breed tools to extract content from URLs, and process it for optimal memory storage.
+
+## Automatic Content Type Detection
+
+supermemory automatically detects the content type of the document you're adding. Simply pass your content to the API, and supermemory will handle the rest.
+
+<Tabs>
+ <Tab title="How It Works">
+ The content detection system analyzes:
+ - URL patterns and domains
+ - File extensions and MIME types
+ - Content structure and metadata
+ - Headers and response types
+ </Tab>
+ <Tab title="Best Practices">
+ <Accordion title="Content Type Best Practices" defaultOpen icon="sparkles">
+ 1. **Type Selection**
+ - Use `note` for simple text
+ - Use `webpage` for online content
+ - Use native types when possible
+
+ 2. **URL Content**
+ - Send clean URLs without tracking parameters
+ - Use article URLs, not homepage URLs
+ - Check URL accessibility before sending
+ </Accordion>
+
+ </Tab>
+</Tabs>
+
+### Quick Implementation
+
+All you need to do is pass the content to the `/documents` endpoint:
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/documents \
+ --request POST \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ -d '{"content": "https://example.com/article"}'
+```
+
+```typescript
+await client.add.create({
+ content: "https://example.com/article",
+});
+```
+
+```python
+client.add.create(
+ content="https://example.com/article"
+)
+```
+
+</CodeGroup>
+
+<Note>
+ supermemory uses [Markdowner](https://md.dhr.wtf) to extract content from
+ URLs.
+</Note>
+
+## Supported Content Types
+
+supermemory supports a wide range of content formats to ensure versatility in memory creation:
+
+<Grid cols={2}>
+ <Card title="Text Content" icon="document-text">
+ - `note`: Plain text notes and documents
+ - Directly processes raw text content
+ - Automatically chunks content for optimal retrieval
+ - Preserves formatting and structure
+ </Card>
+
+ <Card title="Web Content" icon="globe">
+ - `webpage`: Web pages (just provide the URL)
+ - Intelligently extracts main content
+ - Preserves important metadata (title, description, images)
+ - Extracts OpenGraph metadata when available
+
+ - `tweet`: Twitter content
+ - Captures tweet text, media, and metadata
+ - Preserves thread structure if applicable
+
+ </Card>
+
+ <Card title="Document Types" icon="document">
+ - `pdf`: PDF files
+ - Extracts text content while maintaining structure
+ - Handles both searchable PDFs and scanned documents with OCR
+ - Preserves page breaks and formatting
+
+ - `google_doc`: Google Documents
+ - Seamlessly integrates with Google Docs API
+ - Maintains document formatting and structure
+ - Auto-updates when source document changes
+
+ - `notion_doc`: Notion pages
+ - Extracts content while preserving Notion's block structure
+ - Handles rich text formatting and embedded content
+
+ </Card>
+
+ <Card title="Media Types" icon="photo">
+ - `image`: Images with text content
+ - Advanced OCR for text extraction
+ - Visual content analysis and description
+
+ - `video`: Video content
+ - Transcription and content extraction
+ - Key frame analysis
+
+ </Card>
+</Grid>
+
+## Processing Pipeline
+
+<Steps>
+ <Step title="Content Detection">
+ supermemory automatically identifies the content type based on the input provided.
+ </Step>
+
+<Step title="Content Extraction">
+ Type-specific extractors process the content with: - Specialized parsing for
+ each format - Error handling with retries - Rate limit management
+</Step>
+
+ <Step title="AI Enhancement">
+ ```typescript
+ interface ProcessedContent {
+ content: string; // Extracted text
+ summary?: string; // AI-generated summary
+ tags?: string[]; // Extracted tags
+ categories?: string[]; // Content categories
+ }
+ ```
+ </Step>
+
+ <Step title="Chunking & Indexing">
+ - Sentence-level splitting
+ - 2-sentence overlap
+ - Context preservation
+ - Semantic coherence
+ </Step>
+</Steps>
+
+## Technical Specifications
+
+### Size Limits
+
+| Content Type | Max Size |
+| ------------ | -------- |
+| Text/Note | 1MB |
+| PDF | 10MB |
+| Image | 5MB |
+| Video | 100MB |
+| Web Page | N/A |
+| Google Doc | N/A |
+| Notion Page | N/A |
+| Tweet | N/A |
+
+### Processing Time
+
+| Content Type | Processing Time |
+| ------------ | --------------- |
+| Text/Note | Almost instant |
+| PDF | 1-5 seconds |
+| Image | 2-10 seconds |
+| Video | 10+ seconds |
+| Web Page | 1-3 seconds |
+| Google Doc | N/A |
+| Notion Page | N/A |
+| Tweet | N/A |
diff --git a/apps/docs/memory-api/features/content-cleaner.mdx b/apps/docs/memory-api/features/content-cleaner.mdx
new file mode 100644
index 00000000..e586c3dc
--- /dev/null
+++ b/apps/docs/memory-api/features/content-cleaner.mdx
@@ -0,0 +1,86 @@
+---
+title: "Cleaning and Categorizing"
+description: "Document Cleaning Summaries in supermemory"
+icon: "washing-machine"
+---
+
+supermemory provides advanced configuration options to customize your content processing pipeline. At its core is an AI-powered system that can automatically analyze, categorize, and filter your content based on your specific needs.
+
+## Configuration Schema
+
+```json
+{
+ "shouldLLMFilter": true,
+ "categories": ["feature-request", "bug-report", "positive", "negative"],
+ "filterPrompt": "Analyze feedback sentiment and identify feature requests",
+ "includeItems": ["critical", "high-priority"],
+ "excludeItems": ["spam", "irrelevant"]
+}
+```
+
+## Core Settings
+
+### shouldLLMFilter
+- **Type**: `boolean`
+- **Required**: No (defaults to `false`)
+- **Description**: Master switch for AI-powered content analysis. Must be enabled to use any of the advanced filtering features.
+
+### categories
+- **Type**: `string[]`
+- **Limits**: Each category must be 1-50 characters
+- **Required**: No
+- **Description**: Define custom categories for content classification. When specified, the AI will only use these categories. If not specified, it will generate 3-5 relevant categories automatically.
+
+### filterPrompt
+- **Type**: `string`
+- **Limits**: 1-750 characters
+- **Required**: No
+- **Description**: Custom instructions for the AI on how to analyze and categorize content. Use this to guide the categorization process based on your specific needs.
+
+### includeItems & excludeItems
+- **Type**: `string[]`
+- **Limits**: Each item must be 1-20 characters
+- **Required**: No
+- **Description**: Fine-tune content filtering by specifying items to explicitly include or exclude during processing.
+
+## Content Processing Pipeline
+
+When content is ingested with LLM filtering enabled:
+
+1. **Initial Processing**
+ - Content is extracted and normalized
+ - Basic metadata (title, description) is captured
+
+2. **AI Analysis**
+ - Content is analyzed based on your `filterPrompt`
+ - Categories are assigned (either from your predefined list or auto-generated)
+ - Tags are evaluated and scored
+
+3. **Chunking & Indexing**
+ - Content is split into semantic chunks
+ - Each chunk is embedded for efficient search
+ - Metadata and classifications are stored
+
+## Example Use Cases
+
+### 1. Customer Feedback System
+```json
+{
+ "shouldLLMFilter": true,
+ "categories": ["positive", "negative", "neutral"],
+ "filterPrompt": "Analyze customer sentiment and identify key themes",
+}
+```
+
+### 2. Content Moderation
+```json
+{
+ "shouldLLMFilter": true,
+ "categories": ["safe", "needs-review", "flagged"],
+ "filterPrompt": "Identify potentially inappropriate or sensitive content",
+ "excludeItems": ["spam", "offensive"],
+ "includeItems": ["user-generated"]
+}
+```
+
+> **Important**: All filtering features (`categories`, `filterPrompt`, `includeItems`, `excludeItems`) require `shouldLLMFilter` to be enabled. Attempting to use these features without enabling `shouldLLMFilter` will result in a 400 error.
diff --git a/apps/docs/memory-api/features/filtering.mdx b/apps/docs/memory-api/features/filtering.mdx
new file mode 100644
index 00000000..3873e606
--- /dev/null
+++ b/apps/docs/memory-api/features/filtering.mdx
@@ -0,0 +1,297 @@
+---
+title: "Filtering"
+description: "Learn how to filter content while searching from supermemory"
+icon: "list-filter-plus"
+---
+
+## Container Tag
+
+Container tag is an identifier for your end users, to group memories together..
+
+This can be:
+- A user using your product
+- An organization using a SaaS
+
+A project ID, or even a dynamic one like `user_project_etc`
+
+We recommend using single containerTag in all API requests.
+
+The graph is built on top of the Container Tags. For example, each user / tag in your supermemory account will have one single graph built for them.
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/search \
+ --request POST \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ --data '{
+ "q": "machine learning",
+ "containerTags": ["user_123"]
+ }'
+```
+
+```typescript Typescript
+await client.search.execute({
+ q: "machine learning",
+ containerTags: ["user_123"],
+});
+```
+
+```python Python
+client.search.execute(
+ q="machine learning",
+ containerTags=["user_123"]
+)
+```
+
+</CodeGroup>
+
+## Metadata
+
+Sometimes, you might want to add metadata and do advanced filtering based on it.
+
+Using metadata filtering, you can search based on:
+
+- AND and OR conditions
+- String matching
+- Numeric matching
+- Date matching
+- Time range queries
+
+### Validation Rules & Limits
+
+To ensure optimal performance and security, the filtering system has the following limits:
+
+- **Metadata keys**: Must contain only alphanumeric characters, underscores, and hyphens (`/^[a-zA-Z0-9_-]+$/`)
+- **Metadata key length**: Maximum of 64 characters
+- **Maximum conditions**: Up to 200 conditions per query
+- **Maximum nesting depth**: Up to 8 levels of nested AND/OR expressions
+- **Valid operators**: `=`, `!=`, `<`, `<=`, `>`, `>=` for numeric filtering
+
+<Warning>
+These limits help prevent overly complex queries that could impact performance. If you need to filter on more conditions, consider breaking your query into multiple requests or using broader search terms with post-processing.
+</Warning>
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/search \
+ --request POST \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ --data '{
+ "q": "machine learning",
+ "filters": {
+ "AND": [
+ {
+ "key": "category",
+ "value": "technology",
+ "negate": false
+ },
+ {
+ "filterType": "numeric",
+ "key": "readingTime",
+ "value": "5",
+ "negate": false,
+ "numericOperator": "<="
+ }
+ ]
+ }
+}'
+```
+
+```typescript Typescript
+await client.search.execute({
+ q: "machine learning",
+ filters: {
+ AND: [
+ {
+ key: "category",
+ value: "technology",
+ negate: false,
+ },
+ {
+ filterType: "numeric",
+ key: "readingTime",
+ value: "5",
+ negate: false,
+ numericOperator: "<=",
+ },
+ ],
+ },
+});
+```
+
+```python Python
+client.search.execute(
+ q="machine learning",
+ filters={
+ "AND": [
+ {
+ "key": "category",
+ "value": "technology",
+ "negate": false
+ },
+ {
+ "filterType": "numeric",
+ "key": "readingTime",
+ "value": "5",
+ "negate": false,
+ "numericOperator": "<="
+ }
+ ]
+ }
+)
+```
+
+</CodeGroup>
+
+## Array Contains Filtering
+
+You can filter memories by array values using the `array_contains` filter type. This is particularly useful for filtering by participants or other array-based metadata.
+
+First, create a memory with participants in the metadata:
+
+<CodeGroup>
+
+```bash cURL
+curl --location 'https://api.supermemory.ai/v3/documents' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+--data '{
+ "content": "quarterly planning meeting discussion",
+ "metadata": {
+ "participants": ["john.doe", "sarah.smith", "mike.wilson"]
+ }
+ }'
+```
+
+```typescript Typescript
+await client.memories.create({
+ content: "quarterly planning meeting discussion",
+ metadata: {
+ participants: ["john.doe", "sarah.smith", "mike.wilson"]
+ }
+});
+```
+
+```python Python
+client.memories.create(
+ content="quarterly planning meeting discussion",
+ metadata={
+ "participants": ["john.doe", "sarah.smith", "mike.wilson"]
+ }
+)
+```
+
+</CodeGroup>
+
+Then search using the `array_contains` filter:
+
+<CodeGroup>
+
+```bash cURL
+curl --location 'https://api.supermemory.ai/v3/search' \
+--header 'Content-Type: application/json' \
+--header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+--data '{
+ "q": "meeting",
+ "filters": {
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ "limit": 5
+ }'
+```
+
+```typescript Typescript
+await client.search.execute({
+ q: "meeting",
+ filters: {
+ AND: [
+ {
+ key: "participants",
+ value: "john.doe",
+ filterType: "array_contains"
+ }
+ ]
+ },
+ limit: 5
+});
+```
+
+```python Python
+client.search.execute(
+ q="meeting",
+ filters={
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ limit=5
+)
+```
+
+</CodeGroup>
+
+## Migration Notes
+
+<Note>
+**Breaking Changes**: Recent updates to the filtering system have introduced stricter validation rules. If you're experiencing filter validation errors, please check the following:
+
+1. **Metadata Key Format**: Ensure all metadata keys only contain alphanumeric characters, underscores, and hyphens. Keys with spaces, dots, or other special characters will now fail validation.
+
+2. **Key Length**: Metadata keys must be 64 characters or fewer.
+
+3. **Filter Complexity**: Queries with more than 200 conditions or more than 8 levels of nesting will be rejected.
+
+**Example of invalid keys that need updating**:
+- `"user.email"` → `"user_email"`
+- `"reading time"` → `"reading_time"`
+- `"category-with-very-long-name-that-exceeds-the-limit"` → `"category_name"`
+</Note>
+
+## Document
+
+You can also find chunks within a specific, large document.
+
+This can be particularly useful for extremely large documents like Books, Podcasts, etc.
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/search \
+ --request POST \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ --data '{
+ "q": "machine learning",
+ "docId": "doc_123"
+ }'
+```
+
+```typescript Typescript
+await client.search.execute({
+ q: "machine learning",
+ docId: "doc_123",
+});
+```
+
+```python Python
+client.search.execute(
+ q="machine learning",
+ docId="doc_123"
+)
+```
+
+</CodeGroup>
diff --git a/apps/docs/memory-api/features/query-rewriting.mdx b/apps/docs/memory-api/features/query-rewriting.mdx
new file mode 100644
index 00000000..9508297a
--- /dev/null
+++ b/apps/docs/memory-api/features/query-rewriting.mdx
@@ -0,0 +1,50 @@
+---
+title: "Query Rewriting"
+description: "Query Rewriting in supermemory"
+icon: "blend"
+---
+
+Query Rewriting is a feature that allows you to rewrite queries to make them more accurate.
+
+![Query Rewriting](/images/query-rewriting.png)
+
+### Usage
+
+In supermemory, you can enable query rewriting by setting the `rewriteQuery` parameter to `true` in the search API.
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/search \
+ --request POST \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ --header 'Content-Type: application/json' \
+ -d '{
+ "q": "What is the capital of France?",
+ "rewriteQuery": true
+ }'
+```
+
+```typescript
+await client.search.create({
+ q: "What is the capital of France?",
+ rewriteQuery: true,
+});
+```
+
+```python
+client.search.create(
+ q="What is the capital of France?",
+ rewriteQuery=True
+)
+```
+
+</CodeGroup>
+
+### Notes and limitations
+
+- supermemory generates multiple rewrites, and runs the search through all of them.
+- The results are then merged and returned to you.
+- There is no additional costs associated with query rewriting.
+- While query rewriting makes the quality much better, it also **incurs additional latency**.
+- All other features like filtering, hybrid search, recency bias, etc. work with rewritten results as well.
diff --git a/apps/docs/memory-api/features/reranking.mdx b/apps/docs/memory-api/features/reranking.mdx
new file mode 100644
index 00000000..1df8a9c5
--- /dev/null
+++ b/apps/docs/memory-api/features/reranking.mdx
@@ -0,0 +1,44 @@
+---
+title: "Reranking"
+description: "Reranked search results in supermemory"
+icon: "chart-bar-increasing"
+---
+
+Reranking is a feature that allows you to rerank search results based on the query.
+
+![Reranking](/images/rerank.png)
+
+### Usage
+
+In supermemory, you can enable answer rewriting by setting the `rerank` parameter to `true` in the search API.
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/search?q=What+is+the+capital+of+France?&rerank=true \
+ --request GET \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY'
+```
+
+```typescript
+await client.search.create({
+ q: "What is the capital of France?",
+ rerank: true,
+});
+```
+
+```python
+client.search.create(
+ q="What is the capital of France?",
+ rerank=True
+)
+```
+
+</CodeGroup>
+
+### Notes and limitations
+
+- We currently use `bge-reranker-base` model for reranking.
+- There is no additional costs associated with reranking.
+- While reranking makes the quality much better, it also **incurs additional latency**.
+- All other features like filtering, hybrid search, recency bias, etc. work with reranked results as well.
diff --git a/apps/docs/memory-api/ingesting.mdx b/apps/docs/memory-api/ingesting.mdx
new file mode 100644
index 00000000..87e27330
--- /dev/null
+++ b/apps/docs/memory-api/ingesting.mdx
@@ -0,0 +1,861 @@
+---
+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.memories.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.memories.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 "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.memories.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.memories.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**
+- Old memories are deleted
+- New memories created from updated content
+- Same document ID maintained
+
+### 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, // CORRECTED: Conservative batch size
+ delayBetweenBatches = 2000, // CORRECTED: 2 second delays
+ 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.memories.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.memories.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>
diff --git a/apps/docs/memory-api/introduction.mdx b/apps/docs/memory-api/introduction.mdx
new file mode 100644
index 00000000..8ff4547e
--- /dev/null
+++ b/apps/docs/memory-api/introduction.mdx
@@ -0,0 +1,43 @@
+---
+title: "Introduction - Memory endpoints"
+sidebarTitle: "Introduction"
+description: "Ingest content at scale, in any format."
+---
+
+**supermemory** automatically **ingests and processes your data**, and makes it searchable.
+
+<Info>
+ The Memory engine scales linearly - which means we're **incredibly fast and scalable**, while providing one of the more affordable
+</Info>
+
+![supermemory](/images/processing.png)
+
+It also gives you features like:
+
+- [Connectors and Syncing](/memory-api/connectors/)
+- [Multimodality](/memory-api/features/auto-multi-modal)
+- [Advanced Filtering](/memory-api/features/filtering)
+- [Reranking](/memory-api/features/reranking)
+- [Extracting details from text](/memory-api/features/content-cleaner)
+- [Query Rewriting](/memory-api/features/query-rewriting)
+
+... and lots more\!
+
+
+Check out the following resources to get started:
+
+
+<CardGroup cols={2}>
+ <Card title="Quickstart" icon="zap" href="/memory-api/overview">
+ Get started in 5 minutes
+ </Card>
+ <Card title="API Reference" icon="unplug" href="/api-reference">
+ Learn more about the API
+ </Card>
+ <Card title="Use Cases" icon="brain" href="/overview/use-cases">
+ See what supermemory can do for you
+ </Card>
+ <Card title="SDKs" icon="code" href="/memory-api/sdks/">
+ Learn more about the SDKs
+ </Card>
+</CardGroup> \ No newline at end of file
diff --git a/apps/docs/memory-api/overview.mdx b/apps/docs/memory-api/overview.mdx
new file mode 100644
index 00000000..33771e2c
--- /dev/null
+++ b/apps/docs/memory-api/overview.mdx
@@ -0,0 +1,162 @@
+---
+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 Playground](/api-reference/manage-memories/add-memory).
+
+## 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 Playground](/api-reference/search-memories/search-memories).
+
+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
+ </Card>
+ <Card
+ title="Searching and filtering"
+ icon="search"
+ href="/memory-api/searching"
+ >
+ Searching for items
+ </Card>
+ <Card
+ title="Connectors and Syncing"
+ icon="plug"
+ href="/memory-api/connectors"
+ >
+ Connecting external sources
+ </Card>
+ <Card title="Features" icon="sparkles" href="/memory-api/features">
+ Explore Features
+ </Card>
+</CardGroup>
diff --git a/apps/docs/memory-api/sdks/native.mdx b/apps/docs/memory-api/sdks/native.mdx
new file mode 100644
index 00000000..67f79d18
--- /dev/null
+++ b/apps/docs/memory-api/sdks/native.mdx
@@ -0,0 +1,68 @@
+---
+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();
+```
diff --git a/apps/docs/memory-api/sdks/openai-plugins.mdx b/apps/docs/memory-api/sdks/openai-plugins.mdx
new file mode 100644
index 00000000..2fb0a789
--- /dev/null
+++ b/apps/docs/memory-api/sdks/openai-plugins.mdx
@@ -0,0 +1,584 @@
+---
+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-4o",
+ 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-4",
+ 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!, {
+ projectId: "your-project-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-4o",
+ 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-4o",
+ 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-4",
+ 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-4",
+ 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-4o",
+ 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-4",
+ 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="/ai-sdk/overview">
+ 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>
diff --git a/apps/docs/memory-api/sdks/overview.mdx b/apps/docs/memory-api/sdks/overview.mdx
new file mode 100644
index 00000000..c0f536b5
--- /dev/null
+++ b/apps/docs/memory-api/sdks/overview.mdx
@@ -0,0 +1,24 @@
+---
+title: "Overview"
+---
+
+<Columns cols={2}>
+ <Card title="Native Python and Typescript/JS SDKs" icon="code" href="/memory-api/sdks/native">
+ <br/>
+ ```pip install supermemory```
+
+ ```npm install supermemory```
+ </Card>
+
+ <Card title="AI SDK plugin" icon="triangle" href="/ai-sdk/overview">
+ Easy to use with Vercel AI SDK
+ </Card>
+
+ <Card title="OpenAI SDK plugins" icon="sparkles" href="/memory-api/sdks/openai-plugins">
+ Use supermemory with the python and javascript OpenAI SDKs
+ </Card>
+
+ <Card title="Request more plugins" icon="life-buoy" href="mailto:[email protected]">
+ We will add support for your favorite SDKs asap.
+ </Card>
+</Columns>
diff --git a/apps/docs/memory-api/sdks/python.mdx b/apps/docs/memory-api/sdks/python.mdx
new file mode 100644
index 00000000..2b1f56fc
--- /dev/null
+++ b/apps/docs/memory-api/sdks/python.mdx
@@ -0,0 +1,349 @@
+---
+title: 'Python SDK'
+sidebarTitle: "Python"
+description: 'Learn how to use supermemory with Python'
+---
+
+## 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.execute(
+ q="documents related to python",
+)
+print(response.results)
+```
+
+While you can provide an `api_key` keyword argument,
+we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
+to add `SUPERMEMORY_API_KEY="My API Key"` to your `.env` file
+so that your API Key is not stored in source control.
+
+## Async usage
+
+Simply import `AsyncSupermemory` instead of `supermemory` and use `await` with each API call:
+
+```python
+import os
+import asyncio
+from supermemory import AsyncSupermemory
+
+client = AsyncSupermemory(
+ api_key=os.environ.get("SUPERMEMORY_API_KEY"), # This is the default and can be omitted
+)
+
+
+async def main() -> None:
+ response = await client.search.execute(
+ q="documents related to python",
+ )
+ print(response.results)
+
+
+asyncio.run(main())
+```
+
+Functionality between the synchronous and asynchronous clients is otherwise identical.
+
+## Using types
+
+Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like:
+
+- Serializing back into JSON, `model.to_json()`
+- Converting to a dictionary, `model.to_dict()`
+
+Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.
+
+## File uploads
+
+Request parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`.
+
+```python
+from pathlib import Path
+from supermemory import Supermemory
+
+client = supermemory()
+
+client.memories.upload_file(
+ file=Path("/path/to/file"),
+)
+```
+
+The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically.
+
+## Handling errors
+
+When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `supermemory.APIConnectionError` is raised.
+
+When the API returns a non-success status code (that is, 4xx or 5xx
+response), a subclass of `supermemory.APIStatusError` is raised, containing `status_code` and `response` properties.
+
+All errors inherit from `supermemory.APIError`.
+
+```python
+import supermemory
+from supermemory import Supermemory
+
+client = supermemory()
+
+try:
+ client.memories.add(
+ content="This is a detailed article about machine learning concepts...",
+ )
+except supermemory.APIConnectionError as e:
+ print("The server could not be reached")
+ print(e.__cause__) # an underlying Exception, likely raised within httpx.
+except supermemory.RateLimitError as e:
+ print("A 429 status code was received; we should back off a bit.")
+except supermemory.APIStatusError as e:
+ print("Another non-200-range status code was received")
+ print(e.status_code)
+ print(e.response)
+```
+
+Error codes are as follows:
+
+| Status Code | Error Type |
+| ----------- | -------------------------- |
+| 400 | `BadRequestError` |
+| 401 | `AuthenticationError` |
+| 403 | `PermissionDeniedError` |
+| 404 | `NotFoundError` |
+| 422 | `UnprocessableEntityError` |
+| 429 | `RateLimitError` |
+| >=500 | `InternalServerError` |
+| N/A | `APIConnectionError` |
+
+### Retries
+
+Certain errors are automatically retried 2 times by default, with a short exponential backoff.
+Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,
+429 Rate Limit, and >=500 Internal errors are all retried by default.
+
+You can use the `max_retries` option to configure or disable retry settings:
+
+```python
+from supermemory import Supermemory
+
+# Configure the default for all requests:
+client = supermemory(
+ # default is 2
+ max_retries=0,
+)
+
+# Or, configure per-request:
+client.with_options(max_retries=5).memories.add(
+ content="This is a detailed article about machine learning concepts...",
+)
+```
+
+### Timeouts
+
+By default requests time out after 1 minute. You can configure this with a `timeout` option,
+which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/#fine-tuning-the-configuration) object:
+
+```python
+from supermemory import Supermemory
+
+# Configure the default for all requests:
+client = supermemory(
+ # 20 seconds (default is 1 minute)
+ timeout=20.0,
+)
+
+# More granular control:
+client = supermemory(
+ timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
+)
+
+# Override per-request:
+client.with_options(timeout=5.0).memories.add(
+ content="This is a detailed article about machine learning concepts...",
+)
+```
+
+On timeout, an `APITimeoutError` is thrown.
+
+Note that requests that time out are [retried twice by default](#retries).
+
+## Advanced
+
+### Logging
+
+We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.
+
+You can enable logging by setting the environment variable `SUPERMEMORY_LOG` to `info`.
+
+```shell
+$ export SUPERMEMORY_LOG=info
+```
+
+Or to `debug` for more verbose logging.
+
+### How to tell whether `None` means `null` or missing
+
+In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:
+
+```py
+if response.my_field is None:
+ if 'my_field' not in response.model_fields_set:
+ print('Got json like {}, without a "my_field" key present at all.')
+ else:
+ print('Got json like {"my_field": null}.')
+```
+
+### Accessing raw response data (e.g. headers)
+
+The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,
+
+```py
+from supermemory import Supermemory
+
+client = supermemory()
+response = client.memories.with_raw_response.add(
+ content="This is a detailed article about machine learning concepts...",
+)
+print(response.headers.get('X-My-Header'))
+
+memory = response.parse() # get the object that `memories.add()` would have returned
+print(memory.id)
+```
+
+These methods return an [`APIResponse`](https://github.com/supermemoryai/python-sdk/tree/main/src/supermemory/_response.py) object.
+
+The async client returns an [`AsyncAPIResponse`](https://github.com/supermemoryai/python-sdk/tree/main/src/supermemory/_response.py) with the same structure, the only difference being `await`able methods for reading the response content.
+
+#### `.with_streaming_response`
+
+The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
+
+To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.
+
+```python
+with client.memories.with_streaming_response.add(
+ content="This is a detailed article about machine learning concepts...",
+) as response:
+ print(response.headers.get("X-My-Header"))
+
+ for line in response.iter_lines():
+ print(line)
+```
+
+The context manager is required so that the response will reliably be closed.
+
+### Making custom/undocumented requests
+
+This library is typed for convenient access to the documented API.
+
+If you need to access undocumented endpoints, params, or response properties, the library can still be used.
+
+#### Undocumented endpoints
+
+To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other
+http verbs. Options on the client will be respected (such as retries) when making this request.
+
+```py
+import httpx
+
+response = client.post(
+ "/foo",
+ cast_to=httpx.Response,
+ body={"my_param": True},
+)
+
+print(response.headers.get("x-foo"))
+```
+
+#### Undocumented request params
+
+If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request
+options.
+
+#### Undocumented response properties
+
+To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You
+can also get all the extra fields on the Pydantic model as a dict with
+[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).
+
+### Configuring the HTTP client
+
+You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:
+
+- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)
+- Custom [transports](https://www.python-httpx.org/advanced/transports/)
+- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality
+
+```python
+import httpx
+from supermemory import Supermemory, DefaultHttpxClient
+
+client = supermemory(
+ # Or use the `SUPERMEMORY_BASE_URL` env var
+ base_url="http://my.test.server.example.com:8083",
+ http_client=DefaultHttpxClient(
+ proxy="http://my.test.proxy.example.com",
+ transport=httpx.HTTPTransport(local_address="0.0.0.0"),
+ ),
+)
+```
+
+You can also customize the client on a per-request basis by using `with_options()`:
+
+```python
+client.with_options(http_client=DefaultHttpxClient(...))
+```
+
+### Managing HTTP resources
+
+By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.
+
+```py
+from supermemory import Supermemory
+
+with supermemory() as client:
+ # make requests here
+ ...
+
+# HTTP client is now closed
+```
+
+## Versioning
+
+This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
+
+1. Changes that only affect static types, without breaking runtime behavior.
+2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_
+3. Changes that we do not expect to impact the vast majority of users in practice.
+
+We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
+
+We are keen for your feedback; please open an [issue](https://www.github.com/supermemoryai/python-sdk/issues) with questions, bugs, or suggestions.
+
+### Determining the installed version
+
+If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.
+
+You can determine the version that is being used at runtime with:
+
+```py
+import supermemory
+print(supermemory.__version__)
+```
+
+## Requirements
+
+Python 3.8 or higher. \ No newline at end of file
diff --git a/apps/docs/memory-api/sdks/supermemory-npm.mdx b/apps/docs/memory-api/sdks/supermemory-npm.mdx
new file mode 100644
index 00000000..c872458a
--- /dev/null
+++ b/apps/docs/memory-api/sdks/supermemory-npm.mdx
@@ -0,0 +1,5 @@
+---
+title: "`supermemory` on npm"
+url: "https://www.npmjs.com/package/supermemory"
+icon: npm
+---
diff --git a/apps/docs/memory-api/sdks/supermemory-pypi.mdx b/apps/docs/memory-api/sdks/supermemory-pypi.mdx
new file mode 100644
index 00000000..1b831245
--- /dev/null
+++ b/apps/docs/memory-api/sdks/supermemory-pypi.mdx
@@ -0,0 +1,5 @@
+---
+title: "`supermemory` on pypi"
+url: "https://pypi.org/project/supermemory/"
+icon: python
+---
diff --git a/apps/docs/memory-api/sdks/typescript.mdx b/apps/docs/memory-api/sdks/typescript.mdx
new file mode 100644
index 00000000..54cc7137
--- /dev/null
+++ b/apps/docs/memory-api/sdks/typescript.mdx
@@ -0,0 +1,391 @@
+---
+title: 'Typescript SDK'
+sidebarTitle: "Typescript"
+description: 'Learn how to use supermemory with Typescript'
+---
+
+## 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.execute({ q: 'documents related to python' });
+
+ console.debug(response.results);
+}
+
+main();
+```
+
+### Request & Response types
+
+This library includes TypeScript definitions for all request params and response fields. You may import and use them like so:
+
+
+```ts
+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 params: supermemory.MemoryAddParams = {
+ content: 'This is a detailed article about machine learning concepts...',
+ };
+ const response: supermemory.MemoryAddResponse = await client.memories.add(params);
+}
+
+main();
+```
+
+Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.
+
+## File uploads
+
+Request parameters that correspond to file uploads can be passed in many different forms:
+
+- `File` (or an object with the same structure)
+- a `fetch` `Response` (or an object with the same structure)
+- an `fs.ReadStream`
+- the return value of our `toFile` helper
+
+```ts
+import fs from 'fs';
+import supermemory, { toFile } from 'supermemory';
+
+const client = new supermemory();
+
+// If you have access to Node `fs` we recommend using `fs.createReadStream()`:
+await client.memories.uploadFile({ file: fs.createReadStream('/path/to/file') });
+
+// Or if you have the web `File` API you can pass a `File` instance:
+await client.memories.uploadFile({ file: new File(['my bytes'], 'file') });
+
+// You can also pass a `fetch` `Response`:
+await client.memories.uploadFile({ file: await fetch('https://somesite/file') });
+
+// Finally, if none of the above are convenient, you can use our `toFile` helper:
+await client.memories.uploadFile({ file: await toFile(Buffer.from('my bytes'), 'file') });
+await client.memories.uploadFile({ file: await toFile(new Uint8Array([0, 1, 2]), 'file') });
+```
+
+## Handling errors
+
+When the library is unable to connect to the API,
+or if the API returns a non-success status code (i.e., 4xx or 5xx response),
+a subclass of `APIError` will be thrown:
+
+
+```ts
+async function main() {
+ const response = await client.memories
+ .add({ content: 'This is a detailed article about machine learning concepts...' })
+ .catch(async (err) => {
+ if (err instanceof supermemory.APIError) {
+ console.debug(err.status); // 400
+ console.debug(err.name); // BadRequestError
+ console.debug(err.headers); // {server: 'nginx', ...}
+ } else {
+ throw err;
+ }
+ });
+}
+
+main();
+```
+
+Error codes are as follows:
+
+| Status Code | Error Type |
+| ----------- | -------------------------- |
+| 400 | `BadRequestError` |
+| 401 | `AuthenticationError` |
+| 403 | `PermissionDeniedError` |
+| 404 | `NotFoundError` |
+| 422 | `UnprocessableEntityError` |
+| 429 | `RateLimitError` |
+| >=500 | `InternalServerError` |
+| N/A | `APIConnectionError` |
+
+### Retries
+
+Certain errors will be automatically retried 2 times by default, with a short exponential backoff.
+Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,
+429 Rate Limit, and >=500 Internal errors will all be retried by default.
+
+You can use the `maxRetries` option to configure or disable this:
+
+
+```js
+// Configure the default for all requests:
+const client = new supermemory({
+ maxRetries: 0, // default is 2
+});
+
+// Or, configure per-request:
+await client.memories.add({ content: 'This is a detailed article about machine learning concepts...' }, {
+ maxRetries: 5,
+});
+```
+
+### Timeouts
+
+Requests time out after 1 minute by default. You can configure this with a `timeout` option:
+
+
+```ts
+// Configure the default for all requests:
+const client = new supermemory({
+ timeout: 20 * 1000, // 20 seconds (default is 1 minute)
+});
+
+// Override per-request:
+await client.memories.add({ content: 'This is a detailed article about machine learning concepts...' }, {
+ timeout: 5 * 1000,
+});
+```
+
+On timeout, an `APIConnectionTimeoutError` is thrown.
+
+Note that requests which time out will be [retried twice by default](#retries).
+
+## Advanced Usage
+
+### Accessing raw Response data (e.g., headers)
+
+The "raw" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return.
+This method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic.
+
+You can also use the `.withResponse()` method to get the raw `Response` along with the parsed data.
+Unlike `.asResponse()` this method consumes the body, returning once it is parsed.
+
+
+```ts
+const client = new supermemory();
+
+const response = await client.memories
+ .add({ content: 'This is a detailed article about machine learning concepts...' })
+ .asResponse();
+console.debug(response.headers.get('X-My-Header'));
+console.debug(response.statusText); // access the underlying Response object
+
+const { data: response, response: raw } = await client.memories
+ .add({ content: 'This is a detailed article about machine learning concepts...' })
+ .withResponse();
+console.debug(raw.headers.get('X-My-Header'));
+console.debug(response.id);
+```
+
+### Logging
+
+<Warning>
+All log messages are intended for debugging only. The format and content of log messages may change between releases.
+</Warning>
+
+#### Log levels
+
+The log level can be configured in two ways:
+
+1. Via the `SUPERMEMORY_LOG` environment variable
+2. Using the `logLevel` client option (overrides the environment variable if set)
+
+```ts
+import supermemory from 'supermemory';
+
+const client = new supermemory({
+ logLevel: 'debug', // Show all log messages
+});
+```
+
+Available log levels, from most to least verbose:
+
+- `'debug'` - Show debug messages, info, warnings, and errors
+- `'info'` - Show info messages, warnings, and errors
+- `'warn'` - Show warnings and errors (default)
+- `'error'` - Show only errors
+- `'off'` - Disable all logging
+
+At the `'debug'` level, all HTTP requests and responses are logged, including headers and bodies.
+Some authentication-related headers are redacted, but sensitive data in request and response bodies
+may still be visible.
+
+#### Custom logger
+
+By default, this library logs to `globalThis.console`. You can also provide a custom logger.
+Most logging libraries are supported, including [pino](https://www.npmjs.com/package/pino), [winston](https://www.npmjs.com/package/winston), [bunyan](https://www.npmjs.com/package/bunyan), [consola](https://www.npmjs.com/package/consola), [signale](https://www.npmjs.com/package/signale), and [@std/log](https://jsr.io/@std/log). If your logger doesn't work, please open an issue.
+
+When providing a custom logger, the `logLevel` option still controls which messages are emitted, messages
+below the configured level will not be sent to your logger.
+
+```ts
+import supermemory from 'supermemory';
+import pino from 'pino';
+
+const logger = pino();
+
+const client = new supermemory({
+ logger: logger.child({ name: 'supermemory' }),
+ logLevel: 'debug', // Send all messages to pino, allowing it to filter
+});
+```
+
+### Making custom/undocumented requests
+
+This library is typed for convenient access to the documented API. If you need to access undocumented
+endpoints, params, or response properties, the library can still be used.
+
+#### Undocumented endpoints
+
+To make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs.
+Options on the client, such as retries, will be respected when making these requests.
+
+```ts
+await client.post('/some/path', {
+ body: { some_prop: 'foo' },
+ query: { some_query_arg: 'bar' },
+});
+```
+
+#### Undocumented request params
+
+To make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented
+parameter. This library doesn't validate at runtime that the request matches the type, so any extra values you
+send will be sent as-is.
+
+```ts
+client.foo.create({
+ foo: 'my_param',
+ bar: 12,
+ // @ts-expect-error baz is not yet public
+ baz: 'undocumented option',
+});
+```
+
+For requests with the `GET` verb, any extra params will be in the query, all other requests will send the
+extra param in the body.
+
+If you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request
+options.
+
+#### Undocumented response properties
+
+To access undocumented response properties, you may access the response object with `// @ts-expect-error` on
+the response object, or cast the response object to the requisite type. Like the request params, we do not
+validate or strip extra properties from the response from the API.
+
+### Customizing the fetch client
+
+By default, this library expects a global `fetch` function is defined.
+
+If you want to use a different `fetch` function, you can either polyfill the global:
+
+```ts
+import fetch from 'my-fetch';
+
+globalThis.fetch = fetch;
+```
+
+Or pass it to the client:
+
+```ts
+import supermemory from 'supermemory';
+import fetch from 'my-fetch';
+
+const client = new supermemory({ fetch });
+```
+
+### Fetch options
+
+If you want to set custom `fetch` options without overriding the `fetch` function, you can provide a `fetchOptions` object when instantiating the client or making a request. (Request-specific options override client options.)
+
+```ts
+import supermemory from 'supermemory';
+
+const client = new supermemory({
+ fetchOptions: {
+ // `RequestInit` options
+ },
+});
+```
+
+#### Configuring proxies
+
+To modify proxy behavior, you can provide custom `fetchOptions` that add runtime-specific proxy options to requests:
+
+```ts
+import supermemory from 'supermemory';
+import * as undici from 'undici';
+
+const proxyAgent = new undici.ProxyAgent('http://localhost:8888');
+const client = new supermemory({
+ fetchOptions: {
+ dispatcher: proxyAgent,
+ },
+});
+```
+
+```ts
+import supermemory from 'supermemory';
+
+const client = new supermemory({
+ fetchOptions: {
+ proxy: 'http://localhost:8888',
+ },
+});
+```
+
+```ts
+import supermemory from 'npm:supermemory';
+
+const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });
+const client = new supermemory({
+ fetchOptions: {
+ client: httpClient,
+ },
+});
+```
+
+## Frequently Asked Questions
+
+## Semantic versioning
+
+This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
+
+1. Changes that only affect static types, without breaking runtime behavior.
+2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_
+3. Changes that we do not expect to impact the vast majority of users in practice.
+
+We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
+
+We are keen for your feedback; please open an [issue](https://www.github.com/supermemoryai/sdk-ts/issues) with questions, bugs, or suggestions.
+
+## Requirements
+
+TypeScript >= 4.9 is supported.
+
+The following runtimes are supported:
+
+- Web browsers (Up-to-date Chrome, Firefox, Safari, Edge, and more)
+- Node.js 20 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.
+- Deno v1.28.0 or higher.
+- Bun 1.0 or later.
+- Cloudflare Workers.
+- Vercel Edge Runtime.
+- Jest 28 or greater with the `"node"` environment (`"jsdom"` is not supported at this time).
+- Nitro v2.6 or greater.
+
+Note that React Native is not supported at this time.
+
+If you are interested in other runtime environments, please open or upvote an issue on GitHub. \ No newline at end of file
diff --git a/apps/docs/memory-api/searching/searching-memories.mdx b/apps/docs/memory-api/searching/searching-memories.mdx
new file mode 100644
index 00000000..517b835d
--- /dev/null
+++ b/apps/docs/memory-api/searching/searching-memories.mdx
@@ -0,0 +1,181 @@
+---
+title: "Searching Memories"
+description: "Learn how to search for and retrieve content from supermemory"
+---
+
+<Accordion title="Best Practices" defaultOpen icon="sparkles">
+1. **Query Formulation**:
+ - Use natural language queries
+ - Include relevant keywords
+ - Be specific but not too verbose
+
+2. **Filtering**:
+ - Use metadata filters for precision
+ - Combine multiple filters when needed
+ - Use appropriate thresholds
+
+3. **Performance**:
+ - Set appropriate result limits
+ - Use specific document/chunk filters
+ - Consider response timing
+
+</Accordion>
+
+## Basic Search
+
+To search through your memories, send a POST request to `/search`:
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/search?q=machine+learning+concepts&limit=10 \
+ --request GET \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY'
+```
+
+```typescript Typescript
+await client.search.execute({
+ q: "machine learning concepts",
+ limit: 10,
+});
+```
+
+```python Python
+client.search.execute(
+ q="machine learning concepts",
+ limit=10
+)
+```
+
+</CodeGroup>
+
+The API will return relevant matches with their similarity scores:
+
+```json
+{
+ "results": [
+ {
+ "documentId": "doc_xyz789",
+ "chunks": [
+ {
+ "content": "Machine learning is a subset of artificial intelligence...",
+ "isRelevant": true,
+ "score": 0.85
+ }
+ ],
+ "score": 0.95,
+ "metadata": {
+ "source": "web",
+ "category": "technology"
+ },
+ "title": "Introduction to Machine Learning"
+ }
+ ],
+ "total": 1,
+ "timing": 123.45
+}
+```
+
+## Search Parameters
+
+```json
+{
+ "q": "search query", // Required: Search query string
+ "limit": 10, // Optional: Max results (default: 10)
+ "threshold": 0.6, // Optional: Min similarity score (0-1, default: 0.6)
+ "containerTag": "user_123", // Optional: Filter by container tag
+ "rerank": false, // Optional: Rerank results for better relevance
+ "rewriteQuery": false, // Optional: Rewrite query for better matching
+ "include": {
+ "documents": false, // Optional: Include document metadata
+ "summaries": false, // Optional: Include document summaries
+ "relatedMemories": false, // Optional: Include related memory context
+ "forgottenMemories": false // Optional: Include forgotten memories in results
+ },
+ "filters": {
+ // Optional: Metadata filters
+ "AND": [
+ {
+ "key": "category",
+ "value": "technology"
+ }
+ ]
+ }
+}
+```
+
+## Search Response
+
+The search response includes:
+
+```json
+{
+ "results": [
+ {
+ "documentId": "string", // Document ID
+ "chunks": [
+ {
+ // Matching chunks
+ "content": "string", // Chunk content
+ "isRelevant": true, // Is directly relevant
+ "score": 0.95 // Similarity score
+ }
+ ],
+ "score": 0.95, // Document score
+ "metadata": {}, // Document metadata
+ "title": "string", // Document title
+ "createdAt": "string", // Creation date
+ "updatedAt": "string" // Last update date
+ }
+ ],
+ "total": 1, // Total results
+ "timing": 123.45 // Search time (ms)
+}
+```
+
+## Including Forgotten Memories
+
+By default, the search API excludes memories that have been marked as forgotten or have passed their expiration date. To include these in your search results, set `include.forgottenMemories` to `true`:
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v4/search \
+ --request POST \
+ --header 'Authorization: Bearer SUPERMEMORY_API_KEY' \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "q": "old project notes",
+ "include": {
+ "forgottenMemories": true
+ }
+ }'
+```
+
+```typescript Typescript
+await client.search.memories({
+ q: "old project notes",
+ include: {
+ forgottenMemories: true
+ }
+});
+```
+
+```python Python
+await client.search.memories(
+ q="old project notes",
+ include={
+ "forgottenMemories": True
+ }
+)
+```
+
+</CodeGroup>
+
+<Note>
+Forgotten memories are memories that have been explicitly forgotten using the forget API or have passed their automatic expiration date (`forgetAfter`). Including them in search results can help recover information that may still be relevant.
+</Note>
+
+## Next Steps
+
+Explore more advanced features in our [API Reference](/api-reference/search-memories/search-memories).
diff --git a/apps/docs/memory-api/track-progress.mdx b/apps/docs/memory-api/track-progress.mdx
new file mode 100644
index 00000000..60126dab
--- /dev/null
+++ b/apps/docs/memory-api/track-progress.mdx
@@ -0,0 +1,274 @@
+---
+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
+// 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
+# 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 -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
+const memory = await client.memories.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.memories.get("doc_abc123");
+ console.log(`Status: ${memory.status}`);
+}
+```
+
+```python
+memory = client.memories.get("doc_abc123")
+
+print(f"Status: {memory['status']}")
+
+# Poll for completion
+import time
+while memory['status'] != 'done':
+ time.sleep(2)
+ memory = client.memories.get("doc_abc123")
+ print(f"Status: {memory['status']}")
+```
+
+```bash
+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"
+}
+```
+
+## 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.memories.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.memories.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.memories.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.memories.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)));
+ }
+ }
+}
+```
+
+## Processing Times by Content Type
+
+Documents: Created near instantly (200-500ms)
+
+Memories: Supermemory creates a memory graph understanding based on semantic analysis and contextual understanding.
+
+| Content Type | Memory Processing Time | Notes |
+|--------------|------------------------|-------|
+| Plain Text | 5-10 seconds | Fastest processing |
+| Markdown | 5-10 seconds | Similar to plain text |
+| PDF (< 10 pages) | 15-30 seconds | OCR if needed |
+| PDF (> 100 pages) | 1-3 minutes | Depends on complexity |
+| Images | 10-20 seconds | OCR processing |
+| YouTube Videos | 1-2 min per 10 min video | Transcription required |
+| Web Pages | 10-20 seconds | Content extraction |
+| Google Docs | 10-15 seconds | API extraction |
+
+<Note>
+**Pro Tip**: Use the processing status endpoint to provide real-time feedback to users, especially for larger documents or batch uploads.
+</Note>
diff --git a/apps/docs/memory-router/overview.mdx b/apps/docs/memory-router/overview.mdx
new file mode 100644
index 00000000..4c142e5e
--- /dev/null
+++ b/apps/docs/memory-router/overview.mdx
@@ -0,0 +1,158 @@
+---
+title: "Overview"
+description: "Transform any LLM into an intelligent agent with unlimited context and persistent memory"
+sidebarTitle: "Overview"
+---
+
+The Memory Router is a transparent proxy that sits between your application and your LLM provider, automatically managing context and memories without requiring any code changes.
+
+<Note>
+**Live Demo**: Try the Memory Router at [supermemory.chat](https://supermemory.chat) to see it in action.
+</Note>
+
+<Tip>
+**Using Vercel AI SDK?** Check out our [AI SDK integration](/ai-sdk/overview) for the cleanest implementation with `@supermemory/tools/ai-sdk` - it's our recommended approach for new projects.
+</Tip>
+
+## What is the Memory Router?
+
+The Memory Router gives your LLM applications:
+
+- **Unlimited Context**: No more token limits - conversations can extend indefinitely
+- **Automatic Memory Management**: Intelligently chunks, stores, and retrieves relevant context
+- **Zero Code Changes**: Works with your existing OpenAI-compatible clients
+- **Cost Optimization**: Save up to 70% on token costs through intelligent context management
+
+## How It Works
+
+<Steps>
+ <Step title="Proxy Request">
+ Your application sends requests to Supermemory instead of directly to your LLM provider
+ </Step>
+
+ <Step title="Context Management">
+ Supermemory automatically:
+ - Removes unnecessary context from long conversations
+ - Searches relevant memories from previous interactions
+ - Appends the most relevant context to your prompt
+ </Step>
+
+ <Step title="Forward to LLM">
+ The optimized request is forwarded to your chosen LLM provider
+ </Step>
+
+ <Step title="Async Memory Creation">
+ New memories are created asynchronously without blocking the response
+ </Step>
+</Steps>
+
+## Key Benefits
+
+### For Developers
+
+- **Drop-in Integration**: Just change your base URL - no other code changes needed
+- **Provider Agnostic**: Works with OpenAI, Anthropic, Google, Groq, and more
+- **Shared Memory Pool**: Memories created via API are available to the Router and vice versa
+- **Automatic Fallback**: If Supermemory has issues, requests pass through directly
+
+### For Applications
+
+- **Better Long Conversations**: Maintains context even after thousands of messages
+- **Consistent Responses**: Memories ensure consistent information across sessions
+- **Smart Retrieval**: Only relevant context is included, improving response quality
+- **Cost Savings**: Automatic chunking reduces token usage significantly
+
+## When to Use the Memory Router
+
+The Memory Router is ideal for:
+
+<Tabs>
+ <Tab title="Perfect For">
+ - **Chat Applications**: Customer support, AI assistants, chatbots
+ - **Long Conversations**: Sessions that exceed model context windows
+ - **Multi-Session Memory**: Users who return and continue conversations
+ - **Quick Prototypes**: Get memory capabilities without building infrastructure
+ </Tab>
+
+ <Tab title="Consider API Instead">
+ - **Custom Retrieval Logic**: Need specific control over what memories to fetch
+ - **Non-Conversational Use**: Document processing, analysis tools
+ - **Complex Filtering**: Need advanced metadata filtering
+ - **Batch Operations**: Processing multiple documents at once
+ </Tab>
+</Tabs>
+
+## Supported Providers
+
+The Memory Router works with any OpenAI-compatible endpoint:
+
+| Provider | Base URL | Status |
+|----------|----------|---------|
+| OpenAI | `api.openai.com/v1` | ✅ Fully Supported |
+| Anthropic | `api.anthropic.com/v1` | ✅ Fully Supported |
+| Google Gemini | `generativelanguage.googleapis.com/v1beta/openai` | ✅ Fully Supported |
+| Groq | `api.groq.com/openai/v1` | ✅ Fully Supported |
+| DeepInfra | `api.deepinfra.com/v1/openai` | ✅ Fully Supported |
+| OpenRouter | `openrouter.ai/api/v1` | ✅ Fully Supported |
+| Custom | Any OpenAI-compatible | ✅ Supported |
+
+<Warning>
+**Not Yet Supported**:
+- OpenAI Assistants API (`/v1/assistants`)
+</Warning>
+
+## Authentication
+
+The Memory Router requires two API keys:
+
+1. **Supermemory API Key**: For memory management
+2. **Provider API Key**: For your chosen LLM provider
+
+You can provide these via:
+- Headers (recommended for production)
+- URL parameters (useful for testing)
+- Request body (for compatibility)
+
+## How Memories Work
+
+When using the Memory Router:
+
+1. **Automatic Extraction**: Important information from conversations is automatically extracted
+2. **Intelligent Chunking**: Long messages are split into semantic chunks
+3. **Relationship Building**: New memories connect to existing knowledge
+4. **Smart Retrieval**: Only the most relevant memories are included in context
+
+<Note>
+Memories are shared between the Memory Router and Memory API when using the same `user_id`, allowing you to use both together.
+</Note>
+
+## Response Headers
+
+The Memory Router adds diagnostic headers to help you understand what's happening:
+
+| Header | Description |
+|--------|-------------|
+| `x-supermemory-conversation-id` | Unique conversation identifier |
+| `x-supermemory-context-modified` | Whether context was modified (`true`/`false`) |
+| `x-supermemory-tokens-processed` | Number of tokens processed |
+| `x-supermemory-chunks-created` | New memory chunks created |
+| `x-supermemory-chunks-retrieved` | Memory chunks added to context |
+
+## Error Handling
+
+The Memory Router is designed for reliability:
+
+- **Automatic Fallback**: If Supermemory encounters an error, your request passes through unmodified
+- **Error Headers**: `x-supermemory-error` header provides error details
+- **Zero Downtime**: Your application continues working even if memory features are unavailable
+
+## Rate Limits & Pricing
+
+### Rate Limits
+- No Supermemory-specific rate limits
+- Subject only to your LLM provider's limits
+
+### Pricing
+- **Free Tier**: 100k tokens stored at no cost
+- **Standard Plan**: $20/month after free tier
+- **Usage-Based**: Each conversation includes 20k free tokens, then $1 per million tokens
diff --git a/apps/docs/memory-router/usage.mdx b/apps/docs/memory-router/usage.mdx
new file mode 100644
index 00000000..61dadfbf
--- /dev/null
+++ b/apps/docs/memory-router/usage.mdx
@@ -0,0 +1,214 @@
+---
+title: "Usage"
+description: "How to implement the Memory Router in your application"
+sidebarTitle: "Usage"
+---
+
+Add unlimited memory to your LLM applications with just a URL change.
+
+## Prerequisites
+
+You'll need:
+1. A [Supermemory API key](https://console.supermemory.ai)
+2. Your LLM provider's API key
+
+## Basic Setup
+
+<Steps>
+ <Step title="Get Your API Keys">
+ **Supermemory API Key:**
+ 1. Sign up at [console.supermemory.ai](https://console.supermemory.ai)
+ 2. Navigate to **API Keys** → **Create API Key**
+ 3. Copy your key
+
+ **Provider API Key:**
+ - [OpenAI](https://platform.openai.com/api-keys)
+ - [Anthropic](https://console.anthropic.com/settings/keys)
+ - [Google Gemini](https://aistudio.google.com/app/apikey)
+ - [Groq](https://console.groq.com/keys)
+ </Step>
+
+ <Step title="Update Your Base URL">
+ Prepend `https://api.supermemory.ai/v3/` to your provider's URL:
+
+ ```
+ https://api.supermemory.ai/v3/[PROVIDER_URL]
+ ```
+ </Step>
+
+ <Step title="Add Authentication">
+ Include both API keys in your requests (see examples below)
+ </Step>
+</Steps>
+
+## Provider URLs
+
+<CodeGroup>
+
+```text OpenAI
+https://api.supermemory.ai/v3/https://api.openai.com/v1/
+```
+
+```text Anthropic
+https://api.supermemory.ai/v3/https://api.anthropic.com/v1/
+```
+
+```text Google Gemini
+https://api.supermemory.ai/v3/https://generativelanguage.googleapis.com/v1beta/openai/
+```
+
+```text Groq
+https://api.supermemory.ai/v3/https://api.groq.com/openai/v1/
+```
+
+</CodeGroup>
+
+## Implementation Examples
+
+<Tabs>
+ <Tab title="Python">
+ ```python
+ from openai import OpenAI
+
+ client = OpenAI(
+ api_key="YOUR_OPENAI_API_KEY",
+ base_url="https://api.supermemory.ai/v3/https://api.openai.com/v1/",
+ default_headers={
+ "x-supermemory-api-key": "YOUR_SUPERMEMORY_API_KEY",
+ "x-sm-user-id": "user123" # Unique user identifier
+ }
+ )
+
+ # Use as normal
+ response = client.chat.completions.create(
+ model="gpt-4",
+ messages=[
+ {"role": "user", "content": "Hello!"}
+ ]
+ )
+
+ print(response.choices[0].message.content)
+ ```
+ </Tab>
+
+ <Tab title="TypeScript">
+ ```typescript
+ import OpenAI from 'openai';
+
+ const client = new OpenAI({
+ apiKey: process.env.OPENAI_API_KEY,
+ baseURL: 'https://api.supermemory.ai/v3/https://api.openai.com/v1/',
+ defaultHeaders: {
+ 'x-supermemory-api-key': process.env.SUPERMEMORY_API_KEY,
+ 'x-sm-user-id': 'user123' // Unique user identifier
+ }
+ });
+
+ // Use as normal
+ const response = await client.chat.completions.create({
+ model: 'gpt-4',
+ messages: [
+ { role: 'user', content: 'Hello!' }
+ ]
+ });
+
+ console.log(response.choices[0].message.content);
+ ```
+ </Tab>
+
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/https://api.openai.com/v1/chat/completions" \
+ -H "Authorization: Bearer YOUR_OPENAI_API_KEY" \
+ -H "x-supermemory-api-key: YOUR_SUPERMEMORY_API_KEY" \
+ -H "x-sm-user-id: user123" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "Hello!"}]
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Alternative: URL Parameters
+
+If you can't modify headers, pass authentication via URL parameters:
+
+<CodeGroup>
+
+```python Python
+client = OpenAI(
+ api_key="YOUR_OPENAI_API_KEY",
+ base_url="https://api.supermemory.ai/v3/https://api.openai.com/v1/chat/completions?userId=user123"
+)
+
+# Then set Supermemory API key as environment variable:
+# export SUPERMEMORY_API_KEY="your_key_here"
+```
+
+```typescript TypeScript
+const client = new OpenAI({
+ apiKey: process.env.OPENAI_API_KEY,
+ baseURL: 'https://api.supermemory.ai/v3/https://api.openai.com/v1/chat/completions?userId=user123'
+});
+
+// Set Supermemory API key as environment variable:
+// SUPERMEMORY_API_KEY="your_key_here"
+```
+
+```bash cURL
+curl -X POST "https://api.supermemory.ai/v3/https://api.openai.com/v1/chat/completions?userId=user123" \
+ -H "Authorization: Bearer YOUR_OPENAI_API_KEY" \
+ -H "x-supermemory-api-key: YOUR_SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"model": "gpt-4", "messages": [{"role": "user", "content": "Hello!"}]}'
+```
+
+</CodeGroup>
+
+## Conversation Management
+
+### Managing Conversations
+
+Use `x-sm-conversation-id` to maintain conversation context across requests:
+
+```python
+# Start a new conversation
+response1 = client.chat.completions.create(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "My name is Alice"}],
+ extra_headers={
+ "x-sm-conversation-id": "conv_123"
+ }
+)
+
+# Continue the same conversation later
+response2 = client.chat.completions.create(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "What's my name?"}],
+ extra_headers={
+ "x-sm-conversation-id": "conv_123"
+ }
+)
+# Response will remember "Alice"
+```
+
+### User Identification
+
+Always provide a unique user ID to isolate memories between users:
+
+```python
+# Different users have separate memory spaces
+client_alice = OpenAI(
+ api_key="...",
+ base_url="...",
+ default_headers={"x-sm-user-id": "alice_123"}
+)
+
+client_bob = OpenAI(
+ api_key="...",
+ base_url="...",
+ default_headers={"x-sm-user-id": "bob_456"}
+)
+```
diff --git a/apps/docs/memory-router/with-memory-api.mdx b/apps/docs/memory-router/with-memory-api.mdx
new file mode 100644
index 00000000..fcb09361
--- /dev/null
+++ b/apps/docs/memory-router/with-memory-api.mdx
@@ -0,0 +1,113 @@
+---
+title: "Use with Memory API"
+description: "Combine the Memory Router with Memory API for maximum control"
+sidebarTitle: "Use with Memory API"
+---
+
+The Memory Router and Memory API share the same memory pool. When you use the same `user_id`, memories are automatically shared between both systems.
+
+## How They Work Together
+
+<Note>
+**Key Insight**: Both the Router and API access the same memories when using identical `user_id` values. This enables powerful hybrid implementations.
+</Note>
+
+### Shared Memory Pool
+
+```python
+# Memory created via API
+from supermemory import Client
+
+api_client = Client(api_key="YOUR_SUPERMEMORY_KEY")
+
+# Add memory via API
+api_client.memories.add({
+ "content": "User prefers Python over JavaScript for backend development",
+ "user_id": "user123"
+})
+
+# Later, in your chat application using Router
+from openai import OpenAI
+
+router_client = OpenAI(
+ api_key="YOUR_OPENAI_KEY",
+ base_url="https://api.supermemory.ai/v3/https://api.openai.com/v1/",
+ default_headers={
+ "x-supermemory-api-key": "YOUR_SUPERMEMORY_KEY",
+ "x-sm-user-id": "user123" # Same user_id
+ }
+)
+
+# Router automatically has access to the API-created memory
+response = router_client.chat.completions.create(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "What language should I use for my new backend?"}]
+)
+# Response will consider the Python preference
+```
+
+## Pre-load Context via API
+
+Use the API to add documents and context before conversations:
+
+```python
+# Step 1: Load user's documents via API
+api_client.memories.add({
+ "content": "https://company.com/product-docs.pdf",
+ "user_id": "support_agent_123",
+ "metadata": {"type": "product_documentation"}
+})
+
+# Step 2: Support agent uses chat with Router
+router_client = OpenAI(
+ base_url="https://api.supermemory.ai/v3/https://api.openai.com/v1/",
+ default_headers={"x-sm-user-id": "support_agent_123"}
+)
+
+# Agent has automatic access to product docs
+response = router_client.chat.completions.create(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "How does the enterprise pricing work?"}]
+)
+```
+
+
+## Best Practices
+
+### 1. Consistent User IDs
+
+Always use the same `user_id` format across both systems:
+
+```python
+# ✅ Good - consistent user_id
+api_client.memories.add({"user_id": "user_123"})
+router_headers = {"x-sm-user-id": "user_123"}
+
+# ❌ Bad - inconsistent user_id
+api_client.memories.add({"user_id": "user-123"})
+router_headers = {"x-sm-user-id": "user_123"} # Different format!
+```
+
+### 2. Use Container Tags for Organization
+
+```python
+# API: Add memories with tags
+api_client.memories.add({
+ "content": "Q3 revenue report",
+ "user_id": "analyst_1",
+ "containerTag": "financial_reports"
+})
+
+# Router: Memories are automatically organized
+# The Router will intelligently retrieve from the right containers
+```
+
+### 3. Leverage Each System's Strengths
+
+| Use Case | Best Choice | Why |
+|----------|------------|-----|
+| Chat conversations | Router | Automatic context management |
+| Document upload | API | Batch processing, custom IDs |
+| Search & filter | API | Advanced query capabilities |
+| Quick prototypes | Router | Zero code changes |
+| Memory management | API | Full CRUD operations |
diff --git a/apps/docs/model-enhancement/context-extender.mdx b/apps/docs/model-enhancement/context-extender.mdx
new file mode 100644
index 00000000..0f165f1e
--- /dev/null
+++ b/apps/docs/model-enhancement/context-extender.mdx
@@ -0,0 +1,233 @@
+---
+title: "supermemory Infinite Chat"
+description: "Build chat applications with unlimited context using supermemory's intelligent proxy"
+tag: "BETA"
+---
+
+import GettingAPIKey from '/snippets/getting-api-key.mdx';
+
+supermemory Infinite Chat is a powerful solution that gives your chat applications unlimited contextual memory. It works as a transparent proxy in front of your existing LLM provider, intelligently managing long conversations without requiring any changes to your application logic.
+
+<img
+ src="/images/infinite-context.png"
+ alt="Infinite Context Diagram"
+ className="rounded-lg shadow-lg"
+/>
+
+<Tabs>
+ <Tab title="Key Features">
+ <CardGroup cols={2}>
+ <Card title="Unlimited Context" icon="infinity" color="#4F46E5">
+ No more token limits - conversations can extend indefinitely
+ </Card>
+ <Card title="Zero Latency" icon="bolt" color="#10B981">
+ Transparent proxying with negligible overhead
+ </Card>
+ <Card title="Cost Efficient" icon="coins" color="#F59E0B">
+ Save up to 70% on token costs for long conversations
+ </Card>
+ <Card title="Provider Agnostic" icon="plug" color="#6366F1">
+ Works with any OpenAI-compatible endpoint
+ </Card>
+ </CardGroup>
+ </Tab>
+</Tabs>
+
+## Getting Started
+
+To use the Infinite Chat endpoint, you need to:
+
+### 1. Get a supermemory API key
+
+<GettingAPIKey />
+
+### 2. Add supermemory in front of any **OpenAI-Compatible** API URL
+
+<CodeGroup>
+
+```typescript Typescript
+import OpenAI from "openai";
+
+/**
+ * Initialize the OpenAI client with supermemory proxy
+ * @param {string} OPENAI_API_KEY - Your OpenAI API key
+ * @param {string} SUPERMEMORY_API_KEY - Your supermemory API key
+ * @returns {OpenAI} - Configured OpenAI client
+ */
+const client = new OpenAI({
+ apiKey: process.env.OPENAI_API_KEY,
+ baseURL: "https://api.supermemory.ai/v3/https://api.openai.com/v1",
+ headers: {
+ "x-supermemory-api-key": process.env.SUPERMEMORY_API_KEY,
+ "x-sm-user-id": "Your_users_id"
+ },
+});
+```
+
+```python Python
+import openai
+import os
+
+# Configure the OpenAI client with supermemory proxy
+openai.api_base = "https://api.supermemory.ai/v3/https://api.openai.com/v1"
+openai.api_key = os.environ.get("OPENAI_API_KEY") # Your regular OpenAI key
+openai.default_headers = {
+ "x-supermemory--api-key": os.environ.get("SUPERMEMORY_API_KEY"), # Your supermemory key
+}
+
+# Create a chat completion with unlimited context
+response = openai.ChatCompletion.create(
+ model="gpt-4o-mini",
+ messages=[{"role": "user", "content": "Your message here"}]
+)
+```
+
+</CodeGroup>
+
+## How It Works
+
+<Steps>
+ <Step title="Transparent Proxying">
+ All requests pass through supermemory to your chosen LLM provider with zero latency overhead.
+
+ <img
+ src="/images/transparent-proxy.png"
+ alt="Transparent Proxy Diagram"
+ className="my-4 rounded-md shadow"
+ />
+ </Step>
+ <Step title="Intelligent Chunking">
+ Long conversations are automatically broken down into optimized segments using our proprietary chunking algorithm that preserves semantic coherence.
+ </Step>
+ <Step title="Smart Retrieval">
+ When conversations exceed token limits (20k+), supermemory intelligently retrieves the most relevant context from previous messages.
+ </Step>
+ <Step title="Automatic Token Management">
+ The system intelligently balances token usage, ensuring optimal performance while minimizing costs.
+ </Step>
+</Steps>
+
+## Performance Benefits
+
+<Accordion title="Reduced Token Usage" defaultOpen icon="coins">
+ Save up to 70% on token costs for long conversations through intelligent context management and caching.
+</Accordion>
+
+<Accordion title="Unlimited Context" icon="infinity">
+ No more 8k/32k/128k token limits - conversations can extend indefinitely with supermemory's advanced retrieval system.
+</Accordion>
+
+<Accordion title="Improved Response Quality" icon="sparkles">
+ Better context retrieval means more coherent responses even in very long threads, reducing hallucinations and inconsistencies.
+</Accordion>
+
+<Accordion title="Zero Performance Penalty" icon="bolt">
+ The proxy adds negligible latency to your requests, ensuring fast response times for your users.
+</Accordion>
+
+## Pricing
+
+<Tabs>
+ <Tab title="Plans">
+ <div className="mt-4">
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
+ <div className="p-4 border rounded-lg">
+ <h3 className="text-lg font-bold">Free Tier</h3>
+ <p className="text-sm text-gray-600 dark:text-gray-300">100k tokens stored at no cost</p>
+ </div>
+ <div className="p-4 border rounded-lg">
+ <h3 className="text-lg font-bold">Standard Plan</h3>
+ <p className="text-sm text-gray-600 dark:text-gray-300">$20/month fixed cost after exceeding free tier</p>
+ </div>
+ <div className="p-4 border rounded-lg">
+ <h3 className="text-lg font-bold">Usage-Based</h3>
+ <p className="text-sm text-gray-600 dark:text-gray-300">Each thread includes 20k free tokens, then $1 per million tokens thereafter</p>
+ </div>
+ </div>
+ </div>
+ </Tab>
+ <Tab title="Comparison">
+ <div className="mt-4">
+ <table className="min-w-full divide-y divide-gray-200">
+ <thead>
+ <tr>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Feature
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Free
+ </th>
+ <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
+ Standard
+ </th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-gray-200">
+ <tr>
+ <td className="px-6 py-4 whitespace-nowrap text-sm">
+ Tokens Stored
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm">
+ 100k
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm">
+ Unlimited
+ </td>
+ </tr>
+ <tr>
+ <td className="px-6 py-4 whitespace-nowrap text-sm">
+ Conversations
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm">
+ 10
+ </td>
+ <td className="px-6 py-4 whitespace-nowrap text-sm">
+ Unlimited
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </Tab>
+</Tabs>
+
+## Error Handling
+
+<Note>
+ supermemory is designed with reliability as the top priority. If any issues occur within the supermemory processing pipeline, the system will automatically fall back to direct forwarding of your request to the LLM provider, ensuring zero downtime for your applications.
+</Note>
+
+Each response includes diagnostic headers that provide information about the processing:
+
+| Header | Description |
+| -------------------------------- | ---------------------------------------------------------------------- |
+| `x-supermemory-conversation-id` | Unique identifier for the conversation thread |
+| `x-supermemory-context-modified` | Indicates whether supermemory modified the context ("true" or "false") |
+| `x-supermemory-tokens-processed` | Number of tokens processed in this request |
+| `x-supermemory-chunks-created` | Number of new chunks created from this conversation |
+| `x-supermemory-chunks-deleted` | Number of chunks removed (if any) |
+| `x-supermemory-docs-deleted` | Number of documents removed (if any) |
+
+If an error occurs, an additional header `x-supermemory-error` will be included with details about what went wrong. Your request will still be processed by the underlying LLM provider even if supermemory encounters an error.
+
+## Rate Limiting
+
+<Info>
+ Currently, there are no rate limits specific to supermemory. Your requests are subject only to the rate limits of your underlying LLM provider.
+</Info>
+
+## Supported Models
+
+supermemory works with any OpenAI-compatible API, including:
+
+<CardGroup cols={3}>
+ <Card title="OpenAI" icon="openai">
+ GPT-3.5, GPT-4, GPT-4o
+ </Card>
+ <Card title="Anthropic" icon="user-astronaut">
+ Claude 3 models
+ </Card>
+ <Card title="Other Providers" icon="plug">
+ Any provider with an OpenAI-compatible endpoint
+ </Card>
+</CardGroup>
diff --git a/apps/docs/model-enhancement/getting-started.mdx b/apps/docs/model-enhancement/getting-started.mdx
new file mode 100644
index 00000000..9faa7eba
--- /dev/null
+++ b/apps/docs/model-enhancement/getting-started.mdx
@@ -0,0 +1,99 @@
+---
+title: "Getting Started with Model Enhancement"
+sidebarTitle: "Quickstart"
+description: "Superpower your LLM in one line"
+---
+
+import GettingAPIKey from '/snippets/getting-api-key.mdx';
+
+## Get your supermemory API key
+
+<GettingAPIKey />
+
+## Get your LLM provider's API key
+
+Head to your LLM provider's dashboard and get your API key.
+
+- [OpenAI](https://platform.openai.com/api-keys)
+- [Gemini](https://aistudio.google.com/apikey)
+- [Anthropic](https://console.anthropic.com/account/keys)
+- [Groq](https://console.groq.com/keys)
+
+## Choose your endpoint
+
+<CodeGroup>
+
+```bash OpenAI
+https://api.supermemory.ai/v3/https://api.openai.com/v1/chat/completions
+```
+
+
+```bash Gemini
+https://api.supermemory.ai/v3/https://generativelanguage.googleapis.com/v1beta/openai
+```
+
+
+```bash Anthropic
+https://api.supermemory.ai/v3/https://api.anthropic.com/v1
+```
+
+
+```bash Groq
+https://api.supermemory.ai/v3/https://api.groq.com/openai/v1
+```
+
+
+```bash Other provider
+https://api.supermemory.ai/v3/<your-provider's-openai-endpoint>
+```
+
+</CodeGroup>
+
+## Making your first request
+
+<CodeGroup>
+
+```bash cURL
+curl https://api.supermemory.ai/v3/https://api.openai.com/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $OPENAI_API_KEY" \
+ -H "x-supermemory--api-key: $SUPERMEMORY_API_KEY" \
+ -H 'x-sm-user-id: user_id' \
+ -d '{
+ "model": "gpt-4o",
+ "messages": [
+ {"role": "user", "content": "What is the capital of France?"}
+ ]
+ }'
+```
+
+
+```
+```
+
+
+```typescript TypeScript
+import OpenAI from 'openai';
+
+const openai = new OpenAI({
+ apiKey: process.env.OPENAI_API_KEY,
+ baseURL: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ defaultHeaders: {
+ 'x-supermemory-api-key': process.env.SUPERMEMORY_API_KEY,
+ 'x-sm-user-id': 'your-user-id'
+ }
+});
+
+const completion = await openai.chat.completions.create({
+ model: "gpt-4o",
+/// you can also add user here
+ user: "user",
+ messages: [
+ { role: "user", content: "What is the capital of France?" }
+ ]
+});
+
+ console.debug(completion.choices[0].message);
+```
+
+</CodeGroup>
diff --git a/apps/docs/model-enhancement/identifying-users.mdx b/apps/docs/model-enhancement/identifying-users.mdx
new file mode 100644
index 00000000..518f046a
--- /dev/null
+++ b/apps/docs/model-enhancement/identifying-users.mdx
@@ -0,0 +1,119 @@
+---
+title: "Identifying Users"
+description: "Identifying users in supermemory"
+---
+
+You can enable built-in cross-conversational memory by sending supermemory a `x-sm-user-id`.
+
+## How supermemory Identifies Users and conversations
+
+supermemory will find the user ID in the following places (in order of priority):
+
+### `x-sm-user-id` header
+
+You can add a default header of x-sm-user-id with any client and model
+
+### `user` in body
+
+For models that support the `user` parameter in the body, such as OpenAI, you can also attach it to the body.
+
+### `userId` in search params
+
+You can also add `?userId=xyz` in the URL search parameters, incase the models don't support it.
+
+## Conversation ID
+
+If a conversation identifier is provided, You do not need to send the entire array of messages to supermemory.
+
+```typescript
+// if you provide conversation ID, You do not need to send all the messages every single time. supermemory automatically backfills it.
+const client = new OpenAI({
+ baseURL:
+"https://api.supermemory.ai/v3/https://api.openai.com/v1",
+ defaultHeaders: {
+ "x-supermemory-api-key":
+ "SUPERMEMORY_API_KEY",
+ "x-sm-user-id": `dhravya`,
+ "x-sm-conversation-id": "conversation-id"
+ },
+})
+
+const messages = [
+{"role" : "user", "text": "SOme long thing"},
+// .... 50 other messages
+{"role" : "user", "text": "new message"},
+]
+
+const client.generateText(messages)
+
+// Next time, you dont need to send more.
+const messages2 = [{"role" : "user", "text": "What did we talk about in this conversation, and the one we did last year?"}]
+
+const client.generateText(messages2)
+```
+
+## Implementation Examples
+
+### Google Gemini
+
+```typescript
+const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });
+
+async function main() {
+ const response = await ai.models.generateContent({
+ model: "gemini-2.0-flash",
+ contents: "Explain how AI works in a few words",
+ config: {
+ httpOptions: {
+ headers: {
+ 'x-sm-user-id': "user_123"
+ }
+ }
+ },
+ });
+ console.debug(response.text);
+}
+```
+
+### Anthropic
+
+```typescript
+const anthropic = new Anthropic({
+ apiKey: 'YOUR_API_KEY', // defaults to process.env["ANTHROPIC_API_KEY"]
+});
+
+async function main() {
+ const msg = await anthropic.messages.create({
+ model: "claude-sonnet-4-20250514",
+ max_tokens: 1024,
+ messages: [{ role: "user", content: "Hello, Claude" }],
+ }, {
+ // Using headers
+ headers: {
+ 'x-sm-user-id': "user_123"
+ }
+ });
+
+ console.debug(msg);
+}
+```
+
+### OpenAI
+
+```typescript
+const openai = new OpenAI({
+ apiKey: "YOUR_API_KEY"
+});
+
+async function main() {
+ const completion = await openai.chat.completions.create({
+ messages: [
+ { role: "user", content: "Hello, Assistant" }
+ ],
+ model: "gpt-4o",
+ user: "user_123"
+ });
+
+ console.debug(completion.choices[0].message);
+}
+``` \ No newline at end of file
diff --git a/apps/docs/openai-sdks/usage.mdx b/apps/docs/openai-sdks/usage.mdx
new file mode 100644
index 00000000..db2e52e3
--- /dev/null
+++ b/apps/docs/openai-sdks/usage.mdx
@@ -0,0 +1,9 @@
+---
+title: "Usage with OpenAI SDKs"
+---
+
+To use supermemory with the OpenAI SDKs,
+
+```
+import { memoryToolSchemas } from "@supermemory/tools/openai"
+```
diff --git a/apps/docs/org-settings.mdx b/apps/docs/org-settings.mdx
new file mode 100644
index 00000000..0d954603
--- /dev/null
+++ b/apps/docs/org-settings.mdx
@@ -0,0 +1,265 @@
+---
+title: "Organization Settings"
+description: "Configure organization-wide settings and content filtering for Supermemory"
+icon: "settings"
+---
+
+Organization settings control how Supermemory processes content across your entire organization. These settings apply to all memories and connectors, helping you:
+
+- Filter content before indexing
+- Configure custom OAuth applications for connectors
+- Set organization-wide processing rules
+- Control what gets indexed and what gets excluded
+
+<Note>
+Settings are organization-wide and apply to all users and memories within your organization.
+</Note>
+
+## Why Settings Matter
+
+The settings endpoint is crucial for teaching Supermemory about your specific use case. It helps Supermemory understand:
+
+- **What you are**: Your organization's specific use case and purpose
+- **What to expect**: The types of content and information flowing through your system
+- **How to interpret**: Context for understanding queries in your specific use case
+- **What to prioritize**: Which content matters most for your users
+
+### Example: Brand Guidelines Use Case
+
+Without proper settings, when a user searches "what are our values?", Supermemory might return random documents mentioning "values". But with proper configuration:
+
+```typescript
+await client.settings.update({
+ shouldLLMFilter: true,
+ filterPrompt: `You are managing brand guidelines for Brand.ai.
+ You will receive all outbound content from our organization.
+
+ When users search, they're looking for:
+ - "What are our values?" → Return official brand values document
+ - "What's our tone of voice?" → Return brand voice guidelines
+ - "How do we describe our mission?" → Return approved mission statements
+
+ Focus on the latest approved brand materials, not drafts or outdated versions.`
+});
+```
+
+Now Supermemory understands that:
+- Searches about "values" refer to brand values, not financial values
+- "Tone" means brand voice, not audio settings
+- Priority should be given to official, approved content
+
+This context dramatically improves search relevance and ensures users get the right information for their specific use case.
+
+## API Endpoints
+
+### Get Current Settings
+
+Retrieve your organization's current settings configuration.
+
+<CodeGroup>
+
+```typescript TypeScript
+const settings = await client.settings.get();
+console.log('Current settings:', settings);
+```
+
+```python Python
+settings = client.settings.get()
+print(f'Current settings: {settings}')
+```
+
+```bash cURL
+curl -X GET "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+```
+
+</CodeGroup>
+
+### Update Settings
+
+Update your organization's settings. You only need to include the fields you want to change.
+
+<CodeGroup>
+
+```typescript TypeScript
+const updatedSettings = await client.settings.update({
+ shouldLLMFilter: true,
+ filterPrompt: "Only index technical documentation and code",
+ includeItems: ["*.md", "*.ts", "*.py"],
+ excludeItems: ["node_modules", ".git", "*.test.*"]
+});
+
+console.log('Updated fields:', updatedSettings.updated);
+```
+
+```python Python
+updated_settings = client.settings.update(
+ should_llm_filter=True,
+ filter_prompt="Only index technical documentation and code",
+ include_items=["*.md", "*.ts", "*.py"],
+ exclude_items=["node_modules", ".git", "*.test.*"]
+)
+
+print(f'Updated fields: {updated_settings.updated}')
+```
+
+```bash cURL
+curl -X PATCH "https://api.supermemory.ai/v3/settings" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "shouldLLMFilter": true,
+ "filterPrompt": "Only index technical documentation and code",
+ "includeItems": ["*.md", "*.ts", "*.py"],
+ "excludeItems": ["node_modules", ".git", "*.test.*"]
+ }'
+```
+
+</CodeGroup>
+
+## Content Filtering Settings
+
+Control what content gets indexed into Supermemory.
+
+### Basic Filtering
+
+Use include/exclude patterns to filter content:
+
+```typescript
+await client.settings.update({
+ includeItems: [
+ "*.md", // All markdown files
+ "*.mdx", // MDX documentation
+ "docs/**", // Everything in docs folder
+ "src/**/*.ts" // TypeScript files in src
+ ],
+ excludeItems: [
+ "node_modules", // Dependencies
+ ".git", // Version control
+ "*.test.*", // Test files
+ "build/**", // Build outputs
+ "*.tmp" // Temporary files
+ ]
+});
+```
+
+### Intelligent LLM Filtering
+
+Enable AI-powered content filtering for semantic understanding:
+
+```typescript
+await client.settings.update({
+ shouldLLMFilter: true,
+ filterPrompt: `You are filtering content for a technical documentation system.
+
+ Include:
+ - API documentation
+ - Code examples and tutorials
+ - Technical guides and references
+ - Architecture documentation
+
+ Exclude:
+ - Marketing materials
+ - Internal meeting notes
+ - Personal information
+ - Outdated or deprecated content
+
+ Focus on content that helps developers understand and use our APIs.`
+});
+```
+
+## Connector OAuth Settings
+
+Configure custom OAuth applications for connector integrations.
+
+### Google Drive Custom OAuth
+
+```typescript
+await client.settings.update({
+ googleDriveCustomKeyEnabled: true,
+ googleDriveClientId: "your-client-id.apps.googleusercontent.com",
+ googleDriveClientSecret: "your-client-secret"
+});
+```
+
+### Notion Custom OAuth
+
+```typescript
+await client.settings.update({
+ notionCustomKeyEnabled: true,
+ notionClientId: "your-notion-oauth-client-id",
+ notionClientSecret: "your-notion-oauth-client-secret"
+});
+```
+
+### OneDrive Custom OAuth
+
+```typescript
+await client.settings.update({
+ onedriveCustomKeyEnabled: true,
+ onedriveClientId: "your-azure-app-id",
+ onedriveClientSecret: "your-azure-app-secret"
+});
+```
+
+## Best Practices
+
+### 1. Set Before Bulk Import
+Configure settings before importing large amounts of content. Changes don't retroactively affect existing memories.
+
+### 2. Be Specific in Filter Prompts
+Provide clear context about your organization and expected search patterns:
+
+```typescript
+// Good - Specific and contextual
+filterPrompt: `Technical documentation for developers.
+ Include: API references, code examples, error solutions.
+ Exclude: marketing content, personal data, test files.
+ Users search for: implementation details, troubleshooting, best practices.`
+
+// Bad - Too vague
+filterPrompt: "Only important content"
+```
+
+### 3. Test OAuth Credentials
+Always test custom OAuth credentials in development before production:
+
+```typescript
+// Test connection after updating OAuth settings
+const testConnection = await client.connections.create('google-drive', {
+ redirectUrl: 'https://yourapp.com/callback',
+ containerTags: ['test-connection']
+});
+```
+
+### 4. Monitor Filter Effectiveness
+Check what's being indexed to ensure filters work as expected:
+
+```typescript
+const memories = await client.memories.list({
+ containerTags: ['your-tags'],
+ limit: 10
+});
+
+// Review what's actually being indexed
+memories.memories.forEach(memory => {
+ console.log(`Indexed: ${memory.title} - ${memory.type}`);
+});
+```
+
+## Important Notes
+
+<Warning>
+**Settings Limitations:**
+- Changes are organization-wide, not per-user
+- Settings don't retroactively process existing memories
+- OAuth credentials must be properly configured in respective platforms
+- Filter patterns are applied during content ingestion
+</Warning>
+
+## Related Documentation
+
+- [Connectors Overview](/connectors/overview) - Setting up external integrations
+- [Google Drive Setup](/connectors/google-drive) - Configure Google Drive OAuth
+- [Notion Setup](/connectors/notion) - Configure Notion OAuth
+- [OneDrive Setup](/connectors/onedrive) - Configure OneDrive OAuth \ No newline at end of file
diff --git a/apps/docs/overview/use-cases.mdx b/apps/docs/overview/use-cases.mdx
new file mode 100644
index 00000000..a10f9aae
--- /dev/null
+++ b/apps/docs/overview/use-cases.mdx
@@ -0,0 +1,110 @@
+---
+title: "Use Cases"
+description: "What can you do with supermemory?"
+mode: "wide"
+---
+
+Explore what you can build with supermemory:
+
+<CardGroup cols="3">
+ <Card title="Chat with ____" icon="message-circle">
+ Quickly built apps to chat with:
+
+ • Your Twitter bookmarks \
+ • Your PDF documents \
+ • Your company documentation \
+ ...and more\!
+ </Card>
+ <Card title="Smart Search" icon="search">
+ Search everything with AI:
+
+ • Product recommendations \
+ • Document similarity matching \
+ • Research paper analysis
+
+ ...and more\!
+ </Card>
+ <Card title="Assistants & Agents" icon="chart-line">
+ Build agents with infinite context for:
+
+ • Email management \
+ • Meeting summarization \
+ • Calendar organization \
+ ...and more\!
+ </Card>
+ <Card title="Second Brain" icon="brain">
+ Build your own second brain:
+
+ • Organize your notes, ideas, and resources
+
+ • Connect concepts across documents
+
+ • Never lose track of insights or inspiration
+
+ ...and more\!
+ </Card>
+ <Card title="Content Writing & Brand Voice" icon="pencil-line">
+ For agencies and creators:
+
+ • Maintain consistent tone and style
+ • Analyze your brand’s unique voice
+ • Write with context-aware suggestions
+
+ ...and more\!
+ </Card>
+ <Card title="Healthcare & Medical Records" icon="hospital">
+ For clinics, hospitals, and researchers:
+
+ • Securely summarize patient records
+
+ • Extract key info from medical history
+
+ • Support clinical decisions with AI
+
+ ...and more\!
+ </Card>
+ <Card title="Community & Support Chatbots" icon="users">
+ For online communities and businesses:
+
+ • Powered by your chat or forum history
+
+ • Instant, accurate answers
+
+ • Reduce support load
+
+ ...and more\!
+ </Card>
+ <Card title="Education & Study Tools" icon="book">
+ For students and educators:
+
+ • Flashcards and quizzes from your notes
+
+ • Search across textbooks and lectures
+
+ • Personalized study assistants
+
+ ...and more\!
+ </Card>
+ <Card title="Legal & Compliance Search" icon="scale">
+ For law firms and compliance teams:
+
+ • Search through contracts and case law
+
+ • Extract clauses, obligations, and risks
+
+ • Keep up with regulatory changes
+
+ ...and more\!
+ </Card>
+ <Card title="Enterprise Knowledge Hubs" icon="briefcase-business">
+ For companies and teams:
+
+ • Centralize all internal documentation
+
+ • Search across wikis, policies, and emails
+
+ • Onboard new hires faster
+
+ ...and more\!
+ </Card>
+</CardGroup> \ No newline at end of file
diff --git a/apps/docs/overview/why-supermemory.mdx b/apps/docs/overview/why-supermemory.mdx
new file mode 100644
index 00000000..c1d651a9
--- /dev/null
+++ b/apps/docs/overview/why-supermemory.mdx
@@ -0,0 +1,67 @@
+---
+title: "Why supermemory?"
+description: "Learn the problems and challenges of building a memory layer, and how supermemory solves them!"
+---
+
+### The problem
+
+...so you want to build your own memory layer. Let's go through your decision process:
+
+<Steps>
+ <Step title="Let's choose a vector database">
+ <Card title="Found a vector database?">
+ - Oh no, it's way too expensive. Time to switch.
+ - Turns out it's painfully slow. Let's try another.
+ - Great, now it won't scale. Back to square one.
+ - The maintenance is a nightmare. Need something else.
+ </Card>
+ </Step>
+ <Step title="Now for the embedding model">
+ <Card title="Unless you have a PhD in AI, good luck figuring out:">
+ - Which model fits your use case
+ - What are the performance tradeoffs
+ - How to keep up with new releases
+ </Card>
+ </Step>
+ <Step title="Time to build the memory layer">
+ <CardGroup cols="1">
+ <Card title="So many types of content">
+ - Websites: How do you handle JavaScript? What about rate limits?
+ - PDFs: OCR keeps failing, text extraction is inconsistent
+ - Images: Need computer vision models now?
+ - Audio/Video: Transcription costs add up quickly
+ </Card>
+ </CardGroup>
+ </Step>
+</Steps>
+
+And in the middle of all this, you're wondering...
+
+> "When will I actually ship my product?"
+
+### The solution
+
+If you're not a fan of reinventing the wheel, you can use supermemory.
+
+<CardGroup cols="1">
+ <Card title="Affordable & Easy to Use" icon="banknote">
+ - Start for free, scale as you grow
+ - Simple API, deploy in minutes
+ - No complex setup or maintenance
+ - Clear, predictable pricing
+ </Card>
+ <Card title="Simple Connectors" icon="plug">
+ - Notion, Google Drive, Slack
+ - Web scraping and PDF processing
+ - Email and calendar sync
+ - Custom connector SDK
+ </Card>
+ <Card title="Production Ready" icon="activity">
+ - Enterprise-grade security
+ - Sub-200ms latency at scale
+ - Automatic failover and redundancy
+ - 99.9% uptime guarantee
+ </Card>
+</CardGroup>
+
+Stop reinventing the wheel. Focus on building your product while we handle the memory infrastructure. \ No newline at end of file
diff --git a/apps/docs/package.json b/apps/docs/package.json
new file mode 100644
index 00000000..46e0b708
--- /dev/null
+++ b/apps/docs/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "@repo/docs",
+ "module": "index.ts",
+ "type": "module",
+ "private": true,
+ "scripts": {
+ "dev": "bunx mintlify@latest dev --no-open --port 3003"
+ },
+ "devDependencies": {
+ "@types/bun": "latest",
+ "mintlify": "^4.2.112",
+ "typescript": "^5.9.2"
+ }
+}
diff --git a/apps/docs/quickstart.mdx b/apps/docs/quickstart.mdx
new file mode 100644
index 00000000..131bfd6f
--- /dev/null
+++ b/apps/docs/quickstart.mdx
@@ -0,0 +1,879 @@
+---
+title: Quickstart
+description: Make your first API call to Supermemory - add and retrieve memories.
+---
+
+<Tip>
+**Using Vercel AI SDK?** Check out the [AI SDK integration](/ai-sdk/overview) for the cleanest implementation with `@supermemory/tools/ai-sdk`.
+</Tip>
+
+## Memory API
+
+**Step 1.** Sign up for [Supermemory’s Developer Platform](http://console.supermemory.ai) to get the API key. Click on **API Keys -> Create API Key** to generate one.
+
+![create api key](./images/create-api.png)
+
+<Tabs>
+
+ <Tab title="Python">
+ **Step 2.** Install the Supermemory client
+
+ ```python
+ pip install supermemory
+ ```
+
+ **Step 3.** Run this in your terminal to create an environment variable with your API key:
+
+ ```bash
+ export SUPERMEMORY_API_KEY=“YOUR_API_KEY”
+ ```
+
+ **Step 4.** Import the module in your python file:
+
+ ```python
+ from supermemory import Supermemory
+ import os
+
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+ ```
+
+ **Step 5.** Add your first memory as follows:
+
+ ```python
+ # Create one rich memory about quantum computing applications
+ memory_content = """Quantum computing represents a paradigm shift in computational power, leveraging quantum mechanical phenomena like superposition and entanglement to solve problems that are intractable for classical computers.
+
+
+ The field emerged from theoretical work in the 1980s, when physicist Richard Feynman proposed that quantum systems could simulate other quantum systems more efficiently than classical computers. This insight led to the development of quantum algorithms like Shor's algorithm for factoring large numbers and Grover's algorithm for unstructured search problems.
+
+
+ Today, quantum computing applications span multiple domains: in cryptography, quantum computers threaten current encryption standards while enabling new quantum-resistant protocols; in drug discovery, they can simulate molecular interactions with unprecedented accuracy; in optimization problems like logistics and financial modeling, they offer exponential speedups for certain classes of problems.
+
+
+ Major tech companies including IBM, Google, and Microsoft have invested billions in quantum computing research, while startups like Rigetti Computing and IonQ focus on specific hardware approaches. The race for quantum advantage - demonstrating a quantum computer solving a problem faster than any classical computer - has become a key milestone in the field.
+
+
+ Despite the promise, significant challenges remain: quantum decoherence, error correction, and scaling qubit counts while maintaining coherence. Researchers are exploring various approaches including superconducting qubits, trapped ions, topological qubits, and photonic systems, each with different trade-offs between coherence time, gate fidelity, and scalability."""
+
+
+ # Add the memory to Supermemory
+ response = client.memories.add(
+ content=memory_content,
+ container_tag="quantum-computing",
+ metadata={
+ "category": "technology-overview",
+ "topic": "quantum-computing",
+ "complexity": "intermediate",
+ "word_count": len(memory_content.split())
+ }
+ )
+
+
+ print(f"Memory added successfully!")
+ print(f"Memory ID: {response.id}")
+ print(f"Content length: {len(memory_content)} characters")
+ ```
+
+ Run your code. The output is as follows:
+
+ ```bash
+ Memory added successfully!
+ Memory ID: uLtGU14SBDzfsvefYWbwe7
+ Content length: 1701 characters
+ ```
+
+ **Step 6.** Search for this memory as follows:
+
+ ```python
+ results = client.search.memories(q="what are some applications of quantum computing?", limit=3)
+
+
+ print(results)
+ ```
+ The output is as follows:
+
+ ```bash
+ SearchMemoriesResponse(
+ results=[
+ Result(
+ id="Bn1uc1yQdw3Huf8oitruwF",
+ memory="Quantum computing applications include cryptography (threatening current encryption standards, enabling quantum-resistant protocols), drug discovery (simulating molecular interactions), and optimization problems (logistics, financial modeling, offering exponential speedups).",
+ metadata=None,
+ similarity=0.7920647723809932,
+ updated_at=datetime.datetime(
+ 2025, 8, 24, 5, 41, 55, 87000, tzinfo=datetime.timezone.utc
+ ),
+ context=ResultContext(children=[], parents=[]),
+ documents=None,
+ version=1.0,
+ updatedAt="2025-08-24T05:41:55.087Z",
+ rootMemoryId="Bn1uc1yQdw3Huf8oitruwF",
+ ),
+ Result(
+ id="4aCa4oM8praVBCWdNksjxf",
+ memory="Quantum computing is a paradigm shift in computational power, leveraging quantum mechanical phenomena like superposition and entanglement to solve problems intractable for classical computers.",
+ metadata=None,
+ similarity=0.7198909950191389,
+ updated_at=datetime.datetime(
+ 2025, 8, 24, 5, 41, 55, 87000, tzinfo=datetime.timezone.utc
+ ),
+ context=ResultContext(children=[], parents=[]),
+ documents=None,
+ version=1.0,
+ updatedAt="2025-08-24T05:41:55.087Z",
+ rootMemoryId="4aCa4oM8praVBCWdNksjxf",
+ ),
+ Result(
+ id="8vzhZhBCuqyrLNXtzBDx7y",
+ memory="IBM, Google, and Microsoft have invested billions in quantum computing research.",
+ metadata=None,
+ similarity=0.6960905375426799,
+ updated_at=datetime.datetime(
+ 2025, 8, 24, 5, 41, 55, 87000, tzinfo=datetime.timezone.utc
+ ),
+ context=ResultContext(children=[], parents=[]),
+ documents=None,
+ version=1.0,
+ updatedAt="2025-08-24T05:41:55.087Z",
+ rootMemoryId="8vzhZhBCuqyrLNXtzBDx7y",
+ ),
+ ],
+ timing=214.0,
+ total=3.0,
+ )
+ ```
+ Awesome! Now that you’ve made your first request, explore all of Supermemory’s features in detail and how you can use them in your app.
+ </Tab>
+
+ <Tab title="Typescript">
+ **Step 2.** Install the Supermemory dependency:
+
+ ```bash
+ npm install supermemory
+ ```
+
+ **Step 3.** Set the environment variable:
+
+ ```bash
+ export SUPERMEMORY_API_KEY="your_actual_api_key_here"
+ ```
+ **Step 4.** Create a `quickstart.ts` file and import the package:
+
+ ```ts
+ import 'dotenv/config';
+ import Supermemory from 'supermemory';
+
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY});
+ ```
+
+ **Step 5.** Add a memory:
+
+ ```ts
+
+ const memoryContent = `Quantum computing represents a paradigm shift in computational power, leveraging quantum mechanical phenomena like superposition and entanglement to solve problems that are intractable for classical computers.
+
+
+ The field emerged from theoretical work in the 1980s, when physicist Richard Feynman proposed that quantum systems could simulate other quantum systems more efficiently than classical computers. This insight led to the development of quantum algorithms like Shor's algorithm for factoring large numbers and Grover's algorithm for unstructured search problems.
+
+
+ Today, quantum computing applications span multiple domains: in cryptography, quantum computers threaten current encryption standards while enabling new quantum-resistant protocols; in drug discovery, they can simulate molecular interactions with unprecedented accuracy; in optimization problems like logistics and financial modeling, they offer exponential speedups for certain classes of problems.
+
+
+ Major tech companies including IBM, Google, and Microsoft have invested billions in quantum computing research, while startups like Rigetti Computing and IonQ focus on specific hardware approaches. The race for quantum advantage - demonstrating a quantum computer solving a problem faster than any classical computer - has become a key milestone in the field.
+
+
+ Despite the promise, significant challenges remain: quantum decoherence, error correction, and scaling qubit counts while maintaining coherence. Researchers are exploring various approaches including superconducting qubits, trapped ions, topological qubits, and photonic systems, each with different trade-offs between coherence time, gate fidelity, and scalability.`;
+
+
+ async function addMemory() {
+ try {
+ const response = await client.memories.add({
+ content: memoryContent,
+ containerTag: "quantum-computing",
+ metadata: {
+ category: "technology-overview",
+ topic: "quantum-computing",
+ complexity: "intermediate",
+ wordCount: memoryContent.split(' ').length
+ }
+ });
+ console.log("Memory added successfully!");
+ console.log(`Memory ID: ${response.id}`);
+ return response.id
+ } catch (error) {
+ console.error("Error adding memory:", error);
+ throw error;
+ }
+ }
+ ```
+
+ Running this code block gives the following output:
+
+ ```bash
+
+ Memory added successfully!
+ Memory ID: adMxzQgSxo37jq6kjpsFMg
+ ```
+
+ **Step 6.** Search for your memory using natural language:
+
+ ```ts
+ async function searchMemories() {
+ try {
+ const results = await client.search.memories({
+ q: "what are some applications of quantum computing?",
+ limit: 3
+ });
+
+ console.log('Search results:', results);
+
+ return results;
+ } catch (error) {
+ console.error('Error searching memories:', error);
+ }
+ }
+ ```
+
+ The output is as follows:
+
+ ```bash
+ Search results: {
+ results: [
+ {
+ id: 'Bn1uc1yQdw3Huf8oitruwF',
+ memory: 'Quantum computing applications include cryptography (threatening current encryption standards, enabling quantum-resistant protocols), drug discovery (simulating molecular interactions), and optimization problems (logistics, financial modeling, offering exponential speedups).',
+ metadata: null,
+ updatedAt: '2025-08-24T05:41:55.087Z',
+ version: 1,
+ rootMemoryId: 'Bn1uc1yQdw3Huf8oitruwF',
+ similarity: 0.7920647723809932,
+ context: [Object]
+ },
+ {
+ id: '4aCa4oM8praVBCWdNksjxf',
+ memory: 'Quantum computing is a paradigm shift in computational power, leveraging quantum mechanical phenomena like superposition and entanglement to solve problems intractable for classical computers.',
+ metadata: null,
+ updatedAt: '2025-08-24T05:41:55.087Z',
+ version: 1,
+ rootMemoryId: '4aCa4oM8praVBCWdNksjxf',
+ similarity: 0.7198909950191389,
+ context: [Object]
+ },
+ {
+ id: '8vzhZhBCuqyrLNXtzBDx7y',
+ memory: 'IBM, Google, and Microsoft have invested billions in quantum computing research.',
+ metadata: null,
+ updatedAt: '2025-08-24T05:41:55.087Z',
+ version: 1,
+ rootMemoryId: '8vzhZhBCuqyrLNXtzBDx7y',
+ similarity: 0.6960905375426799,
+ context: [Object]
+ }
+ ],
+ timing: 216,
+ total: 3
+ }
+ ```
+ As you can see, Supermemory automatically chunked the main memory into smaller parts and returned them. You can visually see that in the graph in the console:
+
+ ![graph view](./images/graph-view.png)
+
+ Now that you’ve made your first request, explore all of Supermemory’s features in detail and how you can use them in your app.
+ </Tab>
+
+ <Tab title="cURL">
+ **Step 2.** The base URL for requests is as follows:
+
+ ```bash
+ https://api.supermemory.ai/
+ ```
+
+ **Step 3.** Set the environment variable:
+
+ ```bash
+ export SUPERMEMORY_API_KEY="your_api_key"
+ ```
+
+ **Step 4.** Add a memory as follows:
+
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "content": "Quantum computing represents a paradigm shift in computational power, leveraging quantum mechanical phenomena like superposition and entanglement to solve problems that are intractable for classical computers. The field emerged from theoretical work in the 1980s, when physicist Richard Feynman proposed that quantum systems could simulate other quantum systems more efficiently than classical computers. This insight led to the development of quantum algorithms like Shor'\''s algorithm for factoring large numbers and Grover'\''s algorithm for unstructured search problems. Today, quantum computing applications span multiple domains: in cryptography, quantum computers threaten current encryption standards while enabling new quantum-resistant protocols; in drug discovery, they can simulate molecular interactions with unprecedented accuracy; in optimization problems like logistics and financial modeling, they offer exponential speedups for certain classes of problems. Major tech companies including IBM, Google, and Microsoft have invested billions in quantum computing research, while startups like Rigetti Computing and IonQ focus on specific hardware approaches. The race for quantum advantage - demonstrating a quantum computer solving a problem faster than any classical computer - has become a key milestone in the field. Despite the promise, significant challenges remain: quantum decoherence, error correction, and scaling qubit counts while maintaining coherence. Researchers are exploring various approaches including superconducting qubits, trapped ions, topological qubits, and photonic systems, each with different trade-offs between coherence time, gate fidelity, and scalability.",
+ "containerTag": "quantum-computing",
+ "metadata": {
+ "category": "technology-overview",
+ "topic": "quantum-computing",
+ "complexity": "intermediate",
+ "wordCount": 156
+ }
+ }'
+ ```
+
+ The response is as follows:
+
+ ```json
+ {"id":"D2Ar7Vo7ub83w3PRPZcaP1","status":"queued"}
+ ```
+
+ **Step 5.** Search for this memory using natural language:
+
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "what are some applications of quantum computing?",
+ "limit": 3
+ }'
+ ```
+
+ The result is as follows:
+
+ ```json
+ {
+ "results": [
+ {
+ "id": "Bn1uc1yQdw3Huf8oitruwF",
+ "memory": "Quantum computing applications include cryptography (threatening current encryption standards, enabling quantum-resistant protocols), drug discovery (simulating molecular interactions), and optimization problems (logistics, financial modeling, offering exponential speedups).",
+ "metadata": null,
+ "updatedAt": "2025-08-24T05:41:55.087Z",
+ "version": 1,
+ "rootMemoryId": "Bn1uc1yQdw3Huf8oitruwF",
+ "similarity": 0.7920647723809932,
+ "context": {
+ "parents": [],
+ "children": []
+ }
+ },
+ {
+ "id": "4aCa4oM8praVBCWdNksjxf",
+ "memory": "Quantum computing is a paradigm shift in computational power, leveraging quantum mechanical phenomena like superposition and entanglement to solve problems intractable for classical computers.",
+ "metadata": null,
+ "updatedAt": "2025-08-24T05:41:55.087Z",
+ "version": 1,
+ "rootMemoryId": "4aCa4oM8praVBCWdNksjxf",
+ "similarity": 0.7198909950191389,
+ "context": {
+ "parents": [],
+ "children": []
+ }
+ },
+ {
+ "id": "8vzhZhBCuqyrLNXtzBDx7y",
+ "memory": "IBM, Google, and Microsoft have invested billions in quantum computing research.",
+ "metadata": null,
+ "updatedAt": "2025-08-24T05:41:55.087Z",
+ "version": 1,
+ "rootMemoryId": "8vzhZhBCuqyrLNXtzBDx7y",
+ "similarity": 0.6960905375426799,
+ "context": {
+ "parents": [],
+ "children": []
+ }
+ }
+ ],
+ "timing": 363,
+ "total": 3
+ }
+ ```
+
+ And that's it! Good job!
+
+ </Tab>
+</Tabs>
+
+
+## Memory Router
+Learn how you can add the Memory Router to your existing LLM requests.
+
+The memory router works as a proxy on top of LLM calls. When conversations get very long, it automatically chunks them for optimal performance, retrieves the most relevant information from the history, and balances token usage + cost.
+
+The best part is that it requires no changes to your application logic. Here’s how to get started:
+
+**Step 1.** Sign up for [Supermemory’s Developer Platform](http://console.supermemory.ai) to get the API key. Click on **API Keys -> Create API Key** to generate one.
+
+**Step 2.** Get your LLM provider’s API key
+
+- [OpenAI](https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key)
+- [Gemini](https://ai.google.dev/gemini-api/docs/api-key)
+- [Anthropic](https://docs.anthropic.com/en/api/admin-api/apikeys/get-api-key)
+- [Groq](https://console.groq.com/keys)
+
+**Step 3.** Append Supermemory’s URL to your LLM provider’s OpenAI-compatible API URL:
+
+<CodeGroup>
+
+```bash OpenAI
+https://api.supermemory.ai/v3/https://api.openai.com/v1/
+```
+```bash Anthropic
+https://api.supermemory.ai/v3/https://api.anthropic.com/v1/
+```
+
+```bash Gemini
+https://api.supermemory.ai/v3/https://generativelanguage.googleapis.com/v1beta/openai/
+```
+
+```bash Groq
+https://api.supermemory.ai/v3/https://api.groq.com/openai/v1
+```
+
+```bash Others
+https://api.supermemory.ai/v3/[openai-api-url-here]
+```
+</CodeGroup>
+
+<Tabs>
+
+
+<Tab title="Typescript">
+ **Step 4.** Install the dependencies
+
+ ```bash
+ npm install openai
+ ```
+
+ **Step 5.** Set two environment variables in your environment: one for Supermemory, and one for your model provider.
+
+ ```bash
+ export SUPERMEMORY_API_KEY=“your_api_key_here”
+
+ # export OPENAI_API_KEY/ANTHROPIC_API_KEY/GEMINI_API_KEY/GROQ_API_KEY=“api_key_here” (based on your model)
+ ```
+
+ **Step 6.** Send a request to the updated endpoint:
+
+ <CodeGroup>
+
+ ```ts OpenAI
+ import OpenAI from 'openai';
+
+ const client = new OpenAI({
+ apiKey: process.env.OPENAI_API_KEY,
+ baseURL: 'https://api.supermemory.ai/v3/https://api.openai.com/v1',
+ defaultHeaders: {
+ 'x-supermemory-api-key': process.env.SUPERMEMORY_API_KEY!,
+ 'x-sm-user-id': 'user_123' // Your user identifier
+ }
+ });
+
+ async function chatWithOpenAI() {
+ try {
+ const response = await client.chat.completions.create({
+ model: 'gpt-4o',
+ messages: [
+ { role: 'user', content: 'Hello my name is Naman. How are you?' }
+ ],
+ max_tokens: 1000,
+ temperature: 0.7
+ });
+
+ console.log('OpenAI Response:', response.choices[0].message.content);
+ return response;
+ } catch (error) {
+ console.error('Error with OpenAI:', error);
+ }
+ }
+
+ ```
+ ```ts Anthropic
+ import OpenAI from 'openai';
+
+ const anthropicClient = new OpenAI({
+ apiKey: process.env.ANTHROPIC_API_KEY,
+ baseURL: 'https://api.supermemory.ai/v3/https://api.anthropic.com/v1',
+ defaultHeaders: {
+ 'x-supermemory-api-key': process.env.SUPERMEMORY_API_KEY!,
+ 'x-sm-user-id': 'user_123'
+ }
+ });
+
+ async function chatWithClaude() {
+ try {
+ const response = await anthropicClient.chat.completions.create({
+ model: 'claude-3-sonnet-20240229',
+ messages: [
+ { role: 'user', content: 'Hello my name is Naman. How are you?' }
+ ],
+ max_tokens: 1000
+ });
+
+ console.log('Claude Response:', response.choices[0].message.content);
+ return response;
+ } catch (error) {
+ console.error('Error with Claude:', error);
+ }
+ }
+ ```
+
+ ```ts Gemini
+
+ import OpenAI from 'openai';
+
+ const geminiClient = new OpenAI({
+ apiKey: process.env.GEMINI_API_KEY,
+ baseURL: 'https://api.supermemory.ai/v3/https://generativelanguage.googleapis.com/v1beta',
+ defaultHeaders: {
+ 'x-supermemory-api-key': process.env.SUPERMEMORY_API_KEY!,
+ 'x-sm-user-id': 'user_123'
+ }
+ });
+
+ async function chatWithGemini() {
+ try {
+ const response = await geminiClient.chat.completions.create({
+ model: 'gemini-pro',
+ messages: [
+ { role: 'user', content: 'Hello my name is Naman. How are you?' }
+ ],
+ max_tokens: 1000
+ });
+
+ console.log('Gemini Response:', response.choices[0].message.content);
+ return response;
+ } catch (error) {
+ console.error('Error with Gemini:', error);
+ }
+ }
+
+ ```
+
+ ```ts Groq
+
+ import OpenAI from 'openai';
+
+ const groqClient = new OpenAI({
+ apiKey: process.env.GROQ_API_KEY,
+ baseURL: 'https://api.supermemory.ai/v3/https://api.groq.com/openai/v1',
+ defaultHeaders: {
+ 'x-supermemory-api-key': process.env.SUPERMEMORY_API_KEY!,
+ 'x-sm-user-id': 'user_123'
+ }
+ });
+
+ async function chatWithGroq() {
+ try {
+ const response = await groqClient.chat.completions.create({
+ model: 'mixtral-8x7b-32768',
+ messages: [
+ { role: 'user', content: 'Hello my name is Naman. How are you?' }
+ ],
+ max_tokens: 1000
+ });
+
+ console.log('Groq Response:', response.choices[0].message.content);
+ return response;
+ } catch (error) {
+ console.error('Error with Groq:', error);
+ }
+ }
+
+
+ ```
+
+ </CodeGroup>
+
+ Each of these code snippets changes the Base URL based on the OpenAI-compatible API URL given by the model providers. Some of the key parameters to note are:
+
+ - `apiKey`: Your model provider’s API key
+ - `x-supermemory-api-key`: Your Supermemory API key
+ - `x-sm-user-id`: Scope conversations by user with a user ID. This will enable cross-conversation memory, meaning users can reference other chats and draw information from them.
+
+ Additionally, while not shown in this quickstart, you can also pass an `x-sm-conversation-id` header.
+
+ Then, you won’t have to send the entire array of messages to the LLM as conversation history. Supermemory will handle it.
+
+ If you run the above code blocks, you’ll get an output from your LLM like this:
+
+ ```
+ “Hello, Naman! I'm just a computer program, so I don't have feelings, but I'm here and ready to help you. How can I assist you today?”
+ ```
+
+ After that, if you modify the request to ask, ‘What is my name?’ instead, you’ll get the following response:
+
+ ```
+ Your name is Naman.
+ ```
+
+ Thus, the memory router is working!
+</Tab>
+
+<Tab title="Python">
+ **Step 4.** Install the Python dependency:
+
+ ```
+ pip install openai
+ ```
+
+ **Step 5.** Set two environment variables in your environment: one for Supermemory and one for your model provider.
+
+ ```bash
+ export SUPERMEMORY_API_KEY=“your_api_key_here”
+
+ # export OPENAI_API_KEY/ANTHROPIC_API_KEY/GEMINI_API_KEY/GROQ_API_KEY=“api_key_here” (based on your model)
+ ```
+
+ **Step 6.** Send a request to the LLM with the updated base URL and parameters:
+
+ <CodeGroup>
+
+ ```python OpenAI
+ import os
+ from openai import OpenAI
+
+ client = OpenAI(
+ api_key=os.getenv("OPENAI_API_KEY"),
+ base_url="https://api.supermemory.ai/v3/https://api.openai.com/v1",
+ default_headers={
+ "x-supermemory-api-key": os.getenv("SUPERMEMORY_API_KEY"),
+ "x-sm-user-id": "user_123"
+ }
+ )
+
+ def chat_with_openai():
+ try:
+ response = client.chat.completions.create(
+ model="gpt-4o",
+ messages=[
+ {"role": "user", "content": "Hello my name is Naman. How are you?"}
+ ],
+ max_tokens=1000,
+ temperature=0.7
+ )
+
+ print("OpenAI Response:", response.choices[0].message.content)
+ return response
+ except Exception as error:
+ print(f"Error with OpenAI: {error}")
+
+ ```
+ ```python Anthropic
+ from openai import OpenAI
+
+ anthropic_client = OpenAI(
+ api_key=os.getenv("ANTHROPIC_API_KEY"),
+ base_url="https://api.supermemory.ai/v3/https://api.anthropic.com/v1",
+ default_headers={
+ "x-supermemory-api-key": os.getenv("SUPERMEMORY_API_KEY"),
+ "x-sm-user-id": "user_123"
+ }
+ )
+
+ def chat_with_claude():
+ try:
+ response = anthropic_client.chat.completions.create(
+ model="claude-3-sonnet-20240229",
+ messages=[
+ {"role": "user", "content": "Hello my name is Naman. How are you?"}
+ ],
+ max_tokens=1000
+ )
+
+ print("Claude Response:", response.choices[0].message.content)
+ return response
+ except Exception as error:
+ print(f"Error with Claude: {error}")
+
+ ```
+
+ ```python Gemini
+ from openai import OpenAI
+
+ gemini_client = OpenAI(
+ api_key=os.getenv("GEMINI_API_KEY"),
+ base_url="https://api.supermemory.ai/v3/https://generativelanguage.googleapis.com/v1beta",
+ default_headers={
+ "x-supermemory-api-key": os.getenv("SUPERMEMORY_API_KEY"),
+ "x-sm-user-id": "user_123"
+ }
+ )
+
+ def chat_with_gemini():
+ try:
+ response = gemini_client.chat.completions.create(
+ model="gemini-pro",
+ messages=[
+ {"role": "user", "content": "Hello my name is Naman. How are you?"}
+ ],
+ max_tokens=1000
+ )
+
+ print("Gemini Response:", response.choices[0].message.content)
+ return response
+ except Exception as error:
+ print(f"Error with Gemini: {error}")
+ ```
+
+ ```python Groq
+ from openai import OpenAI
+
+ groq_client = OpenAI(
+ api_key=os.getenv("GROQ_API_KEY"),
+ base_url="https://api.supermemory.ai/v3/https://api.groq.com/openai/v1",
+ default_headers={
+ "x-supermemory-api-key": os.getenv("SUPERMEMORY_API_KEY"),
+ "x-sm-user-id": "user_123"
+ }
+ )
+
+ def chat_with_groq():
+ try:
+ response = groq_client.chat.completions.create(
+ model="mixtral-8x7b-32768",
+ messages=[
+ {"role": "user", "content": "Hello my name is Naman. How are you?"}
+ ],
+ max_tokens=1000
+ )
+
+ print("Groq Response:", response.choices[0].message.content)
+ return response
+ except Exception as error:
+ print(f"Error with Groq: {error}")
+ ```
+
+ </CodeGroup>
+
+ Each of these code snippets changes the Base URL based on the OpenAI-compatible API URL given by the model providers. Some of the key parameters to note are:
+
+ - `api_key`: Your model provider’s API key
+ - `x-supermemory-api-key`: Your Supermemory API key
+ - `x-sm-user-id`: Scope conversations by user with a user ID. This will enable cross-conversation memory, meaning users can reference other chats and draw information from them.
+
+ Additionally, while not shown in this quickstart, you can also pass an `x-sm-conversation-id` header.
+
+ Then, you won’t have to send the entire array of messages to the LLM as conversation history. Supermemory will handle it.
+
+ If you run the above code blocks, you’ll get an output from your LLM like this:
+
+ ```
+ “Hello, Naman! I'm just a computer program, so I don't have feelings, but I'm here and ready to help you. How can I assist you today?”
+ ```
+
+ After that, if you modify the request to ask, ‘What is my name?’ instead, you’ll get the following response:
+
+ ```
+ Your name is Naman.
+ ```
+
+ Thus, the memory router is working!
+ </Tab>
+ <Tab title="cURL">
+ **Step 4.** Set the environment variables:
+
+ ```bash
+ export SUPERMEMORY_API_KEY="your_supermemory_api_key"
+ export OPENAI_API_KEY="your_openai_api_key"
+ export ANTHROPIC_API_KEY="your_anthropic_api_key"
+ export GEMINI_API_KEY="your_gemini_api_key"
+ export GROQ_API_KEY="your_groq_api_key"
+ ```
+
+ **Step 5.** Send a request to the LLM with the updated base URL and parameters:
+
+ <CodeGroup>
+ ```bash OpenAI
+ curl https://api.supermemory.ai/v3/https://api.openai.com/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $OPENAI_API_KEY" \
+ -H "x-supermemory-api-key: $SUPERMEMORY_API_KEY" \
+ -H "x-sm-user-id: user_123" \
+ -d '{
+ "model": "gpt-4o",
+ "messages": [
+ {"role": "user", "content": "Hello my name is Naman. How are you?"}
+ ],
+ "max_tokens": 1000,
+ "temperature": 0.7
+ }'
+ ```
+
+ ```bash Claude
+ curl https://api.supermemory.ai/v3/https://api.anthropic.com/v1/messages \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $ANTHROPIC_API_KEY" \
+ -H "x-supermemory-api-key: $SUPERMEMORY_API_KEY" \
+ -H "x-sm-user-id: user_123" \
+ -d '{
+ "model": "claude-3-sonnet-20240229",
+ "messages": [
+ {"role": "user", "content": "Hello my name is Naman. How are you?"}
+ ],
+ "max_tokens": 1000
+ }'
+ ```
+
+ ```bash Gemini
+ curl https://api.supermemory.ai/v3/https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $GEMINI_API_KEY" \
+ -H "x-supermemory-api-key: $SUPERMEMORY_API_KEY" \
+ -H "x-sm-user-id: user_123" \
+ -d '{
+ "contents": [
+ {
+ "parts": [
+ {"text": "Hello my name is Naman. How are you?"}
+ ]
+ }
+ ],
+ "generationConfig": {
+ "maxOutputTokens": 1000
+ }
+ }'
+ ```
+
+ ```bash Groq
+ curl https://api.supermemory.ai/v3/https://api.groq.com/openai/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $GROQ_API_KEY" \
+ -H "x-supermemory-api-key: $SUPERMEMORY_API_KEY" \
+ -H "x-sm-user-id: user_123" \
+ -d '{
+ "model": "mixtral-8x7b-32768",
+ "messages": [
+ {"role": "user", "content": "Hello my name is Naman. How are you?"}
+ ],
+ "max_tokens": 1000
+ }'
+ ```
+ </CodeGroup>
+
+ Each of these code snippets changes the Base URL based on the OpenAI-compatible API URL given by the model providers. Some of the key parameters to note are:
+
+ - **Authorization header**: Your model provider’s API key
+ - `x-supermemory-api-key`: Your Supermemory API key
+ - `x-sm-user-id`: Scope conversations by user with a user ID. This will enable cross-conversation memory, meaning users can reference other chats and draw information from them.
+
+ Additionally, while not shown in this quickstart, you can also pass an `x-sm-conversation-id` header.
+
+ Then, you won’t have to send the entire array of messages to the LLM as conversation history. Supermemory will handle it.
+
+ If you run the above code blocks, you’ll get an output from your LLM like this:
+
+ ```
+ “Hello, Naman! I'm just a computer program, so I don't have feelings, but I'm here and ready to help you. How can I assist you today?”
+ ```
+
+ After that, if you modify the request to ask, ‘What is my name?’ instead, you’ll get the following response:
+
+ ```
+ Your name is Naman.
+ ```
+
+ Thus, the memory router is working!
+ </Tab>
+</Tabs>
+
+
+For additional reference, here are links to the model providers’ documentation:
+- [OpenAI API Reference](https://platform.openai.com/docs/api-reference)
+- [Anthropic Claude API](https://docs.anthropic.com/claude/reference)
+- [Google Gemini API](https://ai.google.dev/docs)
+- [Groq API Documentation](https://console.groq.com/docs)
diff --git a/apps/docs/routervsapi.mdx b/apps/docs/routervsapi.mdx
new file mode 100644
index 00000000..94d44f3e
--- /dev/null
+++ b/apps/docs/routervsapi.mdx
@@ -0,0 +1,63 @@
+---
+title: "Memory API vs Router — Which one should I use?"
+sidebarTitle: "Memory API vs Router"
+description: "Two ways to add long-term memory to your LLMs. Same engine under the hood. Choose speed (Router) or control (Memory API), or use both together."
+---
+
+<Tip>
+### <strong>TL;DR</strong>
+- <strong>Memory API:</strong> You ingest/search/filter memories yourself and decide exactly what goes into the prompt. Maximum control for production apps and custom retrieval. <br/>
+- <strong>Memory Router:</strong> Keep your existing LLM client and just point it at Supermemory. We automatically fetch relevant memories and append them to your prompt. <br />
+
+Both use the same memory engine underneath, and share a common key (`user_id`). Thus, anything you store via the API is available to the Router, and vice versa, as long as the `user_id` matches.
+</Tip>
+
+We’ll first explain how the Router works, because the API is quite straightforward.
+
+![](./images/infinite-context.png)
+
+You send a request to your LLM, and Supermemory acts as a proxy. The Router will automatically remove unnecessary context from the message, search the user’s memories for additional relevant context, append it to the prompt, and send it to the LLM.
+
+It also writes new memories asynchronously, so your context keeps expanding without any blockages. The Router is specifically built for conversational memory in chat applications, and its utility shows when your conversations get very long.
+
+For you, it leads to:
+
+- No code refactoring - just swap the base URL with one provided by Supermemory. Read the quickstart to learn more.
+- Better chatbot performance due to long-thread retrieval, when conversations go beyond the model window.
+- Cost savings due to our automatic chunking and context management.
+
+The API, on the other hand, is a full-fledged API you can call in your app to ingest documents, create memories, search them, rerank, etc., with very granular control. The Router is built on top of our API.
+
+Technically, you could build your own Memory Router too on top of our API, but it wouldn’t come with the same one-line integration, ease of use, minimal latency, and intelligent token budgeting.
+
+Again, both use the same memory engine underneath the hood, so your memories are available across both products.
+
+Here’s a quick 30-second flow to decide which one to use for your specific use case:
+
+- <strong> Already have a working LLM chat and just want it to remember? </strong> Start with the Router.
+
+
+- <strong> Building a new app or need strict tenancy, filters, ranking, or custom prompts? </strong> Go to the Memory API.
+
+
+- <strong> Need both? </strong> Ingest via API, chat via Router; keep the user_id consistent.
+
+
+- <strong> Still unsure? </strong> Pilot on the Router, then graduate parts of the flow to the API as you need more control.
+
+Now, head over to the quickstart to integrate the API/Router in your app within 5 minutes.
+
+## FAQs
+
+<AccordionGroup>
+ <Accordion title="Is the Router just calling the Memory API behind the scenes?">
+ Conceptually, yes. The Router orchestrates the same Supermemory engine operations (retrieve, re-rank, budget, cite) and wraps them around your model call.
+ </Accordion>
+ <Accordion title="Does the Router store new memories automatically?">
+ It can. The create-memory step is asynchronous, so the user’s response isn’t delayed.
+ </Accordion>
+ <Accordion title="What identifies the user’s memory across Router and API?">
+ <code>user_id</code>. Keep it consistent across Router and API calls to share the same memory pool.
+ </Accordion>
+</AccordionGroup>
+
diff --git a/apps/docs/search/examples/document-search.mdx b/apps/docs/search/examples/document-search.mdx
new file mode 100644
index 00000000..4ef11070
--- /dev/null
+++ b/apps/docs/search/examples/document-search.mdx
@@ -0,0 +1,588 @@
+---
+title: "Documents Search (/v3/search)"
+description: "Full-featured search with extensive control over ranking, filtering, and results"
+---
+
+Documents search (`POST /v3/search`) provides maximum control over search behavior with extensive parameters for fine-tuning results.
+
+## Basic Implementation
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ import Supermemory from 'supermemory';
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ });
+
+ const results = await client.search.documents({
+ q: "machine learning neural networks",
+ limit: 5
+ });
+
+ console.log(`Found ${results.total} documents in ${results.timing}ms`);
+
+ // Sample output structure
+ results.results.forEach((doc, i) => {
+ console.log(`${i + 1}. ${doc.title} (Score: ${doc.score})`);
+ console.log(` ${doc.chunks.length} chunks found`);
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ from supermemory import Supermemory
+ import os
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+ results = client.search.documents(
+ q="machine learning neural networks",
+ limit=5
+ )
+
+ print(f"Found {results.total} documents in {results.timing}ms")
+
+ # Sample output structure
+ for i, doc in enumerate(results.results):
+ print(f"{i + 1}. {doc.title} (Score: {doc.score})")
+ print(f" {len(doc.chunks)} chunks found")
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning neural networks",
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output:**
+```json
+{
+ "results": [
+ {
+ "documentId": "doc_ml_guide_2024",
+ "title": "Machine Learning with Neural Networks: A Comprehensive Guide",
+ "score": 0.89,
+ "chunks": [
+ {
+ "content": "Neural networks are computational models inspired by biological neural networks. They consist of interconnected nodes (neurons) that process information through weighted connections...",
+ "score": 0.92,
+ "isRelevant": true
+ },
+ {
+ "content": "Deep learning, a subset of machine learning, uses neural networks with multiple hidden layers to learn complex patterns in data...",
+ "score": 0.87,
+ "isRelevant": true
+ }
+ ],
+ "createdAt": "2024-01-15T10:30:00Z",
+ "metadata": {
+ "category": "ai",
+ "difficulty": "intermediate"
+ }
+ }
+ ],
+ "total": 12,
+ "timing": 156
+}
+```
+
+## Container Tags Filtering
+
+Container tags are the primary way to isolate search results by user, project, or organization.
+
+**Key behaviors:**
+- **Array-based**: Unlike `/v4/search`, this endpoint accepts multiple container tags as an array
+- **Exact array matching**: Documents must have the EXACT same container tags array to match
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "quarterly reports",
+ containerTags: ["user_123"],
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="quarterly reports",
+ container_tags=["user_123"],
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "quarterly reports",
+ "containerTags": ["user_123"],
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Metadata Filtering
+
+Metadata filtering allows complex conditions on structured data attached to your documents. This uses SQL-like query construction in the backend, requiring explicit AND/OR structures.
+
+**Filter structure rules:**
+- **Must wrap conditions** in AND or OR arrays, even for single conditions
+- **Supports string matching** (exact), numeric operators, and array contains
+- **Negate any condition** with `negate: true`
+- **Combines with container tags** - both filters are applied
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "machine learning",
+ filters: {
+ AND: [
+ {
+ key: "category",
+ value: "technology",
+ negate: false
+ },
+ {
+ filterType: "numeric",
+ key: "readingTime",
+ value: "5",
+ negate: false,
+ numericOperator: "<="
+ }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="machine learning",
+ filters={
+ "AND": [
+ {
+ "key": "category",
+ "value": "technology",
+ "negate": False
+ },
+ {
+ "filterType": "numeric",
+ "key": "readingTime",
+ "value": "5",
+ "negate": False,
+ "numericOperator": "<="
+ }
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning",
+ "filters": {
+ "AND": [
+ {
+ "key": "category",
+ "value": "technology",
+ "negate": false
+ },
+ {
+ "filterType": "numeric",
+ "key": "readingTime",
+ "value": "5",
+ "negate": false,
+ "numericOperator": "<="
+ }
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output:**
+```json
+{
+ "results": [
+ {
+ "documentId": "doc_tech_trends_2024",
+ "title": "Technology Trends in Machine Learning",
+ "score": 0.91,
+ "chunks": [
+ {
+ "content": "Machine learning continues to evolve with new architectures and optimization techniques. Reading time for this comprehensive overview is approximately 8 minutes...",
+ "score": 0.88,
+ "isRelevant": true
+ }
+ ],
+ "metadata": {
+ "category": "technology",
+ "readingTime": 8,
+ "difficulty": "intermediate",
+ "published": true
+ }
+ }
+ ],
+ "total": 6,
+ "timing": 189
+}
+```
+
+## Array Contains Filtering
+
+When your metadata includes arrays (like participant lists, tags, or categories), use `array_contains` to check if the array includes a specific value.
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "meeting discussion",
+ filters: {
+ AND: [
+ {
+ key: "participants",
+ value: "john.doe",
+ filterType: "array_contains"
+ }
+ ]
+ },
+ limit: 5
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="meeting discussion",
+ filters={
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ limit=5
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "meeting discussion",
+ "filters": {
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Threshold Control
+
+Control result quality with sensitivity thresholds:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "artificial intelligence",
+ documentThreshold: 0.7, // Higher = fewer, more relevant documents
+ chunkThreshold: 0.8, // Higher = fewer, more relevant chunks
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="artificial intelligence",
+ document_threshold=0.7, # Higher = fewer, more relevant documents
+ chunk_threshold=0.8, # Higher = fewer, more relevant chunks
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "artificial intelligence",
+ "documentThreshold": 0.7,
+ "chunkThreshold": 0.8,
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Query Rewriting
+
+Improve search accuracy with automatic query rewriting:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "What is the capital of France?",
+ rewriteQuery: true, // +400ms latency but better results
+ limit: 5
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="What is the capital of France?",
+ rewrite_query=True, # +400ms latency but better results
+ limit=5
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "What is the capital of France?",
+ "rewriteQuery": true,
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+<Note>
+Query rewriting generates multiple query variations and searches through all of them, then merges results. No additional cost but adds ~400ms latency.
+</Note>
+
+## Reranking
+
+Improve result quality with secondary ranking:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "machine learning applications",
+ rerank: true, // Apply secondary ranking algorithm
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="machine learning applications",
+ rerank=True, # Apply secondary ranking algorithm
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning applications",
+ "rerank": true,
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Document-Specific Search
+
+Search within a specific large document:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "neural networks",
+ docId: "doc_123", // Search only within this document
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="neural networks",
+ doc_id="doc_123", # Search only within this document
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "neural networks",
+ "docId": "doc_123",
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Full Context Options
+
+Include complete document content and summaries:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "research findings",
+ includeFullDocs: true, // Include complete document content
+ includeSummary: true, // Include document summaries
+ onlyMatchingChunks: false, // Include all chunks, not just matching ones
+ limit: 5
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="research findings",
+ include_full_docs=True, # Include complete document content
+ include_summary=True, # Include document summaries
+ only_matching_chunks=False, # Include all chunks, not just matching ones
+ limit=5
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "research findings",
+ "includeFullDocs": true,
+ "includeSummary": true,
+ "onlyMatchingChunks": false,
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Complete Advanced Example
+
+Combining all features for maximum control:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "machine learning performance metrics",
+ containerTags: ["research_project"],
+ filters: {
+ AND: [
+ { key: "category", value: "ai", negate: false },
+ { key: "status", value: "published", negate: false }
+ ]
+ },
+ documentThreshold: 0.6,
+ chunkThreshold: 0.7,
+ rewriteQuery: true,
+ rerank: true,
+ includeFullDocs: false,
+ includeSummary: true,
+ onlyMatchingChunks: true,
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="machine learning performance metrics",
+ container_tags=["research_project"],
+ filters={
+ "AND": [
+ {"key": "category", "value": "ai", "negate": False},
+ {"key": "status", "value": "published", "negate": False}
+ ]
+ },
+ document_threshold=0.6,
+ chunk_threshold=0.7,
+ rewrite_query=True,
+ rerank=True,
+ include_full_docs=False,
+ include_summary=True,
+ only_matching_chunks=True,
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning performance metrics",
+ "containerTags": ["research_project"],
+ "filters": {
+ "AND": [
+ {"key": "category", "value": "ai", "negate": false},
+ {"key": "status", "value": "published", "negate": false}
+ ]
+ },
+ "documentThreshold": 0.6,
+ "chunkThreshold": 0.7,
+ "rewriteQuery": true,
+ "rerank": true,
+ "includeFullDocs": false,
+ "includeSummary": true,
+ "onlyMatchingChunks": true,
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
diff --git a/apps/docs/search/examples/memory-search.mdx b/apps/docs/search/examples/memory-search.mdx
new file mode 100644
index 00000000..e3cfe7d6
--- /dev/null
+++ b/apps/docs/search/examples/memory-search.mdx
@@ -0,0 +1,472 @@
+---
+title: "Memories Search (/v4/search)"
+description: "Minimal-latency search optimized for chatbots and conversational AI"
+---
+
+
+Memories search (`POST /v4/search`) provides minimal-latency search optimized for real-time interactions. This endpoint prioritizes speed over extensive control, making it perfect for chatbots, Q&A systems, and any application where users expect immediate responses.
+
+## Basic Search
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ import Supermemory from 'supermemory';
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ });
+
+ const results = await client.search.memories({
+ q: "machine learning applications",
+ limit: 5
+ });
+
+ console.log(results)
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ from supermemory import Supermemory
+ import os
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+ results = client.search.memories(
+ q="machine learning applications",
+ limit=5
+ )
+
+ console.log(results)
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning applications",
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output:**
+```json
+{
+ "results": [
+ {
+ "id": "mem_ml_apps_2024",
+ "memory": "Machine learning applications span numerous industries including healthcare (diagnostic imaging, drug discovery), finance (fraud detection, algorithmic trading), autonomous vehicles (computer vision, path planning), and natural language processing (chatbots, translation services).",
+ "similarity": 0.92,
+ "title": "Machine Learning Industry Applications",
+ "type": "text",
+ "metadata": {
+ "topic": "machine-learning",
+ "industry": "technology",
+ "created": "2024-01-10"
+ }
+ },
+ {
+ "id": "mem_ml_healthcare",
+ "memory": "In healthcare, machine learning enables early disease detection through medical imaging analysis, personalized treatment recommendations, and drug discovery acceleration by predicting molecular behavior.",
+ "similarity": 0.89,
+ "title": "ML in Healthcare",
+ "type": "text"
+ }
+ ],
+ "total": 8,
+ "timing": 87
+}
+```
+
+## Container Tag Filtering
+
+Filter by user, project, or organization:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.memories({
+ q: "project updates",
+ containerTag: "user_123", // Note: singular, not plural
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.memories(
+ q="project updates",
+ container_tag="user_123", # Note: singular, not plural
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "project updates",
+ "containerTag": "user_123",
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Threshold Control
+
+Control result quality with similarity threshold:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.memories({
+ q: "artificial intelligence research",
+ threshold: 0.7, // Higher = fewer, more similar results
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.memories(
+ q="artificial intelligence research",
+ threshold=0.7, # Higher = fewer, more similar results
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "artificial intelligence research",
+ "threshold": 0.7,
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Reranking
+
+Improve result quality with secondary ranking:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.memories({
+ q: "quantum computing breakthrough",
+ rerank: true, // Better relevance, slight latency increase
+ limit: 5
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.memories(
+ q="quantum computing breakthrough",
+ rerank=True, # Better relevance, slight latency increase
+ limit=5
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "quantum computing breakthrough",
+ "rerank": true,
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Query Rewriting
+
+Improve search accuracy with automatic query expansion:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.memories({
+ q: "How do neural networks learn?",
+ rewriteQuery: true, // +400ms latency but better results
+ limit: 5
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.memories(
+ q="How do neural networks learn?",
+ rewrite_query=True, # +400ms latency but better results
+ limit=5
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "How do neural networks learn?",
+ "rewriteQuery": true,
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Include Related Content
+
+Include documents, related memories, and summaries:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.memories({
+ q: "machine learning trends",
+ include: {
+ documents: true, // Include source documents
+ relatedMemories: true, // Include related memory entries
+ summaries: true // Include memory summaries
+ },
+ limit: 5
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.memories(
+ q="machine learning trends",
+ include={
+ "documents": True, # Include source documents
+ "relatedMemories": True, # Include related memory entries
+ "summaries": True # Include memory summaries
+ },
+ limit=5
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning trends",
+ "include": {
+ "documents": true,
+ "relatedMemories": true,
+ "summaries": true
+ },
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Metadata Filtering
+
+Simple metadata filtering for Memories search:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.memories({
+ q: "research findings",
+ filters: {
+ AND: [
+ { key: "category", value: "science", negate: false },
+ { key: "status", value: "published", negate: false }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.memories(
+ q="research findings",
+ filters={
+ "AND": [
+ {"key": "category", "value": "science", "negate": False},
+ {"key": "status", "value": "published", "negate": False}
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "research findings",
+ "filters": {
+ "AND": [
+ {"key": "category", "value": "science", "negate": false},
+ {"key": "status", "value": "published", "negate": false}
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Chatbot Example
+
+Optimal configuration for conversational AI:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Optimized for chatbot responses
+ const results = await client.search.memories({
+ q: userMessage,
+ containerTag: userId,
+ threshold: 0.6, // Balanced relevance
+ rerank: false, // Skip for speed
+ rewriteQuery: false, // Skip for speed
+ limit: 3 // Few, relevant results
+ });
+
+ // Quick response for chat
+ const context = results.results
+ .map(r => r.memory)
+ .join('\n\n');
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Optimized for chatbot responses
+ results = client.search.memories(
+ q=user_message,
+ container_tag=user_id,
+ threshold=0.6, # Balanced relevance
+ rerank=False, # Skip for speed
+ rewrite_query=False, # Skip for speed
+ limit=3 # Few, relevant results
+ )
+
+ # Quick response for chat
+ context = '\n\n'.join([r.memory for r in results.results])
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Optimized for chatbot responses
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "user question here",
+ "containerTag": "user_123",
+ "threshold": 0.6,
+ "rerank": false,
+ "rewriteQuery": false,
+ "limit": 3
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Complete Memories Search Example
+
+Combining features for comprehensive results:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.memories({
+ q: "machine learning model performance",
+ containerTag: "research_team",
+ filters: {
+ AND: [
+ { key: "topic", value: "ai", negate: false }
+ ]
+ },
+ threshold: 0.7,
+ rerank: true,
+ rewriteQuery: false, // Skip for speed
+ include: {
+ documents: true,
+ relatedMemories: false,
+ summaries: true
+ },
+ limit: 5
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.memories(
+ q="machine learning model performance",
+ container_tag="research_team",
+ filters={
+ "AND": [
+ {"key": "topic", "value": "ai", "negate": False}
+ ]
+ },
+ threshold=0.7,
+ rerank=True,
+ rewrite_query=False, # Skip for speed
+ include={
+ "documents": True,
+ "relatedMemories": False,
+ "summaries": True
+ },
+ limit=5
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning model performance",
+ "containerTag": "research_team",
+ "filters": {
+ "AND": [
+ {"key": "topic", "value": "ai", "negate": false}
+ ]
+ },
+ "threshold": 0.7,
+ "rerank": true,
+ "rewriteQuery": false,
+ "include": {
+ "documents": true,
+ "relatedMemories": false,
+ "summaries": true
+ },
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Comon Use Cases
+
+- **Chatbots**: Basic search with container tag and low threshold
+- **Q&A Systems**: Add reranking for better relevance
+- **Knowledge Retrieval**: Include documents and summaries
+- **Real-time Search**: Skip rewriting and reranking for maximum speed
diff --git a/apps/docs/search/filtering.mdx b/apps/docs/search/filtering.mdx
new file mode 100644
index 00000000..c20f4f2c
--- /dev/null
+++ b/apps/docs/search/filtering.mdx
@@ -0,0 +1,1059 @@
+---
+title: "Grouping and filtering"
+description: "Container tags, metadata filters, and advanced search filtering techniques"
+icon: "filter"
+---
+
+
+Supermemory supports filtering search results using container tags, metadata conditions, and advanced filtering techniques for both `/v3/search` and `/v4/search` endpoints.
+
+## Container Tags
+
+Container tags group memories by user, project, or organization. They're the primary way to isolate search results.
+
+**Important**: Container tags use **exact array matching**. A document with `["technology", "quantum-computing"]` will NOT match a search for `["technology"]`. The arrays must be identical.
+
+### Document Search (v3/search)
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Single container tag
+ const results = await client.search.documents({
+ q: "machine learning",
+ containerTags: ["user_123"],
+ limit: 10
+ });
+
+ // Multiple container tags
+ const results2 = await client.search.documents({
+ q: "project status",
+ containerTags: ["project_ai", "team_research"],
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Single container tag
+ results = client.search.documents(
+ q="machine learning",
+ container_tags=["user_123"],
+ limit=10
+ )
+
+ # Multiple container tags
+ results2 = client.search.documents(
+ q="project status",
+ container_tags=["project_ai", "team_research"],
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Single container tag
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning",
+ "containerTags": ["user_123"],
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Memory Search (v4/search)
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Note: singular "containerTag" for v4/search
+ const results = await client.search.memories({
+ q: "research findings",
+ containerTag: "user_123", // Single string, not array
+ limit: 5
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Note: singular "container_tag" for v4/search
+ results = client.search.memories(
+ q="research findings",
+ container_tag="user_123", # Single string, not array
+ limit=5
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "research findings",
+ "containerTag": "user_123",
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+<Note>
+**Container Tag Differences**:
+- `/v3/search` uses `containerTags` (plural array) with exact array matching
+- `/v4/search` uses `containerTag` (singular string) for single tag filtering
+- Exact matching means `["user", "project"]` ≠ `["user"]`
+</Note>
+
+## Basic Metadata Filtering
+
+Filter by metadata fields with simple conditions:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "artificial intelligence",
+ filters: {
+ AND: [
+ {
+ key: "category",
+ value: "technology",
+ negate: false
+ }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="artificial intelligence",
+ filters={
+ "AND": [
+ {
+ "key": "category",
+ "value": "technology",
+ "negate": False
+ }
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "artificial intelligence",
+ "filters": {
+ "AND": [
+ {
+ "key": "category",
+ "value": "technology",
+ "negate": false
+ }
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Numeric Filtering
+
+Filter by numeric values with operators:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "research papers",
+ filters: {
+ AND: [
+ {
+ filterType: "numeric",
+ key: "readingTime",
+ value: "10",
+ numericOperator: "<=",
+ negate: false
+ },
+ {
+ filterType: "numeric",
+ key: "wordCount",
+ value: "1000",
+ numericOperator: ">=",
+ negate: false
+ }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="research papers",
+ filters={
+ "AND": [
+ {
+ "filterType": "numeric",
+ "key": "readingTime",
+ "value": "10",
+ "numericOperator": "<=",
+ "negate": False
+ },
+ {
+ "filterType": "numeric",
+ "key": "wordCount",
+ "value": "1000",
+ "numericOperator": ">=",
+ "negate": False
+ }
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "research papers",
+ "filters": {
+ "AND": [
+ {
+ "filterType": "numeric",
+ "key": "readingTime",
+ "value": "10",
+ "numericOperator": "<=",
+ "negate": false
+ },
+ {
+ "filterType": "numeric",
+ "key": "wordCount",
+ "value": "1000",
+ "numericOperator": ">=",
+ "negate": false
+ }
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Array Contains Filtering
+
+Filter by array values like participants, tags, or categories. The `array_contains` filter type checks if an array field contains a specific value.
+
+### Basic Array Contains
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "meeting notes",
+ filters: {
+ AND: [
+ {
+ key: "participants",
+ value: "john.doe",
+ filterType: "array_contains"
+ }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="meeting notes",
+ filters={
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "meeting notes",
+ "filters": {
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Array Contains with Negation
+
+Exclude documents that contain specific values in arrays:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "team meetings",
+ filters: {
+ AND: [
+ {
+ key: "participants",
+ value: "john.doe",
+ filterType: "array_contains",
+ negate: true // Exclude meetings with john.doe
+ }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="team meetings",
+ filters={
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains",
+ "negate": True # Exclude meetings with john.doe
+ }
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "team meetings",
+ "filters": {
+ "AND": [
+ {
+ "key": "participants",
+ "value": "john.doe",
+ "filterType": "array_contains",
+ "negate": true
+ }
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Multiple Array Contains Conditions
+
+Find documents with multiple required participants:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "project planning",
+ filters: {
+ AND: [
+ {
+ key: "participants",
+ value: "project.manager",
+ filterType: "array_contains"
+ },
+ {
+ key: "participants",
+ value: "lead.developer",
+ filterType: "array_contains"
+ },
+ {
+ key: "tags",
+ value: "urgent",
+ filterType: "array_contains"
+ }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="project planning",
+ filters={
+ "AND": [
+ {
+ "key": "participants",
+ "value": "project.manager",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "participants",
+ "value": "lead.developer",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "tags",
+ "value": "urgent",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "project planning",
+ "filters": {
+ "AND": [
+ {
+ "key": "participants",
+ "value": "project.manager",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "participants",
+ "value": "lead.developer",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "tags",
+ "value": "urgent",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+### Array Contains with OR Logic
+
+Find documents with any of several participants:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "weekly reports",
+ filters: {
+ OR: [
+ {
+ key: "reviewers",
+ value: "senior.manager",
+ filterType: "array_contains"
+ },
+ {
+ key: "reviewers",
+ value: "department.head",
+ filterType: "array_contains"
+ },
+ {
+ key: "reviewers",
+ value: "project.lead",
+ filterType: "array_contains"
+ }
+ ]
+ },
+ limit: 15
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="weekly reports",
+ filters={
+ "OR": [
+ {
+ "key": "reviewers",
+ "value": "senior.manager",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "reviewers",
+ "value": "department.head",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "reviewers",
+ "value": "project.lead",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ limit=15
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "weekly reports",
+ "filters": {
+ "OR": [
+ {
+ "key": "reviewers",
+ "value": "senior.manager",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "reviewers",
+ "value": "department.head",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "reviewers",
+ "value": "project.lead",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ "limit": 15
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## OR Conditions
+
+Combine multiple conditions with OR logic:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "technology updates",
+ filters: {
+ OR: [
+ {
+ key: "category",
+ value: "ai",
+ negate: false
+ },
+ {
+ key: "category",
+ value: "machine-learning",
+ negate: false
+ },
+ {
+ key: "topic",
+ value: "neural-networks",
+ negate: false
+ }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="technology updates",
+ filters={
+ "OR": [
+ {
+ "key": "category",
+ "value": "ai",
+ "negate": False
+ },
+ {
+ "key": "category",
+ "value": "machine-learning",
+ "negate": False
+ },
+ {
+ "key": "topic",
+ "value": "neural-networks",
+ "negate": False
+ }
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "technology updates",
+ "filters": {
+ "OR": [
+ {
+ "key": "category",
+ "value": "ai",
+ "negate": false
+ },
+ {
+ "key": "category",
+ "value": "machine-learning",
+ "negate": false
+ },
+ {
+ "key": "topic",
+ "value": "neural-networks",
+ "negate": false
+ }
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Complex Nested Conditions
+
+Combine AND and OR logic for advanced filtering:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "research publications",
+ filters: {
+ AND: [
+ {
+ key: "status",
+ value: "published",
+ negate: false
+ },
+ {
+ OR: [
+ {
+ key: "category",
+ value: "ai",
+ negate: false
+ },
+ {
+ key: "category",
+ value: "machine-learning",
+ negate: false
+ }
+ ]
+ },
+ {
+ filterType: "numeric",
+ key: "year",
+ value: "2023",
+ numericOperator: ">=",
+ negate: false
+ }
+ ]
+ },
+ limit: 15
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="research publications",
+ filters={
+ "AND": [
+ {
+ "key": "status",
+ "value": "published",
+ "negate": False
+ },
+ {
+ "OR": [
+ {
+ "key": "category",
+ "value": "ai",
+ "negate": False
+ },
+ {
+ "key": "category",
+ "value": "machine-learning",
+ "negate": False
+ }
+ ]
+ },
+ {
+ "filterType": "numeric",
+ "key": "year",
+ "value": "2023",
+ "numericOperator": ">=",
+ "negate": False
+ }
+ ]
+ },
+ limit=15
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "research publications",
+ "filters": {
+ "AND": [
+ {
+ "key": "status",
+ "value": "published",
+ "negate": false
+ },
+ {
+ "OR": [
+ {
+ "key": "category",
+ "value": "ai",
+ "negate": false
+ },
+ {
+ "key": "category",
+ "value": "machine-learning",
+ "negate": false
+ }
+ ]
+ },
+ {
+ "filterType": "numeric",
+ "key": "year",
+ "value": "2023",
+ "numericOperator": ">=",
+ "negate": false
+ }
+ ]
+ },
+ "limit": 15
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Negation Filters
+
+Exclude specific values with negation:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "machine learning",
+ filters: {
+ AND: [
+ {
+ key: "category",
+ value: "ai",
+ negate: false
+ },
+ {
+ key: "status",
+ value: "draft",
+ negate: true // Exclude drafts
+ },
+ {
+ key: "author",
+ value: "deprecated_user",
+ negate: true // Exclude specific author
+ }
+ ]
+ },
+ limit: 10
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="machine learning",
+ filters={
+ "AND": [
+ {
+ "key": "category",
+ "value": "ai",
+ "negate": False
+ },
+ {
+ "key": "status",
+ "value": "draft",
+ "negate": True # Exclude drafts
+ },
+ {
+ "key": "author",
+ "value": "deprecated_user",
+ "negate": True # Exclude specific author
+ }
+ ]
+ },
+ limit=10
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning",
+ "filters": {
+ "AND": [
+ {
+ "key": "category",
+ "value": "ai",
+ "negate": false
+ },
+ {
+ "key": "status",
+ "value": "draft",
+ "negate": true
+ },
+ {
+ "key": "author",
+ "value": "deprecated_user",
+ "negate": true
+ }
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Document-Specific Search
+
+Search within a specific document:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "neural network architecture",
+ docId: "doc_large_textbook_123", // Search only within this document
+ limit: 20
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="neural network architecture",
+ doc_id="doc_large_textbook_123", # Search only within this document
+ limit=20
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "neural network architecture",
+ "docId": "doc_large_textbook_123",
+ "limit": 20
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+## Filter Best Practices
+
+<Callout type="info">
+**Performance Tips**:
+- Use container tags as the primary filter (fastest)
+- Combine with simple metadata filters for precision
+- Avoid complex nested OR conditions for better performance
+- Use numeric operators only when necessary
+</Callout>
+
+<Warning>
+**Filter Structure**: All conditions must be wrapped in `AND` or `OR` arrays. Single conditions still need the array wrapper: `{"AND": [{"key": "category", "value": "ai"}]}`.
+</Warning>
+
+<Note>
+**Supported Operators**:
+- **String**: Exact matching only
+- **Numeric**: `<=`, `>=`, `<`, `>`, `=`
+- **Array**: `array_contains` for checking if array contains value
+- **Negation**: Works with all filter types
+</Note>
+
+## Common Filter Patterns
+
+### User-Specific Content
+```json
+{
+ "containerTags": ["user_123"],
+ "filters": {
+ "AND": [
+ {"key": "visibility", "value": "private", "negate": false}
+ ]
+ }
+}
+```
+
+### Recent High-Quality Content
+```json
+{
+ "filters": {
+ "AND": [
+ {
+ "filterType": "numeric",
+ "key": "created_year",
+ "value": "2024",
+ "numericOperator": ">="
+ },
+ {
+ "filterType": "numeric",
+ "key": "quality_score",
+ "value": "7",
+ "numericOperator": ">="
+ }
+ ]
+ }
+}
+```
+
+### Multi-Category Search
+```json
+{
+ "filters": {
+ "OR": [
+ {"key": "category", "value": "ai"},
+ {"key": "category", "value": "machine-learning"},
+ {"key": "category", "value": "data-science"}
+ ]
+ }
+}
+```
+
+### Team Member Participation
+```json
+{
+ "filters": {
+ "AND": [
+ {
+ "key": "participants",
+ "value": "team.lead",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "project_tags",
+ "value": "high-priority",
+ "filterType": "array_contains"
+ }
+ ]
+ }
+}
+```
+
+### Exclude Specific Teams
+```json
+{
+ "filters": {
+ "AND": [
+ {
+ "key": "department",
+ "value": "marketing",
+ "filterType": "array_contains",
+ "negate": true
+ },
+ {
+ "key": "confidential_tags",
+ "value": "executive-only",
+ "filterType": "array_contains",
+ "negate": true
+ }
+ ]
+ }
+}
+```
+
+### Complex Meeting Filter
+```json
+{
+ "filters": {
+ "AND": [
+ {
+ "OR": [
+ {
+ "key": "attendees",
+ "value": "ceo",
+ "filterType": "array_contains"
+ },
+ {
+ "key": "attendees",
+ "value": "cto",
+ "filterType": "array_contains"
+ }
+ ]
+ },
+ {
+ "key": "meeting_type",
+ "value": "cancelled",
+ "negate": true
+ },
+ {
+ "filterType": "numeric",
+ "key": "duration_minutes",
+ "value": "30",
+ "numericOperator": ">="
+ }
+ ]
+ }
+}
+```
diff --git a/apps/docs/search/overview.mdx b/apps/docs/search/overview.mdx
new file mode 100644
index 00000000..4293c72f
--- /dev/null
+++ b/apps/docs/search/overview.mdx
@@ -0,0 +1,376 @@
+---
+title: "Search with Filters & Scoring"
+description: "Semantic and hybrid search with metadata filters, scoring, and precise result control"
+sidebarTitle : "Overview"
+---
+
+
+## Search Endpoints Overview
+
+<CardGroup cols={2}>
+ <Card title="Documents Search - Fast, Advanced RAG" icon="settings" href="/search/examples/document-search">
+ **POST /v3/search**
+
+ Full-featured search with extensive control over ranking, filtering, thresholds, and result structure. Searches through and returns relevant documents. More flexibility.
+ </Card>
+
+ <Card title="Memories Search" icon="zap" href="/search/examples/memory-search">
+ **POST /v4/search**
+
+ Minimal-latency search optimized for chatbots and conversational AI. Searches through and returns memories. Simple parameters, fast responses, easy to use.
+ </Card>
+</CardGroup>
+
+## Documents vs Memories Search: What's the Difference?
+
+The key difference between `/v3/search` and `/v4/search` is **documents vs memories**. `/v3/search` searches through the documents and returns matching chunks, whereas `/v4/search` searches through user's memories, preferences and history.
+
+- **Documents:** Refer to the data you ingest like text, pdfs, videos, images, etc. They are sources of ground truth.
+- **Memories:** They are automatically extracted from your documents by Supermemory. Smaller information chunks inferred from documents and related to each other.
+
+Refer to the [ingestion guide](/memory-api/ingesting) to learn more about the difference between documents and memories.
+
+### Documents Search (`/v3/search`)
+**High quality documents search** - extensive parameters for fine-tuning search behavior:
+
+- **Use cases**: Use this endpoint for use cases where "literal" document search is required.
+ - Looking through legal/finance documents
+ - Searching through items in google drive
+ - Chat with documentation
+- With this endpoint, you get **Full Control** over
+ - Thresholds,
+ - Filtering
+ - Reranking
+ - Query rewriting
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Documents search
+ const results = await client.search.documents({
+ q: "machine learning accuracy",
+ limit: 10,
+ documentThreshold: 0.7,
+ chunkThreshold: 0.8,
+ rerank: true,
+ rewriteQuery: true,
+ includeFullDocs: true,
+ includeSummary: true,
+ onlyMatchingChunks: false,
+ containerTags: ["research"],
+ filters: {
+ AND: [{ key: "category", value: "ai", negate: false }]
+ }
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Documents search
+ results = client.search.documents(
+ q="machine learning accuracy",
+ limit=10,
+ document_threshold=0.7,
+ chunk_threshold=0.8,
+ rerank=True,
+ rewrite_query=True,
+ include_full_docs=True,
+ include_summary=True,
+ only_matching_chunks=False,
+ container_tags=["research"],
+ filters={
+ "AND": [{"key": "category", "value": "ai", "negate": False}]
+ }
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning accuracy",
+ "limit": 10,
+ "documentThreshold": 0.7,
+ "chunkThreshold": 0.8,
+ "rerank": true,
+ "rewriteQuery": true,
+ "includeFullDocs": true,
+ "includeSummary": true,
+ "onlyMatchingChunks": false,
+ "containerTags": ["research"],
+ "filters": {
+ "AND": [{"key": "category", "value": "ai", "negate": false}]
+ }
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+```json Sample Response
+
+{
+ "results": [
+ {
+ "documentId": "doc_abc123",
+ "title": "Machine Learning Fundamentals",
+ "type": "pdf",
+ "score": 0.89,
+ "chunks": [
+ {
+ "content": "Machine learning is a subset of artificial intelligence...",
+ "score": 0.95,
+ "isRelevant": true
+ }
+ ],
+ "metadata": {
+ "category": "education",
+ "author": "Dr. Smith",
+ "difficulty": "beginner"
+ },
+ "createdAt": "2024-01-15T10:30:00Z",
+ "updatedAt": "2024-01-20T14:45:00Z"
+ }
+ ],
+ "timing": 187,
+ "total": 1
+}
+```
+
+The `/v3/search` endpoint returns the most relevant documents and chunks from those documents. Head over to the [response schema](/search/response-schema) page to understand more about the response structure.
+
+### Memories Search (`/v4/search`)
+**Search through user memories**:
+
+- **Use cases**: Use this endpoint for use cases where understanding user context / preferences / memories is more important than literal document search.
+ - Personalized chatbots (AI Companions)
+ - Auto selecting based on what the user wants
+ - Setting the tone of the conversation
+
+Companies like Composio [Rube.app](https://rube.app) use memories search for letting the MCP automate better based on the user prompts before.
+
+<Info>
+ This endpoint works best for conversational AI use cases like chatbots.
+</Info>
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Memories search
+ const results = await client.search.memories({
+ q: "machine learning accuracy",
+ limit: 5,
+ containerTag: "research",
+ threshold: 0.7,
+ rerank: true
+ });
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Memories search
+ results = client.search.memories(
+ q="machine learning accuracy",
+ limit=5,
+ container_tag="research",
+ threshold=0.7,
+ rerank=True
+ )
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning accuracy",
+ "limit": 5,
+ "containerTag": "research",
+ "threshold": 0.7,
+ "rerank": true
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+
+```json Sample Response
+{
+ "results": [
+ {
+ "id": "mem_xyz789",
+ "memory": "Complete memory content about quantum computing applications...",
+ "similarity": 0.87,
+ "metadata": {
+ "category": "research",
+ "topic": "quantum-computing"
+ },
+ "updatedAt": "2024-01-18T09:15:00Z",
+ "version": 3,
+ "context": {
+ "parents": [
+ {
+ "memory": "Earlier discussion about quantum theory basics...",
+ "relation": "extends",
+ "version": 2,
+ "updatedAt": "2024-01-17T16:30:00Z"
+ }
+ ],
+ "children": [
+ {
+ "memory": "Follow-up questions about quantum algorithms...",
+ "relation": "derives",
+ "version": 4,
+ "updatedAt": "2024-01-19T11:20:00Z"
+ }
+ ]
+ },
+ "documents": [
+ {
+ "id": "doc_quantum_paper",
+ "title": "Quantum Computing Applications",
+ "type": "pdf",
+ "createdAt": "2024-01-10T08:00:00Z"
+ }
+ ]
+ }
+ ],
+ "timing": 156,
+ "total": 1
+}
+
+```
+
+The `/v4/search` endpoint searches through and returns memories.
+
+## Search Flow Architecture
+
+### Document Search (`/v3/search`) Flow
+
+```mermaid
+graph TD
+ A[Query Input] --> B{Rewrite Query?}
+ B -->|Yes| C[Query Rewriting +400ms]
+ B -->|No| D[Generate Embeddings]
+ C --> E[Generate Rewritten Embeddings]
+ D --> F[Search Execution]
+ E --> F
+ F --> G[Apply Filtering<br/>metadata, categories, containerTags]
+ G --> H{Rerank?}
+ H -->|Yes| I[Apply Reranking]
+ H -->|No| J[Build Results with Chunks]
+ I --> J
+ J --> K[Return Documents + Chunks + Scores]
+```
+
+### Memory Search (`/v4/search`) Flow
+
+```mermaid
+graph TD
+ A[Query Input] --> B[Query Rewriting + Embedding]
+ B --> C[Parallel Search Execution]
+ C --> D[Apply Filtering]
+ D --> E[Merge Results]
+ E --> F[Deduplication]
+ F --> G{Rerank?}
+ G -->|Yes| H[Apply Reranking]
+ G -->|No| I[Return Memories + Similarity]
+ H --> I
+```
+
+## Key Concepts You Need to Understand
+
+### 1. Thresholds (Sensitivity Control)
+
+Thresholds control result quality vs quantity:
+
+- **0.0** = Least sensitive (more results, lower quality)
+- **1.0** = Most sensitive (fewer results, higher quality)
+
+```typescript
+// Different threshold strategies
+const broadSearch = await client.search.documents({
+ q: "machine learning",
+ chunkThreshold: 0.2, // Return more chunks
+ documentThreshold: 0.1 // From more documents
+});
+
+const preciseSearch = await client.search.documents({
+ q: "machine learning",
+ chunkThreshold: 0.8, // Only highly relevant chunks
+ documentThreshold: 0.7 // From closely matching documents
+});
+```
+
+### 2. Chunk Context vs Exact Matching
+
+By default, Supermemory returns chunks **with context** (surrounding text):
+
+```typescript
+// Default: includes surrounding chunks for context
+const contextualResults = await client.search.documents({
+ q: "neural networks",
+ onlyMatchingChunks: false // Default
+});
+
+// Precise: only the exact matching text
+const exactResults = await client.search.documents({
+ q: "neural networks",
+ onlyMatchingChunks: true
+});
+```
+
+### 3. Query Rewriting & Reranking
+
+**Query Rewriting** (+400ms latency):
+- Expands your query to find more relevant results
+- "ML" becomes "machine learning artificial intelligence"
+- Useful for abbreviations and domain-specific terms
+
+**Reranking**:
+- Re-scores results using a different algorithm
+- More accurate but slower
+- Recommended for critical searches
+
+### 4. Container Tags vs Metadata Filters
+
+Two different filtering mechanisms:
+
+When to use container tags:
+ - The user understanding graph is built on top of container tags. **The graph is formed on top of container tags.**
+ - Container tags are used for organizational grouping and exact matching.
+ - They are useful for categorizing content and ensuring precise results.
+When to use metadata filters:
+ - When you need flexible conditions beyond exact matches.
+ - Useful for filtering by attributes like date, author, or category.
+
+```typescript
+// Container tags: Organizational grouping (exact array matching)
+const userContent = await client.search.documents({
+ q: "python tutorial",
+ containerTag "user_123" // Must match exactly
+});
+
+// Metadata filters: SQL-based queries (flexible conditions)
+const filteredContent = await client.search.documents({
+ q: "python tutorial",
+ filters: JSON.stringify({
+ AND: [
+ { key: "language", value: "python", negate: false },
+ { key: "difficulty", value: "beginner", negate: false }
+ ]
+ })
+});
+```
+
+
+
+<Note>
+**Next Steps:**
+- [Document Search Examples](/search-with-filters/examples/document-search) - Chunked content search
+- [Memory Search Examples](/search-with-filters/examples/memory-search) - Conversational search
+- [Metadata Filtering](/search-with-filters/examples/filtering) - SQL-based filters
+- [Scoring & Thresholds](/search-with-filters/examples/scoring) - Result quality control
+</Note>
diff --git a/apps/docs/search/parameters.mdx b/apps/docs/search/parameters.mdx
new file mode 100644
index 00000000..c4050483
--- /dev/null
+++ b/apps/docs/search/parameters.mdx
@@ -0,0 +1,242 @@
+---
+title: "Search Parameters"
+description: "Complete reference for all search parameters and their effects"
+---
+
+
+Complete parameter reference for all three search endpoints: document search, memory search, and execute search.
+
+## Common Parameters
+
+These parameters work across all search endpoints:
+
+<ParamField query="q" type="string" required>
+ **Search query string**
+
+ The text you want to search for. Can be natural language, keywords, or questions.
+
+ ```typescript
+ q: "machine learning neural networks"
+ q: "What are the applications of quantum computing?"
+ q: "python tutorial beginner"
+ ```
+</ParamField>
+
+<ParamField query="limit" type="number" default="10">
+ **Maximum number of results to return**
+
+ Controls how many results you get back. Higher limits increase response time and size.
+
+ ```typescript
+ limit: 5 // Fast, focused results
+ limit: 20 // Comprehensive results
+ limit: 100 // Maximum recommended
+ ```
+</ParamField>
+
+<ParamField query="containerTags" type="Array<string>">
+ **Filter by container tags**
+
+ Organizational tags for filtering results. Uses **exact array matching** - must match all tags in the same order.
+
+ ```typescript
+ containerTags: ["user_123"] // Single tag
+ containerTags: ["user_123", "project_ai"] // Multiple tags (exact match)
+ ```
+</ParamField>
+
+<ParamField query="filters" type="string">
+ **Metadata filtering with SQL-like structure**
+
+ JSON string containing AND/OR logic for filtering by metadata fields. Uses the same structure as memory listing filters.
+
+ ```typescript
+ filters: JSON.stringify({
+ AND: [
+ { key: "category", value: "tutorial", negate: false },
+ { key: "difficulty", value: "beginner", negate: false }
+ ]
+ })
+ ```
+
+ <Note>
+ See [Metadata Filtering Guide](/search-with-filters/examples/filtering) for complete syntax and examples.
+ </Note>
+</ParamField>
+
+<ParamField query="rerank" type="boolean" default="false">
+ **Re-score results for better relevance**
+
+ Applies a secondary ranking algorithm to improve result quality. Adds ~100-200ms latency but increases accuracy.
+
+ ```typescript
+ rerank: true // Better accuracy, slower
+ rerank: false // Faster, standard accuracy
+ ```
+</ParamField>
+
+<ParamField query="rewriteQuery" type="boolean" default="false">
+ **Expand and improve the query**
+
+ Rewrites your query to find more relevant results. Particularly useful for abbreviations and domain-specific terms. **Adds ~400ms latency**.
+
+ ```typescript
+ // Query rewriting examples:
+ "ML" → "machine learning artificial intelligence"
+ "JS" → "JavaScript programming language"
+ "API" → "application programming interface REST"
+ ```
+
+ <Warning>
+ Query rewriting significantly increases latency. Only use when search quality is more important than speed.
+ </Warning>
+</ParamField>
+
+## Document Search Parameters (POST `/v3/search`)
+
+These parameters are specific to `client.search.documents()`:
+
+<ParamField query="chunkThreshold" type="number" range="0-1" default="0.5">
+ **Sensitivity for chunk selection**
+
+ Controls which text chunks are included in results:
+ - **0.0** = Least sensitive (more chunks, more results)
+ - **1.0** = Most sensitive (fewer chunks, higher quality)
+
+ ```typescript
+ chunkThreshold: 0.2 // Broad search, many chunks
+ chunkThreshold: 0.8 // Precise search, only relevant chunks
+ ```
+</ParamField>
+
+<ParamField query="documentThreshold" type="number" range="0-1" default="0.5">
+ **Sensitivity for document selection**
+
+ Controls which documents are considered for search:
+ - **0.0** = Search more documents (comprehensive)
+ - **1.0** = Search only highly relevant documents (focused)
+
+ ```typescript
+ documentThreshold: 0.1 // Cast wide net
+ documentThreshold: 0.9 // Only very relevant documents
+ ```
+</ParamField>
+
+<ParamField query="docId" type="string">
+ **Search within a specific document**
+
+ Limit search to chunks within a single document. Useful for finding content in large documents.
+
+ ```typescript
+ docId: "doc_abc123" // Only search this document
+ ```
+</ParamField>
+
+<ParamField query="onlyMatchingChunks" type="boolean" default="false">
+ **Return only exact matching chunks**
+
+ By default, Supermemory includes surrounding chunks for context. Set to `true` to get only the exact matching text.
+
+ ```typescript
+ onlyMatchingChunks: false // Include context chunks (default)
+ onlyMatchingChunks: true // Only matching chunks
+ ```
+
+ <Note>
+ Context chunks help LLMs understand the full meaning. Only disable if you need precise text extraction.
+ </Note>
+</ParamField>
+
+<ParamField query="includeFullDocs" type="boolean" default="false">
+ **Include complete document content**
+
+ Adds the full document text to each result. Useful for chatbots that need complete context.
+
+ ```typescript
+ includeFullDocs: true // Full document in response
+ includeFullDocs: false // Only chunks and metadata
+ ```
+
+ <Warning>
+ Including full documents can make responses very large. Use sparingly and with appropriate limits.
+ </Warning>
+</ParamField>
+
+<ParamField query="includeSummary" type="boolean" default="false">
+ **Include document summaries**
+
+ Adds AI-generated document summaries to results. Good middle-ground between chunks and full documents.
+
+ ```typescript
+ includeSummary: true // Include document summaries
+ includeSummary: false // No summaries
+ ```
+</ParamField>
+
+<ParamField query="filters" type="string">
+ **Filter by metadata using SQL queries**
+
+ ```typescript
+
+ // Use this instead:
+ filters: JSON.stringify({
+ OR: [
+ { key: "category", value: "technology", negate: false },
+ { key: "category", value: "science", negate: false }
+ ]
+ })
+ ```
+</ParamField>
+
+## Memory Search Parameters (POST `/v4/search`)
+
+These parameters are specific to `client.search.memories()`:
+
+<ParamField query="threshold" type="number" range="0-1" default="0.5">
+ **Sensitivity for memory selection**
+
+ Controls which memories are returned based on similarity:
+ - **0.0** = Return more memories (broad search)
+ - **1.0** = Return only highly similar memories (precise search)
+
+ ```typescript
+ threshold: 0.3 // Broader memory search
+ threshold: 0.8 // Only very similar memories
+ ```
+</ParamField>
+
+<ParamField query="containerTag" type="string">
+ **Filter by single container tag**
+
+ Note: Memory search uses `containerTag` (singular) while document search uses `containerTags` (plural array).
+
+ ```typescript
+ containerTag: "user_123" // Single tag for memory search
+ ```
+</ParamField>
+
+<ParamField query="include" type="object">
+ **Control what additional data to include**
+
+ Object specifying what contextual information to include with memory results.
+
+ <ParamField query="include.documents" type="boolean" default="false">
+ Include associated documents for each memory
+ </ParamField>
+
+ <ParamField query="include.relatedMemories" type="boolean" default="false">
+ Include parent and child memories (contextual relationships)
+ </ParamField>
+
+ <ParamField query="include.summaries" type="boolean" default="false">
+ Include memory summaries
+ </ParamField>
+
+ ```typescript
+ include: {
+ documents: true, // Show related documents
+ relatedMemories: true, // Show parent/child memories
+ summaries: true // Include summaries
+ }
+ ```
+</ParamField>
diff --git a/apps/docs/search/query-rewriting.mdx b/apps/docs/search/query-rewriting.mdx
new file mode 100644
index 00000000..114af692
--- /dev/null
+++ b/apps/docs/search/query-rewriting.mdx
@@ -0,0 +1,440 @@
+---
+title: "Query Rewriting"
+description: "Improve search accuracy with automatic query expansion and rewriting"
+---
+
+
+![query rewriting](/images/query-rewriting.png)
+
+Query rewriting automatically generates multiple variations of your search query to improve result coverage and accuracy. Supermemory creates several rewrites, searches through all of them, then merges and deduplicates the results.
+
+## How Query Rewriting Works
+
+When you enable `rewriteQuery: true`, Supermemory:
+
+1. **Analyzes your original query** for intent and key concepts
+2. **Generates multiple rewrites** with different phrasings and synonyms
+3. **Executes searches** for both original and rewritten queries in parallel
+4. **Merges and deduplicates** results from all queries
+5. **Returns unified results** ranked by relevance
+
+This process adds ~400ms latency but significantly improves result quality, especially for:
+- **Natural language questions** ("How do neural networks learn?")
+- **Ambiguous terms** that could have multiple meanings
+- **Complex queries** with multiple concepts
+- **Domain-specific terminology** that might have synonyms
+
+## Basic Query Rewriting
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ import Supermemory from 'supermemory';
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ });
+
+ // Without query rewriting
+ const basicResults = await client.search.documents({
+ q: "How do transformers work in AI?",
+ rewriteQuery: false,
+ limit: 5
+ });
+
+ // With query rewriting - generates multiple query variations
+ const rewrittenResults = await client.search.documents({
+ q: "How do transformers work in AI?",
+ rewriteQuery: true,
+ limit: 5
+ });
+
+ console.log(`Basic search: ${basicResults.total} results`);
+ console.log(`Rewritten search: ${rewrittenResults.total} results`);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ from supermemory import Supermemory
+ import os
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+ # Without query rewriting
+ basic_results = client.search.documents(
+ q="How do transformers work in AI?",
+ rewrite_query=False,
+ limit=5
+ )
+
+ # With query rewriting - generates multiple query variations
+ rewritten_results = client.search.documents(
+ q="How do transformers work in AI?",
+ rewrite_query=True,
+ limit=5
+ )
+
+ print(f"Basic search: {basic_results.total} results")
+ print(f"Rewritten search: {rewritten_results.total} results")
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Without query rewriting
+ echo "Basic search:"
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "How do transformers work in AI?",
+ "rewriteQuery": false,
+ "limit": 5
+ }' | jq '.total'
+
+ # With query rewriting
+ echo "Rewritten search:"
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "How do transformers work in AI?",
+ "rewriteQuery": true,
+ "limit": 5
+ }' | jq '.total'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output Comparison:**
+```json
+// Without rewriting: 3 results
+{
+ "results": [...],
+ "total": 3,
+ "timing": 120
+}
+
+// With rewriting: 8 results (found more relevant content)
+{
+ "results": [...],
+ "total": 8,
+ "timing": 520 // +400ms for query processing
+}
+```
+
+## Natural Language Questions
+
+Query rewriting excels at converting conversational questions into effective search queries:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Natural language question
+ const results = await client.search.documents({
+ q: "What are the best practices for training deep learning models?",
+ rewriteQuery: true,
+ limit: 10
+ });
+
+ // The system might generate rewrites like:
+ // - "deep learning model training best practices"
+ // - "neural network training optimization techniques"
+ // - "machine learning model training guidelines"
+ // - "deep learning training methodology"
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Natural language question
+ results = client.search.documents(
+ q="What are the best practices for training deep learning models?",
+ rewrite_query=True,
+ limit=10
+ )
+
+ # The system might generate rewrites like:
+ # - "deep learning model training best practices"
+ # - "neural network training optimization techniques"
+ # - "machine learning model training guidelines"
+ # - "deep learning training methodology"
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "What are the best practices for training deep learning models?",
+ "rewriteQuery": true,
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output:**
+```json
+{
+ "results": [
+ {
+ "documentId": "doc_123",
+ "title": "Deep Learning Training Guide",
+ "score": 0.92,
+ "chunks": [
+ {
+ "content": "Best practices for training deep neural networks include proper weight initialization, learning rate scheduling, and regularization techniques...",
+ "score": 0.89,
+ "isRelevant": true
+ }
+ ]
+ },
+ {
+ "documentId": "doc_456",
+ "title": "Neural Network Optimization",
+ "score": 0.87,
+ "chunks": [
+ {
+ "content": "Effective training methodologies involve batch normalization, dropout, and gradient clipping to prevent overfitting...",
+ "score": 0.85,
+ "isRelevant": true
+ }
+ ]
+ }
+ ],
+ "total": 12,
+ "timing": 445
+}
+```
+
+## Technical Term Expansion
+
+Query rewriting helps find content using different technical terminologies:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Original query with specific terminology
+ const results = await client.search.documents({
+ q: "CNN architecture patterns",
+ rewriteQuery: true,
+ containerTags: ["research"],
+ limit: 8
+ });
+
+ // System expands to include:
+ // - "convolutional neural network architecture"
+ // - "CNN design patterns"
+ // - "convolutional network structures"
+ // - "CNN architectural components"
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Original query with specific terminology
+ results = client.search.documents(
+ q="CNN architecture patterns",
+ rewrite_query=True,
+ container_tags=["research"],
+ limit=8
+ )
+
+ # System expands to include:
+ # - "convolutional neural network architecture"
+ # - "CNN design patterns"
+ # - "convolutional network structures"
+ # - "CNN architectural components"
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "CNN architecture patterns",
+ "rewriteQuery": true,
+ "containerTags": ["research"],
+ "limit": 8
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output:**
+```json
+{
+ "results": [
+ {
+ "documentId": "doc_789",
+ "title": "Convolutional Neural Network Architectures",
+ "score": 0.94,
+ "chunks": [
+ {
+ "content": "Modern CNN architectures like ResNet and DenseNet utilize skip connections to address the vanishing gradient problem...",
+ "score": 0.91,
+ "isRelevant": true
+ }
+ ]
+ },
+ {
+ "documentId": "doc_101",
+ "title": "Deep Learning Design Patterns",
+ "score": 0.88,
+ "chunks": [
+ {
+ "content": "Convolutional layers followed by pooling operations form the fundamental building blocks of CNN architectures...",
+ "score": 0.86,
+ "isRelevant": true
+ }
+ ]
+ }
+ ],
+ "total": 15,
+ "timing": 478
+}
+```
+
+## Memory Search with Query Rewriting
+
+Query rewriting works with both document and memory search:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Memory search with query rewriting
+ const memoryResults = await client.search.memories({
+ q: "explain quantum entanglement simply",
+ rewriteQuery: true,
+ containerTag: "physics_notes",
+ limit: 5
+ });
+
+ // Generates variations like:
+ // - "quantum entanglement explanation"
+ // - "what is quantum entanglement"
+ // - "quantum entanglement basics"
+ // - "simple quantum entanglement description"
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Memory search with query rewriting
+ memory_results = client.search.memories(
+ q="explain quantum entanglement simply",
+ rewrite_query=True,
+ container_tag="physics_notes",
+ limit=5
+ )
+
+ # Generates variations like:
+ # - "quantum entanglement explanation"
+ # - "what is quantum entanglement"
+ # - "quantum entanglement basics"
+ # - "simple quantum entanglement description"
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "explain quantum entanglement simply",
+ "rewriteQuery": true,
+ "containerTag": "physics_notes",
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output:**
+```json
+{
+ "results": [
+ {
+ "id": "mem_456",
+ "memory": "Quantum entanglement is a phenomenon where two particles become connected in such a way that measuring one instantly affects the other, regardless of distance. Think of it like having two magical coins that always land on opposite sides.",
+ "similarity": 0.91,
+ "title": "Simple Quantum Entanglement Explanation",
+ "metadata": {
+ "topic": "quantum-physics",
+ "difficulty": "beginner"
+ }
+ },
+ {
+ "id": "mem_789",
+ "memory": "Einstein called quantum entanglement 'spooky action at a distance' because entangled particles seem to communicate instantaneously across vast distances, challenging our understanding of locality in physics.",
+ "similarity": 0.87,
+ "title": "Einstein's View on Entanglement"
+ }
+ ],
+ "total": 7,
+ "timing": 412
+}
+```
+
+## Complex Multi-Concept Queries
+
+Query rewriting excels at handling queries with multiple concepts:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "machine learning bias fairness algorithmic discrimination",
+ rewriteQuery: true,
+ filters: {
+ AND: [
+ { key: "category", value: "ethics", negate: false }
+ ]
+ },
+ limit: 10
+ });
+
+ // Breaks down into focused rewrites:
+ // - "machine learning bias detection"
+ // - "algorithmic fairness in AI"
+ // - "discrimination in machine learning algorithms"
+ // - "bias mitigation techniques ML"
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="machine learning bias fairness algorithmic discrimination",
+ rewrite_query=True,
+ filters={
+ "AND": [
+ {"key": "category", "value": "ethics", "negate": False}
+ ]
+ },
+ limit=10
+ )
+
+ # Breaks down into focused rewrites:
+ # - "machine learning bias detection"
+ # - "algorithmic fairness in AI"
+ # - "discrimination in machine learning algorithms"
+ # - "bias mitigation techniques ML"
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "machine learning bias fairness algorithmic discrimination",
+ "rewriteQuery": true,
+ "filters": {
+ "AND": [
+ {"key": "category", "value": "ethics", "negate": false}
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
diff --git a/apps/docs/search/reranking.mdx b/apps/docs/search/reranking.mdx
new file mode 100644
index 00000000..7d2e017a
--- /dev/null
+++ b/apps/docs/search/reranking.mdx
@@ -0,0 +1,387 @@
+---
+title: "Reranking"
+description: "Improve result relevance with secondary ranking algorithms"
+---
+
+
+Reranking applies a secondary ranking algorithm to improve the relevance order of search results. After the initial search returns results, the reranker analyzes the relationship between your query and each result to provide better ordering.
+
+## How Reranking Works
+
+Supermemory's reranking process:
+
+1. **Initial search** returns results using standard semantic similarity
+2. **Reranker model** analyzes query-result pairs
+3. **Scores are recalculated** based on deeper semantic understanding
+4. **Results are reordered** by the new relevance scores
+5. **Final results** maintain the same structure but with improved ordering
+
+The reranker is particularly effective at:
+- **Understanding context** and nuanced relationships
+- **Handling ambiguous queries** with multiple possible meanings
+- **Improving precision** for complex technical topics
+- **Better ranking** when results have similar initial scores
+
+## Basic Reranking Comparison
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ import Supermemory from 'supermemory';
+
+ const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+ });
+
+ // Search without reranking
+ const standardResults = await client.search.documents({
+ q: "neural network optimization techniques",
+ rerank: false,
+ limit: 5
+ });
+
+ // Search with reranking
+ const rerankedResults = await client.search.documents({
+ q: "neural network optimization techniques",
+ rerank: true,
+ limit: 5
+ });
+
+ console.log("Standard top result:", standardResults.results[0].score);
+ console.log("Reranked top result:", rerankedResults.results[0].score);
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ from supermemory import Supermemory
+ import os
+
+ client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+ # Search without reranking
+ standard_results = client.search.documents(
+ q="neural network optimization techniques",
+ rerank=False,
+ limit=5
+ )
+
+ # Search with reranking
+ reranked_results = client.search.documents(
+ q="neural network optimization techniques",
+ rerank=True,
+ limit=5
+ )
+
+ print("Standard top result:", standard_results.results[0].score)
+ print("Reranked top result:", reranked_results.results[0].score)
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ # Without reranking
+ echo "Standard ranking:"
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "neural network optimization techniques",
+ "rerank": false,
+ "limit": 3
+ }' | jq '.results[0] | {title, score}'
+
+ # With reranking
+ echo "Reranked results:"
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "neural network optimization techniques",
+ "rerank": true,
+ "limit": 3
+ }' | jq '.results[0] | {title, score}'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output Comparison:**
+
+```json
+// Without reranking - results ordered by semantic similarity
+{
+ "results": [
+ {
+ "title": "Deep Learning Optimization Methods",
+ "score": 0.82,
+ "chunks": [
+ {
+ "content": "Various optimization algorithms like Adam, RMSprop, and SGD are used in neural network training...",
+ "score": 0.79
+ }
+ ]
+ },
+ {
+ "title": "Neural Network Training Techniques",
+ "score": 0.81,
+ "chunks": [
+ {
+ "content": "Batch normalization and dropout are common regularization techniques for neural networks...",
+ "score": 0.78
+ }
+ ]
+ }
+ ],
+ "timing": 145
+}
+
+// With reranking - results reordered by contextual relevance
+{
+ "results": [
+ {
+ "title": "Neural Network Training Techniques",
+ "score": 0.89, // Boosted by reranker
+ "chunks": [
+ {
+ "content": "Batch normalization and dropout are common regularization techniques for neural networks...",
+ "score": 0.85
+ }
+ ]
+ },
+ {
+ "title": "Deep Learning Optimization Methods",
+ "score": 0.86, // Slightly adjusted
+ "chunks": [
+ {
+ "content": "Various optimization algorithms like Adam, RMSprop, and SGD are used in neural network training...",
+ "score": 0.83
+ }
+ ]
+ }
+ ],
+ "timing": 267 // Additional ~120ms for reranking
+}
+```
+
+## Complex Query Reranking
+
+Reranking excels with complex, multi-faceted queries:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const results = await client.search.documents({
+ q: "sustainable machine learning carbon footprint energy efficiency",
+ rerank: true,
+ containerTags: ["research", "sustainability"],
+ limit: 8
+ });
+
+ // Reranker understands the connection between:
+ // - Machine learning computational costs
+ // - Environmental impact of AI training
+ // - Energy-efficient model architectures
+ // - Green computing practices in ML
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ results = client.search.documents(
+ q="sustainable machine learning carbon footprint energy efficiency",
+ rerank=True,
+ container_tags=["research", "sustainability"],
+ limit=8
+ )
+
+ # Reranker understands the connection between:
+ # - Machine learning computational costs
+ # - Environmental impact of AI training
+ # - Energy-efficient model architectures
+ # - Green computing practices in ML
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "sustainable machine learning carbon footprint energy efficiency",
+ "rerank": true,
+ "containerTags": ["research", "sustainability"],
+ "limit": 8
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output:**
+```json
+{
+ "results": [
+ {
+ "documentId": "doc_green_ai",
+ "title": "Green AI: Reducing the Carbon Footprint of Machine Learning",
+ "score": 0.94, // Highly relevant after reranking
+ "chunks": [
+ {
+ "content": "Training large neural networks can consume as much energy as several cars over their lifetime. Sustainable ML practices focus on model efficiency, pruning, and quantization to reduce computational demands...",
+ "score": 0.92,
+ "isRelevant": true
+ }
+ ]
+ },
+ {
+ "documentId": "doc_efficient_models",
+ "title": "Energy-Efficient Neural Network Architectures",
+ "score": 0.91, // Boosted for strong topical relevance
+ "chunks": [
+ {
+ "content": "MobileNets and EfficientNets are designed specifically for energy-constrained environments, achieving high accuracy with minimal computational overhead...",
+ "score": 0.88,
+ "isRelevant": true
+ }
+ ]
+ }
+ ],
+ "total": 12,
+ "timing": 298
+}
+```
+
+## Memory Search Reranking
+
+Reranking also improves memory search results:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ const memoryResults = await client.search.memories({
+ q: "explain transformer architecture attention mechanism",
+ rerank: true,
+ containerTag: "ai_notes",
+ threshold: 0.6,
+ limit: 5
+ });
+
+ // Reranker identifies memories that best explain
+ // the relationship between transformers and attention
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ memory_results = client.search.memories(
+ q="explain transformer architecture attention mechanism",
+ rerank=True,
+ container_tag="ai_notes",
+ threshold=0.6,
+ limit=5
+ )
+
+ # Reranker identifies memories that best explain
+ # the relationship between transformers and attention
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v4/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "explain transformer architecture attention mechanism",
+ "rerank": true,
+ "containerTag": "ai_notes",
+ "threshold": 0.6,
+ "limit": 5
+ }'
+ ```
+ </Tab>
+</Tabs>
+
+**Sample Output:**
+```json
+{
+ "results": [
+ {
+ "id": "mem_transformer_intro",
+ "memory": "The transformer architecture revolutionized NLP by replacing recurrent layers with self-attention mechanisms. The attention mechanism allows the model to focus on different parts of the input sequence when processing each token, enabling parallel processing and better long-range dependency modeling.",
+ "similarity": 0.93, // Reranked higher for comprehensive explanation
+ "title": "Transformer Architecture Overview",
+ "metadata": {
+ "topic": "deep-learning",
+ "subtopic": "transformers"
+ }
+ },
+ {
+ "id": "mem_attention_detail",
+ "memory": "Self-attention computes attention weights by taking dot products between query, key, and value vectors derived from the input embeddings. This allows each position to attend to all positions in the previous layer, capturing complex relationships in the data.",
+ "similarity": 0.91, // Boosted for technical detail
+ "title": "Self-Attention Mechanism Details"
+ }
+ ],
+ "total": 8,
+ "timing": 198
+}
+```
+
+## Domain-Specific Reranking
+
+Reranking understands domain-specific relationships:
+
+<Tabs>
+ <Tab title="TypeScript">
+ ```typescript
+ // Medical domain query
+ const medicalResults = await client.search.documents({
+ q: "diabetes treatment insulin resistance metformin",
+ rerank: true,
+ filters: {
+ AND: [
+ { key: "domain", value: "medical", negate: false }
+ ]
+ },
+ limit: 10
+ });
+
+ // Reranker understands medical relationships:
+ // - Diabetes types and treatments
+ // - Insulin resistance mechanisms
+ // - Metformin's role in diabetes management
+ ```
+ </Tab>
+ <Tab title="Python">
+ ```python
+ # Medical domain query
+ medical_results = client.search.documents(
+ q="diabetes treatment insulin resistance metformin",
+ rerank=True,
+ filters={
+ "AND": [
+ {"key": "domain", "value": "medical", "negate": False}
+ ]
+ },
+ limit=10
+ )
+
+ # Reranker understands medical relationships:
+ # - Diabetes types and treatments
+ # - Insulin resistance mechanisms
+ # - Metformin's role in diabetes management
+ ```
+ </Tab>
+ <Tab title="cURL">
+ ```bash
+ curl -X POST "https://api.supermemory.ai/v3/search" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "q": "diabetes treatment insulin resistance metformin",
+ "rerank": true,
+ "filters": {
+ "AND": [
+ {"key": "domain", "value": "medical", "negate": false}
+ ]
+ },
+ "limit": 10
+ }'
+ ```
+ </Tab>
+</Tabs>
diff --git a/apps/docs/search/response-schema.mdx b/apps/docs/search/response-schema.mdx
new file mode 100644
index 00000000..f9234787
--- /dev/null
+++ b/apps/docs/search/response-schema.mdx
@@ -0,0 +1,261 @@
+---
+title: "Response Schema"
+description: "Complete response structure for all search endpoints with scoring details"
+---
+
+
+## Document Search Response (POST `/v3/search`)
+
+Response from `client.search.documents()` and `client.search.execute()`:
+
+```json
+{
+ "results": [
+ {
+ "documentId": "doc_abc123",
+ "title": "Machine Learning Fundamentals",
+ "type": "pdf",
+ "score": 0.89,
+ "chunks": [
+ {
+ "content": "Machine learning is a subset of artificial intelligence...",
+ "score": 0.95,
+ "isRelevant": true
+ }
+ ],
+ "metadata": {
+ "category": "education",
+ "author": "Dr. Smith",
+ "difficulty": "beginner"
+ },
+ "createdAt": "2024-01-15T10:30:00Z",
+ "updatedAt": "2024-01-20T14:45:00Z"
+ }
+ ],
+ "timing": 187,
+ "total": 1
+}
+```
+
+### Document Result Fields
+
+<ResponseField name="documentId" type="string">
+ Unique identifier for the document containing the matching chunks.
+</ResponseField>
+
+<ResponseField name="title" type="string | null">
+ Document title if available. May be null for documents without titles.
+</ResponseField>
+
+<ResponseField name="type" type="string | null">
+ Document type (e.g., "pdf", "text", "webpage", "notion_doc"). May be null if not specified.
+</ResponseField>
+
+<ResponseField name="score" type="number" range="0-1">
+ **Overall document relevance score**. Combines semantic similarity, keyword matching, and metadata relevance.
+
+ - **0.9-1.0**: Extremely relevant
+ - **0.7-0.9**: Highly relevant
+ - **0.5-0.7**: Moderately relevant
+ - **0.3-0.5**: Somewhat relevant
+ - **0.0-0.3**: Marginally relevant
+</ResponseField>
+
+<ResponseField name="chunks" type="Array<Chunk>">
+ Array of matching text chunks from the document. Each chunk represents a portion of the document that matched your query.
+
+ <ResponseField name="chunks[].content" type="string">
+ The actual text content of the matching chunk. May include context from surrounding chunks unless `onlyMatchingChunks=true`.
+ </ResponseField>
+
+ <ResponseField name="chunks[].score" type="number" range="0-1">
+ **Chunk-specific similarity score**. How well this specific chunk matches your query.
+ </ResponseField>
+
+ <ResponseField name="chunks[].isRelevant" type="boolean">
+ Whether this chunk passed the `chunkThreshold`. `true` means the chunk is above the threshold, `false` means it's included for context only.
+ </ResponseField>
+</ResponseField>
+
+<ResponseField name="metadata" type="object | null">
+ Document metadata as key-value pairs. Structure depends on what was stored with the document.
+
+ ```json
+ {
+ "category": "tutorial",
+ "language": "python",
+ "difficulty": "intermediate",
+ "tags": "web-development,backend"
+ }
+ ```
+</ResponseField>
+
+<ResponseField name="createdAt" type="string">
+ ISO 8601 timestamp when the document was created.
+</ResponseField>
+
+<ResponseField name="updatedAt" type="string">
+ ISO 8601 timestamp when the document was last updated.
+</ResponseField>
+
+<ResponseField name="content" type="string | null" optional>
+ **Full document content**. Only included when `includeFullDocs=true`. Can be very large.
+
+ <Warning>
+ Full document content can make responses extremely large. Use with appropriate limits and only when necessary.
+ </Warning>
+</ResponseField>
+
+<ResponseField name="summary" type="string | null" optional>
+ **AI-generated document summary**. Only included when `includeSummary=true`. Provides a concise overview of the document.
+</ResponseField>
+
+## Memory Search Response
+
+Response from `client.search.memories()`:
+
+```json
+{
+ "results": [
+ {
+ "id": "mem_xyz789",
+ "memory": "Complete memory content about quantum computing applications...",
+ "similarity": 0.87,
+ "metadata": {
+ "category": "research",
+ "topic": "quantum-computing"
+ },
+ "updatedAt": "2024-01-18T09:15:00Z",
+ "version": 3,
+ "context": {
+ "parents": [
+ {
+ "memory": "Earlier discussion about quantum theory basics...",
+ "relation": "extends",
+ "version": 2,
+ "updatedAt": "2024-01-17T16:30:00Z"
+ }
+ ],
+ "children": [
+ {
+ "memory": "Follow-up questions about quantum algorithms...",
+ "relation": "derives",
+ "version": 4,
+ "updatedAt": "2024-01-19T11:20:00Z"
+ }
+ ]
+ },
+ "documents": [
+ {
+ "id": "doc_quantum_paper",
+ "title": "Quantum Computing Applications",
+ "type": "pdf",
+ "createdAt": "2024-01-10T08:00:00Z"
+ }
+ ]
+ }
+ ],
+ "timing": 156,
+ "total": 1
+}
+```
+
+### Memory Result Fields
+
+<ResponseField name="id" type="string">
+ Unique identifier for the memory entry.
+</ResponseField>
+
+<ResponseField name="memory" type="string">
+ **Complete memory content**. Unlike document search which returns chunks, memory search returns the full memory text.
+</ResponseField>
+
+<ResponseField name="similarity" type="number" range="0-1">
+ **Similarity score** between your query and this memory. Higher scores indicate better matches.
+
+ - **0.9-1.0**: Extremely similar
+ - **0.8-0.9**: Very similar
+ - **0.7-0.8**: Similar
+ - **0.6-0.7**: Somewhat similar
+ - **0.5-0.6**: Marginally similar
+</ResponseField>
+
+<ResponseField name="metadata" type="object | null">
+ Memory metadata as key-value pairs. Structure depends on what was stored with the memory.
+</ResponseField>
+
+<ResponseField name="updatedAt" type="string">
+ ISO 8601 timestamp when the memory was last updated.
+</ResponseField>
+
+<ResponseField name="version" type="number | null" optional>
+ Version number of this memory entry. Used for tracking memory evolution and relationships.
+</ResponseField>
+
+<ResponseField name="context" type="object" optional>
+ **Contextual memory relationships**. Only included when `include.relatedMemories=true`.
+
+ <ResponseField name="context.parents" type="Array<ContextMemory>" optional>
+ Array of parent memories that this memory extends or derives from.
+ </ResponseField>
+
+ <ResponseField name="context.children" type="Array<ContextMemory>" optional>
+ Array of child memories that extend or derive from this memory.
+ </ResponseField>
+
+ ### Context Memory Structure
+
+ <ResponseField name="memory" type="string">
+ Content of the related memory.
+ </ResponseField>
+
+ <ResponseField name="relation" type="string">
+ Relationship type: `"updates"`, `"extends"`, or `"derives"`.
+
+ - **updates**: This memory updates/replaces the related memory
+ - **extends**: This memory builds upon the related memory
+ - **derives**: This memory is derived from the related memory
+ </ResponseField>
+
+ <ResponseField name="version" type="number | null">
+ Relative version distance:
+ - **Negative values** for parents (-1 = direct parent, -2 = grandparent)
+ - **Positive values** for children (+1 = direct child, +2 = grandchild)
+ </ResponseField>
+
+ <ResponseField name="updatedAt" type="string">
+ When the related memory was last updated.
+ </ResponseField>
+
+ <ResponseField name="metadata" type="object | null" optional>
+ Metadata of the related memory.
+ </ResponseField>
+</ResponseField>
+
+<ResponseField name="documents" type="Array<Document>" optional>
+ **Associated documents**. Only included when `include.documents=true`.
+
+ <ResponseField name="documents[].id" type="string">
+ Document identifier.
+ </ResponseField>
+
+ <ResponseField name="documents[].title" type="string">
+ Document title.
+ </ResponseField>
+
+ <ResponseField name="documents[].type" type="string">
+ Document type.
+ </ResponseField>
+
+ <ResponseField name="documents[].metadata" type="object">
+ Document metadata.
+ </ResponseField>
+
+ <ResponseField name="documents[].createdAt" type="string">
+ Document creation timestamp.
+ </ResponseField>
+
+ <ResponseField name="documents[].updatedAt" type="string">
+ Document update timestamp.
+ </ResponseField>
+</ResponseField>
diff --git a/apps/docs/snippets/getting-api-key.mdx b/apps/docs/snippets/getting-api-key.mdx
new file mode 100644
index 00000000..1531f5dc
--- /dev/null
+++ b/apps/docs/snippets/getting-api-key.mdx
@@ -0,0 +1,34 @@
+Head to [supermemory's Developer Platform](https://console.supermemory.ai) built to help you monitor and manage every aspect of the API.
+
+<Accordion title="Getting an API Key" icon="sparkles">
+ <Steps>
+ <Step title="Create an account" icon="circle-user">
+ An account will automatically be created on your first login.
+
+ ![Dev Platform Login Pn](/images/dev-platform-login.png)
+ </Step>
+ <Step title="Create an API Key" icon="key">
+ <Steps>
+ <Step title="Navigate to API Keys">
+ ![Dev Platform Api Keys Pn](/images/dev-platform-api-keys.png)
+
+ Click `Create API Key`
+ </Step>
+ <Step title="Choose Name and Expiry (Optional)">
+ ![Dev Platform Create Key Pn](/images/dev-platform-create-key.png)
+
+ Click `Create`
+ </Step>
+ <Step title="Copy New Key">
+ ![Dev Platform Copy Key Pn](/images/dev-platform-copy-key.png)
+
+ Click <Icon icon="clipboard" /> to copy
+ </Step>
+ </Steps>
+ </Step>
+ </Steps>
+</Accordion>
+
+Done\! You can now use your API key to authenticate requests to the supermemory API.
+
+Next up, let's add your first memory. \ No newline at end of file
diff --git a/apps/docs/supermemory-mcp/introduction.mdx b/apps/docs/supermemory-mcp/introduction.mdx
new file mode 100644
index 00000000..0ee96b45
--- /dev/null
+++ b/apps/docs/supermemory-mcp/introduction.mdx
@@ -0,0 +1,74 @@
+---
+title: 'About supermemory MCP'
+description: 'Carry your memories with you, using supermemory MCP'
+---
+
+supermemory MCP is a lightweight **consumer-facing** component that allows you to carry your memories with you across any AI platform. It serves as a universal memory layer that enables Large Language Models (LLMs) to maintain persistent context and memories across different applications and sessions, solving the fundamental limitation of AI assistants forgetting everything between conversations.
+
+## What supermemory MCP is and how it works
+
+**supermemory MCP** functions as an open-source, universal memory system that bridges the gap between isolated AI applications through the Model Context Protocol (MCP). It operates as a **meta MCP server** that creates individual server instances for each user, providing seamless memory persistence across any MCP-compatible LLM client including ChatGPT, Claude, Windsurf, Cursor, and VS Code.
+
+The system works by running as an MCP server that communicates with MCP-compatible clients, storing and retrieving contextual information through the robust supermemory API infrastructure. When users interact with any connected AI application, the system automatically captures relevant information and makes it available to all other connected platforms through **semantic search and intelligent retrieval**.
+
+
+It is also a great example of how you can use supermemory to build your own consumer-facing applications.
+<Card title="supermemory MCP code" icon="github" href="https://github.com/supermemoryai/supermemory-mcp">
+ Code behind the scenes
+</Card>
+
+
+### Key consumer benefits
+
+- **No login requirements**: Access granted via unique, private URLs that serve as both identifier and API key
+- **Completely free**: Fully functional hosted service available at no cost
+- **One-command setup**: Single CLI installation: `npx install-mcp [URL] --client [CLIENT]`
+- **Universal compatibility**: Works seamlessly across multiple LLM clients and platforms
+
+
+### Core workflow process
+
+1. User interacts with any MCP-compatible AI client
+2. The client connects to supermemory MCP server via a unique, private URL
+3. During conversations, relevant information is stored using the `addToSupermemory` action
+4. When context is needed, the `searchSupermemory` action retrieves relevant memories
+5. The AI assistant accesses this persistent context regardless of which platform is being used
+
+## Building applications with supermemory
+
+supermemory MCP demonstrates building consumer applications with supermemory through its **API-first architecture**. The system acts as a "customer" of the underlying supermemory API infrastructure, showcasing how developers can leverage the platform to create their own memory-enabled applications.
+
+### Supported platforms
+
+- **Claude Desktop**: Direct SSE connection support
+- **Cursor IDE**: Global MCP server configuration via `~/.cursor/mcp.json`
+- **Windsurf**: Seamless integration for AI-powered development
+- **VS Code**: Compatible with various AI coding extensions
+- **Cline/Roo-Cline**: Full MCP protocol support
+- **Any MCP-compatible application**: Universal compatibility through standard protocol implementation
+
+## Security and privacy considerations
+
+### Security model
+
+- **URL-based authentication**: Random URLs serve as access keys, eliminating traditional login complexity
+- **Session isolation**: Complete user data separation through unique URL paths
+- **Self-hosting option**: Full control over data and infrastructure for privacy-conscious users
+- **No authentication overhead**: Simplified access without traditional username/password systems
+
+### Privacy features
+
+- **Data isolation**: User memories completely separated by unique URLs
+- **Local control option**: Self-hosting capability for enterprise or sensitive use cases
+- **Secure infrastructure**: Built on Cloudflare's enterprise-grade security platform
+
+## Future developments and ecosystem
+
+The project represents a **breakthrough in AI memory portability**, with ongoing developments including:
+
+- **Infinite Chat API**: Enhanced inline memory management with conversation history
+- **Expanded client support**: More MCP clients adding SSE connection capabilities
+- **Enterprise features**: Advanced security and compliance options for business use
+- **Integration expansion**: Potential connections to Google Drive, Notion, OneDrive, and other productivity platforms
+
+supermemory MCP successfully demonstrates how to build compelling consumer-facing applications using supermemory's infrastructure, achieving massive adoption through exceptional user experience design combined with robust technical architecture. Its success validates the market demand for universal AI memory solutions and provides a compelling template for developers building their own memory-enabled applications. \ No newline at end of file
diff --git a/apps/docs/supermemory-mcp/setup.mdx b/apps/docs/supermemory-mcp/setup.mdx
new file mode 100644
index 00000000..23f17967
--- /dev/null
+++ b/apps/docs/supermemory-mcp/setup.mdx
@@ -0,0 +1,67 @@
+---
+title: 'Setup and usage'
+description: 'How to set up and use supermemory MCP'
+---
+
+### Hosted setup (recommended)
+
+1. **Visit** https://mcp.supermemory.ai
+2. **Receive** automatically generated unique URL (e.g., `https://mcp.supermemory.ai/TN-IKxAcDdHWTJkMhtGLF/sse`)
+3. **Select** your MCP client from the dropdown menu
+4. **Copy** the generated installation command
+5. **Run** the command: `npx install-mcp [YOUR_URL] --client [CLIENT_NAME]`
+
+Or follow the client configuration example below.
+
+### Self-hosted configuration
+
+For users requiring complete data control:
+
+1. **Obtain API key** from https://console.supermemory.ai
+2. **Create `.env` file** with `SUPERMEMORY_API_KEY=your_key`
+3. **Clone repository**: `git clone https://github.com/supermemoryai/supermemory-mcp.git`
+4. **Configure MCP client** to connect to local server instance
+
+### Client configuration example
+
+1. For Clients that support `url` configuration:
+```json
+{
+ "mcpServers": {
+ "supermemory": {
+ "transport": "sse",
+ "url": "https://mcp.supermemory.ai/[USER_ID]/sse"
+ }
+ }
+}
+```
+
+2. Using `supergateway` with `npx`:
+```json
+{
+ "command": "npx",
+ "args": ["-y", "supergateway", "--sse", "YOUR_URL"]
+}
+```
+
+3. Using `supergateway` with `docker`:
+
+The equivalent MCP command would be:
+```json
+{
+ "mcpServers": {
+ "supermachineExampleDocker": {
+ "command": "docker",
+ "args": [
+ "run",
+ "-i",
+ "--rm",
+ "supercorp/supergateway",
+ "--sse",
+ "YOUR_SUPERMEMORY_URL"
+ ]
+ }
+ }
+}
+```
+
diff --git a/apps/docs/supermemory-mcp/technology.mdx b/apps/docs/supermemory-mcp/technology.mdx
new file mode 100644
index 00000000..5f64e87d
--- /dev/null
+++ b/apps/docs/supermemory-mcp/technology.mdx
@@ -0,0 +1,48 @@
+---
+title: 'Technical implementation details'
+description: 'Technical implementation details of supermemory MCP'
+---
+
+The technical architecture prioritizes **simplicity and user experience** while maintaining robust functionality. Built as what the creators describe as "the simplest thing you'll see" - essentially a React Router application making fetch calls to the supermemory API - the entire system was developed and shipped in approximately 5 hours of actual work time.
+
+### Architecture components
+
+- **Backend API**: Built on top of the supermemory API (https://api.supermemory.ai/v3)
+- **Transport Layer**: Uses Server-Sent Events (SSE) for real-time communication
+- **Dynamic Server Generation**: Creates unique MCP server instances for each user via URL path parameters
+- **Session Management**: Maintains complete user isolation through unique URLs
+- **Infrastructure**: Hosted on Cloudflare using Durable Objects for persistent, long-running connections
+
+The system leverages **Cloudflare's infrastructure** with CPU-based billing, making it highly efficient since memory connections spend most time waiting between interactions rather than actively processing, resulting in minimal CPU usage despite potentially running for millions of milliseconds.
+
+## The two main components explained
+
+### addToSupermemory action
+
+This component **stores user information, preferences, and behavioral patterns** with sophisticated triggering mechanisms:
+
+**Trigger methods:**
+- **Explicit commands**: Direct user instructions like "remember this"
+- **Implicit detection**: Automatic identification of significant user traits, preferences, or patterns during conversations
+
+**Data types captured:**
+- Technical preferences and details (e.g., "My primary programming language is Python")
+- Project information and context (e.g., "I'm currently working on a project named 'Apollo'")
+- User behaviors and emotional responses
+- Personal facts, preferences, and decision-making patterns
+- Rich context including technical details and examples
+
+### searchSupermemory action
+
+This component **retrieves relevant information** from stored memories using advanced search capabilities:
+
+**Activation triggers:**
+- Explicit user requests for historical information
+- Contextual situations where past user choices would be helpful for current decisions
+- Automatic context enhancement based on conversation flow
+
+**Search capabilities:**
+- **Semantic matching**: Finds relevant details across related experiences using vector search
+- **Pattern recognition**: Identifies behavioral patterns and preferences
+- **Cross-session retrieval**: Accesses memories from previous conversations and platforms
+- **Intelligent filtering**: Returns most relevant context based on current conversation needs
diff --git a/apps/docs/update-delete-memories/overview.mdx b/apps/docs/update-delete-memories/overview.mdx
new file mode 100644
index 00000000..f708a561
--- /dev/null
+++ b/apps/docs/update-delete-memories/overview.mdx
@@ -0,0 +1,510 @@
+---
+title: "Update & Delete Memories"
+description: "Safely update and delete memories with upsert patterns and idempotency"
+icon: "delete"
+---
+
+Choose from direct updates, idempotent upserts, single deletions, and powerful bulk operations.
+
+## Direct Updates
+
+Update existing memories by their ID when you know the specific memory you want to modify. Changes trigger reprocessing through the full pipeline.
+
+<CodeGroup>
+
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+});
+
+// Update by memory ID
+const updated = await client.memories.update('memory_id_123', {
+ content: 'Updated content here',
+ metadata: { version: 2, updated: true }
+});
+
+console.log(updated.status); // "queued" for reprocessing
+console.log(updated.id); // "memory_id_123"
+```
+
+```python Python
+from supermemory import Supermemory
+import os
+
+client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+# Update by memory ID
+updated = client.memories.update(
+ 'memory_id_123',
+ content='Updated content here',
+ metadata={'version': 2, 'updated': True}
+)
+
+print(f"Status: {updated.status}") # "queued" for reprocessing
+print(f"ID: {updated.id}") # "memory_id_123"
+```
+
+```bash cURL
+curl -X PATCH "https://api.supermemory.ai/v3/documents/memory_id_123" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "content": "Updated content here",
+ "metadata": {"version": 2, "updated": true}
+ }'
+```
+
+</CodeGroup>
+
+## Upserts Using customId
+
+Use `customId` for idempotent operations where the same `customId` with `add()` will update existing memory instead of creating duplicates.
+
+<CodeGroup>
+
+```typescript Typescript
+import Supermemory from 'supermemory';
+
+const client = new Supermemory({
+ apiKey: process.env.SUPERMEMORY_API_KEY!
+});
+
+const customId = 'user-note-001';
+
+// First call creates memory
+const created = await client.memories.add({
+ content: 'Initial content',
+ customId: customId,
+ metadata: { version: 1 }
+});
+
+console.log('Created memory:', created.id);
+
+// Second call with same customId updates existing
+const updated = await client.memories.add({
+ content: 'Updated content',
+ customId: customId, // Same customId = upsert
+ metadata: { version: 2 }
+});
+```
+
+```python Python
+from supermemory import Supermemory
+import os
+
+client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
+
+custom_id = 'user-note-001'
+
+# First call creates memory
+created = client.memories.add(
+ content='Initial content',
+ custom_id=custom_id,
+ metadata={'version': 1}
+)
+
+print(f'Created memory: {created.id}')
+
+# Second call with same customId updates existing
+updated = client.memories.add(
+ content='Updated content',
+ custom_id=custom_id, # Same customId = upsert
+ metadata={'version': 2}
+)
+
+print(f'Updated memory: {updated.id}')
+print(f'Same memory? {created.id == updated.id}') # True
+```
+
+```bash cURL
+# First call - creates memory
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "content": "Initial content",
+ "customId": "user-note-001",
+ "metadata": {"version": 1}
+ }'
+
+# Response: {"id": "mem_abc123", "status": "queued", "customId": "user-note-001"}
+
+# Second call - updates existing (same customId)
+curl -X POST "https://api.supermemory.ai/v3/documents" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "content": "Updated content",
+ "customId": "user-note-001",
+ "metadata": {"version": 2}
+ }'
+
+# Response: {"id": "mem_abc123", "status": "queued", "customId": "user-note-001"}
+# Note: Same ID returned - memory was updated, not created
+```
+
+</CodeGroup>
+
+<Note>
+The `customId` enables idempotency across all endpoints. The `memoryId` doesn't support idempotency, only the `customId` does.
+</Note>
+
+## Single Delete
+
+Delete individual memories by their ID. This is a permanent hard delete with no recovery mechanism.
+
+<CodeGroup>
+
+```typescript Typescript
+// Hard delete - permanently removes memory
+await client.memories.delete('memory_id_123');
+console.log('Memory deleted successfully');
+```
+
+```python Python
+# Hard delete - permanently removes memory
+client.memories.delete('memory_id_123')
+print('Memory deleted successfully')
+
+# Error handling for single delete
+try:
+ client.memories.delete('memory_id_123')
+ print('Delete successful')
+except NotFoundError:
+ print('Memory not found or already deleted')
+except AuthenticationError:
+ print('Authentication failed')
+except Exception as e:
+ print(f'Delete failed: {e}')
+```
+
+```bash cURL
+curl -X DELETE "https://api.supermemory.ai/v3/documents/memory_id_123" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY"
+
+# Response: 204 No Content (success)
+# Response: 404 Not Found (memory doesn't exist)
+```
+
+</CodeGroup>
+
+## Bulk Delete by IDs
+
+Delete multiple memories at once by providing an array of memory IDs. Maximum of 100 IDs per request.
+
+<CodeGroup>
+
+```typescript Typescript
+// Bulk delete by memory IDs
+const result = await client.memories.bulkDelete({
+ ids: [
+ 'memory_id_1',
+ 'memory_id_2',
+ 'memory_id_3',
+ 'non_existent_id' // This will be reported in errors
+ ]
+});
+
+console.log('Bulk delete result:', result);
+// Output: {
+// success: true,
+// deletedCount: 3,
+// errors: [
+// { id: "non_existent_id", error: "Memory not found" }
+// ]
+// }
+```
+
+```python Python
+# Bulk delete by memory IDs
+result = client.memories.bulk_delete(
+ ids=[
+ 'memory_id_1',
+ 'memory_id_2',
+ 'memory_id_3',
+ 'non_existent_id' # This will be reported in errors
+ ]
+)
+
+print(f'Bulk delete result: {result}')
+# Output: {
+# 'success': True,
+# 'deletedCount': 3,
+# 'errors': [
+# {'id': 'non_existent_id', 'error': 'Memory not found'}
+# ]
+# }
+```
+
+```bash cURL
+curl -X DELETE "https://api.supermemory.ai/v3/documents/bulk" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "ids": [
+ "memory_id_1",
+ "memory_id_2",
+ "memory_id_3",
+ "non_existent_id"
+ ]
+ }'
+
+# Response: {
+# "success": true,
+# "deletedCount": 3,
+# "errors": [
+# {"id": "non_existent_id", "error": "Memory not found"}
+# ]
+# }
+```
+
+</CodeGroup>
+
+## Bulk Delete by Container Tags
+
+Delete all memories within specific container tags. This is useful for cleaning up entire projects or user data.
+
+<CodeGroup>
+
+```typescript Typescript
+// Delete all memories in specific container tags
+const result = await client.memories.bulkDelete({
+ containerTags: ['user-123', 'project-old', 'archived-content']
+});
+
+console.log('Bulk delete by tags result:', result);
+// Output: {
+// success: true,
+// deletedCount: 45,
+// containerTags: ["user-123", "project-old", "archived-content"]
+// }
+```
+
+```python Python
+# Delete all memories in specific container tags
+result = client.memories.bulk_delete(
+ container_tags=['user-123', 'project-old', 'archived-content']
+)
+
+print(f'Bulk delete by tags result: {result}')
+# Output: {
+# 'success': True,
+# 'deletedCount': 45,
+# 'containerTags': ['user-123', 'project-old', 'archived-content']
+# }
+```
+
+```bash cURL
+curl -X DELETE "https://api.supermemory.ai/v3/documents/bulk" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "containerTags": ["user-123", "project-old", "archived-content"]
+ }'
+
+# Response: {
+# "success": true,
+# "deletedCount": 45,
+# "containerTags": ["user-123", "project-old", "archived-content"]
+# }
+```
+
+</CodeGroup>
+
+## Advanced Patterns
+
+### Soft Delete Implementation
+
+For applications requiring audit trails or recovery mechanisms, implement soft delete patterns using metadata:
+
+<CodeGroup>
+
+```typescript Typescript
+// Soft delete pattern using metadata
+await client.memories.update('memory_id', {
+ metadata: {
+ deleted: true,
+ deletedAt: new Date().toISOString(),
+ deletedBy: 'user_123'
+ }
+});
+
+// Filter out deleted memories in searches
+const activeMemories = await client.memories.list({
+ filters: JSON.stringify({
+ AND: [
+ { key: "deleted", value: "true", negate: true }
+ ]
+ })
+});
+
+console.log('Active memories:', activeMemories.results.length);
+```
+
+```python Python
+from datetime import datetime
+import json
+
+# Soft delete pattern using metadata
+client.memories.update('memory_id', {
+ 'metadata': {
+ 'deleted': True,
+ 'deletedAt': datetime.now().isoformat(),
+ 'deletedBy': 'user_123'
+ }
+})
+
+# Filter out deleted memories
+active_memories = client.memories.list(
+ filters=json.dumps({
+ "AND": [
+ {"key": "deleted", "value": "true", "negate": True}
+ ]
+ })
+)
+
+print(f'Active memories: {len(active_memories.results)}')
+```
+
+```bash cURL
+# Soft delete using metadata
+curl -X PATCH "https://api.supermemory.ai/v3/documents/memory_id" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "metadata": {
+ "deleted": true,
+ "deletedAt": "2024-01-15T10:30:00Z",
+ "deletedBy": "user_123"
+ }
+ }'
+
+# Response: {"id": "memory_id", "status": "queued"}
+```
+
+</CodeGroup>
+
+### Batch Processing for Large Operations
+
+<CodeGroup>
+
+```typescript Typescript
+// Batch delete large numbers of memories safely
+async function batchDeleteMemories(memoryIds: string[], batchSize = 100) {
+ const results = [];
+
+ for (let i = 0; i < memoryIds.length; i += batchSize) {
+ const batch = memoryIds.slice(i, i + batchSize);
+
+ console.log(`Processing batch ${Math.floor(i/batchSize) + 1} of ${Math.ceil(memoryIds.length/batchSize)}`);
+
+ try {
+ const result = await client.memories.bulkDelete({ ids: batch });
+ results.push(result);
+
+ // Brief delay between batches to avoid rate limiting
+ if (i + batchSize < memoryIds.length) {
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ }
+ } catch (error) {
+ console.error(`Batch ${Math.floor(i/batchSize) + 1} failed:`, error);
+ results.push({ success: false, error: error.message, batch });
+ }
+ }
+
+ // Aggregate results
+ const totalDeleted = results
+ .filter(r => r.success)
+ .reduce((sum, r) => sum + (r.deletedCount || 0), 0);
+
+ console.log(`Total deleted: ${totalDeleted} out of ${memoryIds.length}`);
+ return { totalDeleted, results };
+}
+```
+
+```python Python
+import time
+import math
+
+def batch_delete_memories(memory_ids, batch_size=100):
+ """Batch delete large numbers of memories safely"""
+ results = []
+
+ for i in range(0, len(memory_ids), batch_size):
+ batch = memory_ids[i:i + batch_size]
+ batch_num = i // batch_size + 1
+ total_batches = math.ceil(len(memory_ids) / batch_size)
+
+ print(f'Processing batch {batch_num} of {total_batches}')
+
+ try:
+ result = client.memories.bulk_delete(ids=batch)
+ results.append(result)
+
+ # Brief delay between batches to avoid rate limiting
+ if i + batch_size < len(memory_ids):
+ time.sleep(1)
+ except Exception as error:
+ print(f'Batch {batch_num} failed: {error}')
+ results.append({'success': False, 'error': str(error), 'batch': batch})
+
+ # Aggregate results
+ total_deleted = sum(
+ r.get('deletedCount', 0) for r in results if r.get('success')
+ )
+
+ print(f'Total deleted: {total_deleted} out of {len(memory_ids)}')
+ return {'totalDeleted': total_deleted, 'results': results}
+```
+
+```bash cURL
+# Batch processing script example
+#!/bin/bash
+
+MEMORY_IDS=("id1" "id2" "id3") # Your memory IDs array
+BATCH_SIZE=100
+TOTAL_DELETED=0
+
+# Process in batches
+for ((i=0; i<${#MEMORY_IDS[@]}; i+=BATCH_SIZE)); do
+ batch=("${MEMORY_IDS[@]:i:BATCH_SIZE}")
+ batch_json=$(printf '%s\n' "${batch[@]}" | jq -R . | jq -s .)
+
+ echo "Processing batch $((i/BATCH_SIZE + 1))"
+
+ response=$(curl -s -X DELETE \
+ "https://api.supermemory.ai/v3/documents/bulk" \
+ -H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d "{\"ids\": $batch_json}")
+
+ deleted_count=$(echo "$response" | jq -r '.deletedCount // 0')
+ TOTAL_DELETED=$((TOTAL_DELETED + deleted_count))
+
+ echo "Batch deleted: $deleted_count memories"
+ sleep 1 # Rate limiting protection
+done
+
+echo "Total deleted: $TOTAL_DELETED memories"
+```
+
+</CodeGroup>
+
+## Best Practices
+
+### Update Operations
+
+1. **Use customId for idempotent updates** - Prevents duplicate memories and enables safe retries
+2. **Monitor processing status** - Updates trigger full reprocessing pipeline
+3. **Handle metadata carefully** - Updates replace specified metadata keys
+4. **Implement proper error handling** - Memory may be deleted between operations
+
+### Delete Operations
+
+1. **Hard delete is permanent** - No recovery mechanism exists
+2. **Use bulk operations efficiently** - Maximum 100 IDs per bulk delete request
+3. **Consider soft delete patterns** - Use metadata flags for recoverable deletion
+4. **Batch large operations** - Avoid rate limits with proper batching
+5. **Clean up application state** - Update your UI/cache after deletions