How to Use Supermemory with AI SDK
Add persistent user context to an AI SDK application, then test continuity, isolation, corrections, and retrieval failures.

Add persistent memory to an AI SDK application by using a stable memory scope across conversations, a separate identifier for each conversation, and an explicit policy for what gets saved. Supermemory's middleware can retrieve user context before generation and save conversation text afterward. Your application still owns authentication, chat-history storage, and the decisions that require authoritative business data.
This guide uses the middleware path. Start there when every request should receive relevant memory; use individual memory tools when the agent needs to choose specific memory operations.
What persists between AI SDK conversations?
Your application stores the chat messages needed to reopen a conversation. Supermemory stores and retrieves selected context that can be useful in other conversations. Keep a stable, authorized containerTag for the user or workspace and a distinct customId for each conversation. Reusing the conversation ID as the user scope prevents the intended continuity when a new chat starts.
This example adds memory to an application built with AI SDK. It does not configure memory in the consumer ChatGPT or Claude apps. Start with the user-preference example for the behavior to test and the isolation guide for shared applications.
Install the integration package
npm install ai@6.0.285 @ai-sdk/openai@3.0.113 @supermemory/tools@2.3.0
Keep model-provider and Supermemory credentials on the server. Configure OPENAI_API_KEY and SUPERMEMORY_API_KEY in your runtime's secret settings. Installing the supermemory client alone does not install the @supermemory/tools/ai-sdk integration imported below.
The official integration documentation describes the middleware and tools separately. Use the compatible package versions in the install command for this example. The current AI SDK 7 model interface is not accepted by this integration version; do not upgrade that combination without checking compatibility.
Wrap the model for one authorized conversation
The following helper belongs in server-side code. memoryScope and conversationId must come from application logic that has already authenticated the request and checked access to the conversation.
import { generateText, type ModelMessage } from "ai";
import { openai } from "@ai-sdk/openai";
import { withSupermemory } from "@supermemory/tools/ai-sdk";
export async function answerWithMemory(input: {
memoryScope: string;
conversationId: string;
messages: ModelMessage[];
}) {
const apiKey = process.env.SUPERMEMORY_API_KEY;
if (!apiKey) throw new Error("SUPERMEMORY_API_KEY is required");
const model = withSupermemory(openai("gpt-5"), {
apiKey,
containerTag: input.memoryScope,
customId: input.conversationId,
mode: "full",
addMemory: "always",
skipMemoryOnError: false,
});
const result = await generateText({
model,
messages: input.messages,
});
return result.text;
}
The caller must supply a scope it is authorized to use. A privileged API key combined with a client-chosen scope is not a safe multi-user design.
Keep the same scope when a user starts a new conversation that should share memory. Change the conversation identifier so unrelated chats do not become one document. Check that your identifier scheme remains unambiguous across tenants.
Choose saving and failure behavior deliberately
The example enables conversation saving and combines profile context with query-based retrieval. If your workflow should retrieve without saving new conversation text, use addMemory: "never" and implement an explicit write path for approved content.
It also sets skipMemoryOnError: false. That makes a memory error fail the operation instead of silently continuing without context. An application may prefer a fallback, but that should be a product decision. A support agent should not pretend to remember an earlier ticket when retrieval failed.
Distinguish temporary retrieval failure from missing evidence. The first may justify a retry or a degraded response; the second may require a clarifying question.
Keep chat persistence and memory separate
Persist the messages needed to display or resume a conversation in your application. Retrieved memory supplies selected context from other interactions; it is not necessarily a complete transcript or an exact replay of every tool call.
Similarly, check current permissions, account state, and transactional data against their authoritative systems. A remembered subscription tier should not grant an entitlement.
The AI SDK memory guide describes memory patterns alongside the agent loop. Keep the application's existing history store when adding the memory layer.
Test across two sessions
Use synthetic data before a customer pilot:
- In conversation A, save a harmless preference such as “use concise bullet points.”
- Wait for the documented processing state rather than assuming immediate availability.
- Start conversation B with the same memory scope and a new conversation ID.
- Verify the preference is retrieved and used when relevant.
- Repeat with another user's scope and verify the preference is absent.
- Correct the preference and check both current behavior and any historical question your product supports.
Add a retrieval-outage case and a deletion case. Inspect the context sent to the model, not only the final answer.
Measure the cost of adding memory
Record retrieval latency, time to first output, total response time, and context tokens separately. A published retrieval figure does not guarantee that a stream has no additional delay.
Compare a baseline that sends your existing conversation context with the memory-enhanced version. Keep the questions and model configuration the same. If context becomes smaller, check that difficult questions still retain the evidence they need.
Use the debugging guide when a test fails. The target is reliable continuity for the same authorized user, with visible failure behavior and a cost you can measure.
Add memory to an existing TypeScript app incrementally
Keep your current chat-history store and introduce memory at one server-side generation boundary. Derive the memory scope from authenticated tenant and user identity, while retaining the application's existing conversation ID. A request body must not choose which other user's memories to retrieve.
This standalone helper makes the scope encoding unambiguous. It does not authenticate a request; call it only with trusted identifiers that have already passed your access checks.
export function memoryScope(tenantId: string, userId: string): string {
if (!tenantId.trim() || !userId.trim()) {
throw new Error("Tenant and user identifiers are required");
}
return ["tenant", encodeURIComponent(tenantId),
"user", encodeURIComponent(userId)].join(":");
}
Encoding each identifier avoids delimiter collisions, such as a tenant ID containing a colon. A workspace-wide feature needs a separately authorized workspace scope; do not silently reuse a personal scope for shared knowledge.
Start with one route and a synthetic user. Compare the assembled context and answer with the existing path, then enable the feature for a controlled cohort. Avoid saving each interaction through both middleware and a separate write hook unless you have verified their deduplication behavior. Decide how to handle timeouts and roll back the read path without losing the original conversation records.
Plan the rollout around authentication, streaming, retries, background ingestion and deletion. Use the middleware above at the generation boundary and test each surrounding application path. For the broader implementation choice, compare three ways to add long-term memory.
For other agent frameworks, follow the OpenAI Agents SDK or Mastra integration guide.
Ready to add this to your app? Get your API key in the Supermemory console and connect the middleware to one server-side route. Use a fictional user to run the two-session, correction, and deletion checks before expanding the rollout.