migrate docs to public
84
apps/docs/.cursor/rules/docs.mdc
Normal file
|
|
@ -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
|
||||
34
apps/docs/.gitignore
vendored
Normal file
|
|
@ -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
|
||||
1
apps/docs/README.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
# supermemory Docs
|
||||
278
apps/docs/add-memories/examples/basic.mdx
Normal file
|
|
@ -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>
|
||||
195
apps/docs/add-memories/examples/file-upload.mdx
Normal file
|
|
@ -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 "file=@document.pdf" \
|
||||
-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 "file=@screenshot.png" \
|
||||
-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 "file=@document.pdf" \
|
||||
-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
|
||||
210
apps/docs/add-memories/overview.mdx
Normal file
|
|
@ -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 "file=@document.pdf" \
|
||||
-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
|
||||
156
apps/docs/add-memories/parameters.mdx
Normal file
|
|
@ -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 "file=@document.pdf" \
|
||||
-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"] }
|
||||
```
|
||||
426
apps/docs/ai-sdk/examples.mdx
Normal file
|
|
@ -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>
|
||||
216
apps/docs/ai-sdk/infinite-chat.mdx
Normal file
|
|
@ -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>
|
||||
147
apps/docs/ai-sdk/memory-tools.mdx
Normal file
|
|
@ -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>
|
||||
5
apps/docs/ai-sdk/npm.mdx
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
title: "NPM link"
|
||||
url: "https://www.npmjs.com/package/@supermemory/tools"
|
||||
icon: npm
|
||||
---
|
||||
80
apps/docs/ai-sdk/overview.mdx
Normal file
|
|
@ -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>
|
||||
300
apps/docs/analytics.mdx
Normal file
|
|
@ -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
|
||||
74
apps/docs/changelog/developer-platform.mdx
Normal file
|
|
@ -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
|
||||
34
apps/docs/changelog/overview.mdx
Normal file
|
|
@ -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>
|
||||
435
apps/docs/connectors/google-drive.mdx
Normal file
|
|
@ -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": "user@example.com",
|
||||
# "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>
|
||||
429
apps/docs/connectors/notion.mdx
Normal file
|
|
@ -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": "workspace@example.com",
|
||||
# "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 | `` |
|
||||
| **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>
|
||||
390
apps/docs/connectors/onedrive.mdx
Normal file
|
|
@ -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>
|
||||
306
apps/docs/connectors/overview.mdx
Normal file
|
|
@ -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": "user@example.com", ...}]
|
||||
|
||||
# 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: user@company.com (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": "user@company.com",
|
||||
# "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>
|
||||
190
apps/docs/connectors/troubleshooting.mdx
Normal file
|
|
@ -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
|
||||
424
apps/docs/cookbook/ai-sdk-integration.mdx
Normal file
|
|
@ -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>
|
||||
4
apps/docs/cookbook/chat-with-gdrive.mdx
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
title: "Chat with Google Drive"
|
||||
url: "https://supermemory.ai/blog/building-an-ai-compliance-chatbot-with-supermemory-and-google-drive/"
|
||||
---
|
||||
1047
apps/docs/cookbook/customer-support.mdx
Normal file
883
apps/docs/cookbook/document-qa.mdx
Normal file
|
|
@ -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.*
|
||||
4
apps/docs/cookbook/inf-chat-blog.mdx
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
title: "Extending context windows in LLMs"
|
||||
url: "https://supermemory.ai/blog/extending-context-windows-in-llms/"
|
||||
---
|
||||
64
apps/docs/cookbook/overview.mdx
Normal file
|
|
@ -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:dhravya@supermemory.com)
|
||||
|
||||
<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:dhravya@supermemory.com) for help
|
||||
|
||||
## Contributing Recipes
|
||||
|
||||
Have a great Supermemory use case? We'd love to add it to the cookbook!
|
||||
|
||||
[Suggest a recipe →](mailto:dhravya@supermemory.com?subject=Cookbook%20Recipe%20Suggestion)
|
||||
4
apps/docs/cookbook/perplexity-supermemory.mdx
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
title: "Perplexity with memory"
|
||||
url: "https://supermemory.ai/blog/build-your-own-perplexity-in-15-minutes-with-supermemory/"
|
||||
---
|
||||
770
apps/docs/cookbook/personal-assistant.mdx
Normal file
|
|
@ -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.*
|
||||
243
apps/docs/deployment/self-hosting.mdx
Normal file
|
|
@ -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.
|
||||
|
||||
---
|
||||
260
apps/docs/docs.json
Normal file
|
|
@ -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:dhravya@supermemory.com",
|
||||
"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"
|
||||
}
|
||||
BIN
apps/docs/favicon.png
Normal file
|
After Width: | Height: | Size: 616 B |
152
apps/docs/how-it-works.mdx
Normal file
|
|
@ -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.
|
||||
|
||||

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

|
||||
|
||||
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>
|
||||
BIN
apps/docs/images/Screenshot 2025-06-19 at 3.50.20 PM.png
Normal file
|
After Width: | Height: | Size: 226 KiB |
BIN
apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (2).png
Normal file
|
After Width: | Height: | Size: 412 KiB |
BIN
apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM (3).png
Normal file
|
After Width: | Height: | Size: 330 KiB |
BIN
apps/docs/images/Screenshot 2025-07-05 at 7.16.18 PM.png
Normal file
|
After Width: | Height: | Size: 855 KiB |
BIN
apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (2).png
Normal file
|
After Width: | Height: | Size: 412 KiB |
BIN
apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM (3).png
Normal file
|
After Width: | Height: | Size: 330 KiB |
BIN
apps/docs/images/Screenshot 2025-07-05 at 7.16.22 PM.png
Normal file
|
After Width: | Height: | Size: 909 KiB |
BIN
apps/docs/images/connectors-flow.png
Normal file
|
After Width: | Height: | Size: 239 KiB |
BIN
apps/docs/images/create-api.png
Normal file
|
After Width: | Height: | Size: 164 KiB |
BIN
apps/docs/images/dev-platform-api-keys.png
Normal file
|
After Width: | Height: | Size: 238 KiB |
BIN
apps/docs/images/dev-platform-copy-key.png
Normal file
|
After Width: | Height: | Size: 303 KiB |
BIN
apps/docs/images/dev-platform-create-key.png
Normal file
|
After Width: | Height: | Size: 260 KiB |
BIN
apps/docs/images/dev-platform-login.png
Normal file
|
After Width: | Height: | Size: 569 KiB |
BIN
apps/docs/images/doc-to-memory-process.png
Normal file
|
After Width: | Height: | Size: 263 KiB |
BIN
apps/docs/images/graph-view.png
Normal file
|
After Width: | Height: | Size: 474 KiB |
32
apps/docs/images/hero-dark.svg
Normal file
|
After Width: | Height: | Size: 13 KiB |
32
apps/docs/images/hero-light.svg
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
apps/docs/images/infinite-context.png
Normal file
|
After Width: | Height: | Size: 163 KiB |
BIN
apps/docs/images/memories-inferred.png
Normal file
|
After Width: | Height: | Size: 3 MiB |
BIN
apps/docs/images/opts/Connectors.png
Normal file
|
After Width: | Height: | Size: 4 MiB |
BIN
apps/docs/images/opts/Memory_API.png
Normal file
|
After Width: | Height: | Size: 4 MiB |
BIN
apps/docs/images/opts/Model_Enhancer.png
Normal file
|
After Width: | Height: | Size: 4 MiB |
BIN
apps/docs/images/opts/Supermemory_MCP.png
Normal file
|
After Width: | Height: | Size: 4.1 MiB |
BIN
apps/docs/images/overview-image.png
Normal file
|
After Width: | Height: | Size: 5.1 MiB |
BIN
apps/docs/images/pipeline.png
Normal file
|
After Width: | Height: | Size: 6.3 MiB |
BIN
apps/docs/images/process.png
Normal file
|
After Width: | Height: | Size: 6.2 MiB |
BIN
apps/docs/images/processing.png
Normal file
|
After Width: | Height: | Size: 182 KiB |
BIN
apps/docs/images/query-rewriting.png
Normal file
|
After Width: | Height: | Size: 106 KiB |
BIN
apps/docs/images/rerank.png
Normal file
|
After Width: | Height: | Size: 28 KiB |
BIN
apps/docs/images/sm-header.png
Normal file
|
After Width: | Height: | Size: 409 KiB |
BIN
apps/docs/images/transparent-proxy.png
Normal file
|
After Width: | Height: | Size: 94 KiB |
63
apps/docs/intro.mdx
Normal file
|
|
@ -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)
|
||||
|
||||

|
||||
|
||||
- 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.
|
||||
66
apps/docs/introduction.mdx
Normal file
|
|
@ -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>
|
||||
87
apps/docs/list-memories/examples/basic.mdx
Normal file
|
|
@ -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>
|
||||
508
apps/docs/list-memories/examples/filtering.mdx
Normal file
|
|
@ -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>
|
||||
118
apps/docs/list-memories/examples/monitoring.mdx
Normal file
|
|
@ -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>
|
||||
110
apps/docs/list-memories/examples/pagination.mdx
Normal file
|
|
@ -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>
|
||||
153
apps/docs/list-memories/overview.mdx
Normal file
|
|
@ -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>
|
||||
1
apps/docs/logo/dark.svg
Normal file
|
|
@ -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>
|
||||
|
After Width: | Height: | Size: 371 B |
1
apps/docs/logo/light.svg
Normal file
|
|
@ -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>
|
||||
|
After Width: | Height: | Size: 371 B |
138
apps/docs/memory-api/connectors/advanced/bring-your-own-key.mdx
Normal file
|
|
@ -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>
|
||||
85
apps/docs/memory-api/connectors/creating-connection.mdx
Normal file
|
|
@ -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.
|
||||
27
apps/docs/memory-api/connectors/google-drive.mdx
Normal file
|
|
@ -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
|
||||
26
apps/docs/memory-api/connectors/overview.mdx
Normal file
|
|
@ -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`
|
||||
|
||||

|
||||
|
||||
## 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
|
||||
376
apps/docs/memory-api/creation/adding-memories.mdx
Normal file
|
|
@ -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)
|
||||
14
apps/docs/memory-api/creation/status.mdx
Normal file
|
|
@ -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
|
||||
181
apps/docs/memory-api/features/auto-multi-modal.mdx
Normal file
|
|
@ -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 |
|
||||
86
apps/docs/memory-api/features/content-cleaner.mdx
Normal file
|
|
@ -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.
|
||||
297
apps/docs/memory-api/features/filtering.mdx
Normal file
|
|
@ -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>
|
||||
50
apps/docs/memory-api/features/query-rewriting.mdx
Normal file
|
|
@ -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.
|
||||
|
||||

|
||||
|
||||
### 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.
|
||||
44
apps/docs/memory-api/features/reranking.mdx
Normal file
|
|
@ -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.
|
||||
|
||||

|
||||
|
||||
### 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.
|
||||
861
apps/docs/memory-api/ingesting.mdx
Normal file
|
|
@ -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 "file=@document.pdf" \
|
||||
-F "containerTags=research_project"
|
||||
|
||||
# Response:
|
||||
# {
|
||||
# "id": "Mx7fK9pL2qR5tE8yU4nC7",
|
||||
# "status": "processing"
|
||||
# }
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import Supermemory from 'supermemory'
|
||||
import fs from 'fs'
|
||||
|
||||
const client = new Supermemory({
|
||||
apiKey: process.env.SUPERMEMORY_API_KEY
|
||||
})
|
||||
|
||||
// Method 1: Using SDK uploadFile method (RECOMMENDED)
|
||||
const result = await client.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>
|
||||
43
apps/docs/memory-api/introduction.mdx
Normal file
|
|
@ -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>
|
||||
|
||||

|
||||
|
||||
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>
|
||||
162
apps/docs/memory-api/overview.mdx
Normal file
|
|
@ -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>
|
||||
68
apps/docs/memory-api/sdks/native.mdx
Normal file
|
|
@ -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();
|
||||
```
|
||||
584
apps/docs/memory-api/sdks/openai-plugins.mdx
Normal file
|
|
@ -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>
|
||||
24
apps/docs/memory-api/sdks/overview.mdx
Normal file
|
|
@ -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:dhravya@supermemory.com">
|
||||
We will add support for your favorite SDKs asap.
|
||||
</Card>
|
||||
</Columns>
|
||||
349
apps/docs/memory-api/sdks/python.mdx
Normal file
|
|
@ -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.
|
||||
5
apps/docs/memory-api/sdks/supermemory-npm.mdx
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
title: "`supermemory` on npm"
|
||||
url: "https://www.npmjs.com/package/supermemory"
|
||||
icon: npm
|
||||
---
|
||||
5
apps/docs/memory-api/sdks/supermemory-pypi.mdx
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
title: "`supermemory` on pypi"
|
||||
url: "https://pypi.org/project/supermemory/"
|
||||
icon: python
|
||||
---
|
||||
391
apps/docs/memory-api/sdks/typescript.mdx
Normal file
|
|
@ -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.
|
||||
181
apps/docs/memory-api/searching/searching-memories.mdx
Normal file
|
|
@ -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).
|
||||
274
apps/docs/memory-api/track-progress.mdx
Normal file
|
|
@ -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
|
||||
|
||||

|
||||
|
||||
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>
|
||||
158
apps/docs/memory-router/overview.mdx
Normal file
|
|
@ -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
|
||||
214
apps/docs/memory-router/usage.mdx
Normal file
|
|
@ -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"}
|
||||
)
|
||||
```
|
||||
113
apps/docs/memory-router/with-memory-api.mdx
Normal file
|
|
@ -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 |
|
||||
233
apps/docs/model-enhancement/context-extender.mdx
Normal file
|
|
@ -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>
|
||||
99
apps/docs/model-enhancement/getting-started.mdx
Normal file
|
|
@ -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>
|
||||