supermemory/apps/docs/integrations/ai-sdk.mdx
MaheshtheDev ca829b04ff fix(tools): send only memories an earlier block does not already carry
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-11-26 07:14:57 +00:00

253 lines
8 KiB
Text

---
title: "Vercel AI SDK"
sidebarTitle: "Vercel AI SDK"
description: "Use Supermemory with Vercel AI SDK for seamless memory management"
icon: "/icons/hugeicons/triangle.svg"
---
import MigrateCli from "/snippets/migrate-cli.mdx";
The Supermemory AI SDK provides native integration with Vercel's AI SDK through two approaches: **User Profiles** for automatic personalization and **Memory Tools** for agent-based interactions.
<MigrateCli legacy="@supermemory/tools 2.x" guideHref="/migration/tools-v3-upgrade" guideLabel="3.0 upgrade guide" />
<Card title="@supermemory/tools on npm" icon="/icons/hugeicons/package.svg" href="https://www.npmjs.com/package/@supermemory/tools">
Check out the NPM page for more details
</Card>
## Installation
```bash
npm install @supermemory/tools
```
## Quick comparison
| Approach | Use Case | Setup |
|----------|----------|-------|
| User Profiles | Personalized LLM responses with automatic user context | Simple middleware |
| Memory Tools | AI agents that need explicit memory control | Tool definitions |
---
## User profiles with middleware
Load the user profile once and reuse the same snapshot throughout the conversation.
```typescript
import { generateText } from "ai"
import { withSupermemory } from "@supermemory/tools/ai-sdk"
import { openai } from "@ai-sdk/openai"
const modelWithMemory = withSupermemory(openai("gpt-5"), {
namespace: "user-123",
id: "conversation-456",
})
const result = await generateText({
model: modelWithMemory,
messages: [{ role: "user", content: "What do you know about me?" }]
})
```
### Prompt caching
Your system prompt, your messages and your cache breakpoints are never changed. On
each user turn the wrapper makes one recall (the profile and search results, per
`mode`) and sends it as a separate user message after your latest user message.
Memories already shown in an earlier restored block are left out, so a turn that
recalls nothing new sends no block at all.
The reply's first text or tool-call part carries that block, signed, in
`providerMetadata.supermemory`. Save the whole UI message (the default `useChat` and
`onFinish` flow) and build the next request with `convertToModelMessages`: the
wrapper puts each block back in front of its reply, so earlier turns are resent byte
for byte. Tool steps reuse the block without a new request.
The wrapper holds nothing between calls, so a new wrapper per request or per server
instance is fine. The signature is an HMAC keyed by your Supermemory API key, so a
block edited or invented on the client is ignored. If your app stores only message
text, nothing is restored and each call just gets a fresh recall after the latest
user message, which still caches well with an explicit cache breakpoint on your last
message but not with Anthropic's automatic caching.
If retrieval fails or times out, the call continues without it by default. Provider
cache eligibility and minimum token counts still apply, so cache-hit savings are not
guaranteed.
### Required fields
Both `namespace` and `id` are required.
- **`namespace`** — *who* the memories belong to. Use a stable identifier per user, workspace, or tenant (e.g. `"user-123"`, `"acme-workspace"`). Memory search and writes are scoped to this tag.
- **`id`** — *which conversation* this turn belongs to. Use it to group messages from the same chat session into a single document (e.g. `"chat-2026-04-25"`, a thread ID, or a UUID per session).
<Note>
**Memory saving is enabled by default** (`addMemory: "always"`). New conversations are persisted automatically. To opt out, set `addMemory: "never"`:
```typescript
const modelWithMemory = withSupermemory(openai("gpt-5"), {
namespace: "user-123",
id: "conversation-456",
addMemory: "never",
})
```
</Note>
### Memory search modes
**Profile Mode (Default)** - Retrieves the user's complete profile:
```typescript
const model = withSupermemory(openai("gpt-4"), { namespace: "user-123", id: "conv-1", mode: "profile" })
```
**Query Mode** - Searches memories based on the user's message:
```typescript
const model = withSupermemory(openai("gpt-4"), { namespace: "user-123", id: "conv-1", mode: "query" })
```
**Full Mode** - Combines profile AND query-based search:
```typescript
const model = withSupermemory(openai("gpt-4"), { namespace: "user-123", id: "conv-1", mode: "full" })
```
### Custom prompt templates
Customize how memories are formatted. The template receives `userMemories`, `generalSearchMemories`, and `searchResults` (raw array for filtering by metadata):
```typescript
import { withSupermemory, type MemoryPromptData } from "@supermemory/tools/ai-sdk"
const claudePrompt = (data: MemoryPromptData) => `
<context>
<user_profile>
${data.userMemories}
</user_profile>
<relevant_memories>
${data.generalSearchMemories}
</relevant_memories>
</context>
`.trim()
const model = withSupermemory(anthropic("claude-3-sonnet"), {
namespace: "user-123",
id: "conv-1",
mode: "full",
promptTemplate: claudePrompt,
})
```
### Verbose logging
```typescript
const model = withSupermemory(openai("gpt-4"), {
namespace: "user-123",
id: "conv-1",
verbose: true,
})
// Console output shows memory retrieval details
```
### When Supermemory errors (default: continue without memories)
If the Supermemory API returns an error, is unreachable, or retrieval hits the internal time limit, memory injection is skipped. **`skipMemoryOnError` defaults to `true`**, so the LLM call still runs with the **original** prompt (no injected memories). Use `verbose: true` if you want console output when that happens.
To **fail the call** when memory retrieval fails instead, set `skipMemoryOnError: false`:
```typescript
const model = withSupermemory(openai("gpt-5"), {
namespace: "user-123",
id: "conv-1",
skipMemoryOnError: false,
})
```
### Persisting tool calls (default: off)
By default, saved conversations include only user and assistant text — tool calls and tool results are dropped, since tool payloads are often large and low-signal and would pollute memory extraction. To persist the full tool round trip (tool calls with their arguments, plus tool results, in their original order), set `includeToolCalls: true`:
```typescript
const model = withSupermemory(openai("gpt-5"), {
namespace: "user-123",
id: "conv-1",
includeToolCalls: true,
})
```
---
## Memory tools
Add memory capabilities to AI agents. `supermemoryTools` returns seven tools: `searchMemories`, `addMemory`, `getProfile`, `documentList`, `documentAdd`, `documentDelete`, and `memoryForget`.
```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")
})
```
### Available tools
**Search Memories** - Semantic search through user memories:
```typescript
const result = await streamText({
model: openai("gpt-5"),
prompt: "What are my dietary preferences?",
tools: supermemoryTools("API_KEY")
})
// AI will call: searchMemories({ informationToGet: "dietary preferences" })
```
**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")
})
// AI will call: addMemory({ memory: "User is allergic to peanuts" })
```
### Using individual tools
For more control, import tools separately:
```typescript
import {
searchMemoriesTool,
addMemoryTool
} from "@supermemory/tools/ai-sdk"
const result = await streamText({
model: openai("gpt-5"),
prompt: "What do you know about me?",
tools: {
searchMemories: searchMemoriesTool("API_KEY", { namespace: "personal" }),
createEvent: yourCustomTool,
}
})
```
### Tool results
```typescript
// searchMemories result
{ success: true, results: [...], count: 5 }
// addMemory result
{ success: true, memory: { id: "doc_123", status: "queued" } }
```