How to Add Memory to a Vercel AI SDK Agent with Redis
streamText and generateText in Vercel AI SDK only process the messages you send to them. If a user tells the agent that "I'm vegetarian" in an earlier conversation, the agent won't be able to recall that because each request to the AI SDK models is independent.
Upstash AgentKit includes an AI SDK memory provider, createAgentMemory(), which is used to provide an agent with long-term memory via semantic search. AgentKit uses Upstash Redis to compute embeddings for facts about each user, find relevant facts, and inject those facts into the prompt on each call, without any need to run an embedding model, vector database, or separate memory service.
What you get:
- Semantic search. "dietary restrictions" finds "The user is vegetarian." even though they share no words. Recall matches by meaning and by keyword.
- Automatic recall. Before each call, the facts that match the new message go into the prompt, with no tool call needed.
- Facts saved for you. The model stores lasting facts with a
save_memorytool as the user mentions them, so you write no extraction code. - Memory per user. Every fact is keyed by the
userIdyour route already gets from auth. - A few lines in your route. It works with
generateText,streamTextandToolLoopAgent, without wrapping your model. - Chat history in the same database.
createChatHistorystores each conversation next to the memories.
Below, we’ll use these two pieces to build a Next.js chat route, and demonstrate how a second conversation remembers a previous conversation.
What memory does an AI SDK agent need?
An AI SDK agent needs two kinds of external memory: both chat history to load when the user reloads the page, and long-term memory to load into each conversation with facts about the user. These live outside the model, and are loaded by your route before each call.
The two kinds behave differently:
| Chat history | Long-term memory | |
|---|---|---|
| Scope | One conversation (chatId) | One user, across all conversations |
| What gets stored | Every message, in order | Short facts ("The user is vegetarian.") |
| Who writes it | Your route, after each response | The model, through a tool call |
| How it's read | Load the whole transcript into useChat | A search for the facts that match the new message, added to the prompt |
Redis is great for both because it's fast enough to read on every turn, and one database holds the transcripts, the memories, and the search index over them.
Set up the project
AgentKit's AI SDK adapter gives you ready-made helpers for both kinds of memory. Install it with the AI SDK and a model provider:
npm install @upstash/agentkit-ai-sdk @upstash/redis ai @ai-sdk/anthropicCreate a Redis database in the Upstash Console and copy its REST URL and token into your environment. AgentKit reads them with Redis.fromEnv(), so there's nothing else to configure:
UPSTASH_REDIS_REST_URL="https://..."
UPSTASH_REDIS_REST_TOKEN="..."Store chat history
createChatHistory saves each conversation as one JSON document in Redis, keyed by user and chat ID. The chat route saves the full transcript when the stream finishes, and adds long-term memory to the same call:
// app/api/chat/route.ts
import { anthropic } from "@ai-sdk/anthropic";
import { createAgentMemory, createChatHistory } from "@upstash/agentkit-ai-sdk";
import {
convertToModelMessages,
createUIMessageStreamResponse,
isStepCount,
streamText,
toUIMessageStream,
type UIMessage,
} from "ai";
declare function getSessionUserId(req: Request): Promise<string>; // your auth provider
const history = createChatHistory();
const memory = createAgentMemory();
export async function POST(req: Request) {
const userId = await getSessionUserId(req);
const { id: chatId, messages } = (await req.json()) as { id: string; messages: UIMessage[] };
const result = streamText({
model: anthropic("claude-haiku-5-5"),
system: "You are a helpful assistant.\n\n" + memory.instructions,
messages: await convertToModelMessages(messages),
tools: memory.tools({ userId }),
prepareStep: memory.prepareStep({ userId }),
stopWhen: isStepCount(5),
});
return createUIMessageStreamResponse({
stream: toUIMessageStream({
stream: result.stream,
originalMessages: messages,
onFinish: async ({ messages }) => {
await history.saveChat({ userId, sessionId: chatId, messages });
},
}),
});
}saveChat replaces the whole message array each time, which matches how useChat works: the client posts the full conversation on every request. To restore a chat after a reload, load it on the server and pass it to useChat:
const chat = await history.getChat({ userId, sessionId: chatId });
// client: useChat({ id: chatId, messages: chat?.messages ?? [] })Only userId distinguishes one user's data from another's. Retrieve it from your auth session (Clerk, Auth.js, Supabase Auth) – not the request body.
The same helper lists chats for the sidebar (listChats) and implements full-text search across them (searchChats).
Give the agent long-term memory
createAgentMemory() follows the shape of the AI SDK memory providers: create it once, then hand each request three things:
memory.tools({ userId })gives the modelsave_memory, to store a lasting fact about the user, andrecall_memory, to search for more facts mid-conversation.memory.prepareStep({ userId })searches the user's memories with the latest user message before the first step and adds the best matches to the instructions. The model is never wrapped, so this works withgenerateText,streamTextandToolLoopAgent.memory.instructionsis a short prompt that tells the model when to use the tools.
A failed recall never fails the call: it goes to an onError callback, which logs a warning by default.
We ran two separate conversations for the same user. The first one shares two facts, and the second one asks a question that needs them:
import { anthropic } from "@ai-sdk/anthropic";
import { createAgentMemory } from "@upstash/agentkit-ai-sdk";
import { generateText, isStepCount } from "ai";
const memory = createAgentMemory();
const userId = "user-45";
async function ask(prompt: string) {
const { text } = await generateText({
model: anthropic("claude-haiku-5-5"),
system: memory.instructions,
tools: memory.tools({ userId }),
prepareStep: memory.prepareStep({ userId }),
stopWhen: isStepCount(5),
prompt,
});
console.log(`> ${prompt}\n${text}\n`);
}
await ask("I'm vegetarian and I live in Lisbon.");
await memory.store.searchIndex.waitIndexing(); // make the new facts searchable now
await ask("Suggest a dinner place for me tonight.");The output, trimmed:
> I'm vegetarian and I live in Lisbon.
Thanks, I've noted that you're vegetarian and live in Lisbon. I'll keep that in mind for restaurant suggestions, recipes, or anything else where it matters.
> Suggest a dinner place for me tonight.
Since you're vegetarian and based in Lisbon, here are two good options to check out tonight:
- **Cantinho Vegetariano**: a long-standing fully vegetarian restaurant in the city centre...In an earlier run, we logged what prepareStep added to the instructions before the second conversation:
<memories>
...
- The user is vegetarian.
- The user lives in Lisbon.
</memories>Memories are JSON documents stored at agentkit:memory:<userId>:<id>, and you can see them in the Upstash Console Data Browser.
Note that no mention of diet or location was made in the second conversation. These were already in the prompt when the model responded.
If you want the model to decide on its own when to look things up, createMemoryTools({ userId }) gives it the two tools without the automatic recall.
How recall finds the right memories
When you add a memory, Upstash Redis auto-converts it to a text embedding, meaning your app only needs to send text, not use embedding models. Recall then does a "hybrid search" on your Upstash Redis Search, combining semantic (by meaning) and keyword (BM25, a common text relevance metric, with typo tolerance) to rank.
We searched the two saved facts for "dietary restrictions", which shares no words with either of them. memory.store is the underlying AgentMemory, and the second store sets minScore to search by keyword only:
import { createAgentMemory } from "@upstash/agentkit-ai-sdk";
import { AgentMemory } from "@upstash/agentkit-sdk";
import { Redis } from "@upstash/redis";
const userId = "user-45";
const memory = createAgentMemory();
const keywordOnly = new AgentMemory({ redis: Redis.fromEnv(), minScore: 0.1 });
console.log(await memory.store.recall({ userId, query: "dietary restrictions", topK: 3 }));
console.log(await keywordOnly.recall({ userId, query: "dietary restrictions", topK: 3 }));The hybrid search returned "The user is vegetarian." first, followed by "The user lives in Lisbon.". The keyword-only search returned nothing.
Because hybrid search works by ranking results rather than filtering them, recall will return up to topK memories (defaulting to 5) for any message. This includes weak results, such as Lisbon in this case. You can optionally set minScore to revert to keyword matches exceeding that BM25 score.
Putting it together
For most AI SDK apps, this setup is all you need: createChatHistory keeps each conversation, and createAgentMemory saves what the model learns about the user and adds the relevant facts to every new conversation. The AgentKit docs have the full API reference, and the AgentKit repo contains a complete Next.js app with chat sidebar example.
Everything lives in your own Upstash Redis database as plain JSON documents at known keys, so you can read, change, and delete a user's memory yourself. With default settings, chat history and memory share one search index, so both work on the free plan. AgentKit works in edge runtimes as well as Node.js, and the same package adds RAG search tools, rate limiting, and tool caching to the agent.