How to Add Memory to a TanStack AI Agent with Redis
Each call to chat() in TanStack AI sees only the messages passed to it. It has no access to previous conversations. So if the user tells the agent "I'm vegetarian" in one conversation and asks for a dinner idea in the next, the agent won't be able to know about the first conversation.
To solve this, TanStack AI 1.0 comes with withPersistence() middleware for chat history and memoryMiddleware() for long term memory. But these middlewares need a persistence store to work with. And the stores TanStack AI ships to get you started only work inside one process. In a serverless environment, requests can land on different instances, so this memory is lost on the next request.
The Upstash AgentKit TanStack AI adapter stores the state of both middlewares in Upstash Redis, and gives the agent long-term memory powered by semantic search. Upstash Redis handles the embeddings, eliminating the need for an external memory, vector database, or embedding model.
What you get:
- Semantic search. "Suggest a dinner place for me tonight." finds "The user is vegetarian." even though they share no words. Recall matches by meaning and by keyword.
- Automatic recall. Before each turn,
memoryMiddleware()adds the memories that match the new message to the system prompt. - Facts saved for you. The model stores lasting facts with a
save_memorytool, and the adapter also saves each user message, so you write no extraction code. - Memory per user. Memories are scoped to the
userIdyou pass in, across all of that user's threads. - Drop-in adapters.
upstashMemory()andupstashPersistence()plug into TanStack AI's own middlewares, so the rest of the route stays the same. - Works on serverless. Every instance reads the same Redis database over HTTP.
Below, we wire both into a chat route, run two conversations to show the second one remembering the first, and compare the adapter with the redis() memory adapter that TanStack AI ships.
What memory does a TanStack AI agent need?
TanStack AI agents use two kinds of external memory (memory that's stored outside the model's memory):
- Chat history: When the user reloads, we want to load the chat thread.
- Long-term memory: When the user starts a new chat thread, we want to load some facts we know about them.
Middleware loads both on the server before each call to the model.
The two kinds work differently:
| Chat history | Long-term memory | |
|---|---|---|
| Scope | One thread (threadId) | One user, across all threads |
| What gets stored | The full transcript, plus runs and pending approvals | Short facts and the user's own messages |
| Who writes it | withPersistence(), at the start and end of each run | The model through a save_memory tool, and the middleware after each turn |
| How it's read | The client loads the whole thread on mount | A search for the memories that match the new message |
The transcripts, memories, and the search index over them are all stored in the same Redis database, which is fast enough to read on each turn.
Set up the project
Install AgentKit's TanStack AI adapter with TanStack AI, its persistence and memory packages, and a model provider:
npm install @upstash/agentkit-tanstack-ai @tanstack/ai @tanstack/ai-persistence @tanstack/ai-memory @tanstack/ai-anthropicThe adapter needs TanStack AI 1.0 or later.
Create a Redis database in the Upstash Console and copy its REST URL and token into your environment. Every AgentKit helper reads them with Redis.fromEnv(), so there is no client to set up:
UPSTASH_REDIS_REST_URL="https://..."
UPSTASH_REDIS_REST_TOKEN="..."Store chat history
upstashPersistence() gives withPersistence() a Redis backend for the transcript of each thread, a record of each run, and pending human-in-the-loop approvals. The route below adds it next to the memory middleware, and adds a GET handler that returns a stored thread:
// app/api/chat/route.ts
import { chat, chatParamsFromRequest, toServerSentEventsResponse } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { memoryMiddleware } from "@tanstack/ai-memory";
import { reconstructChat, withPersistence } from "@tanstack/ai-persistence";
import { upstashMemory } from "@upstash/agentkit-tanstack-ai/memory";
import { upstashPersistence } from "@upstash/agentkit-tanstack-ai/persistence";
declare function getSessionUserId(req: Request): Promise<string>; // your auth provider
declare function userOwnsThread(userId: string, threadId: string): Promise<boolean>;
const persistence = upstashPersistence();
const memory = upstashMemory();
export async function POST(request: Request) {
const userId = await getSessionUserId(request);
const params = await chatParamsFromRequest(request);
if (!(await userOwnsThread(userId, params.threadId))) {
return new Response("Forbidden", { status: 403 });
}
const stream = chat({
adapter: anthropicText("claude-haiku-5-5"),
messages: params.messages,
threadId: params.threadId,
runId: params.runId,
...(params.resume ? { resume: params.resume } : {}),
middleware: [
withPersistence(persistence),
memoryMiddleware({ adapter: memory, scope: { threadId: params.threadId, userId } }),
],
});
return toServerSentEventsResponse(stream);
}
export async function GET(request: Request) {
const userId = await getSessionUserId(request);
return reconstructChat(persistence, request, {
authorize: (threadId) => userOwnsThread(userId, threadId),
});
}Note that reconstructChat is available for any request knowing the threadId — unless you pass authorize. Same goes for memory: you should use your auth session (Clerk, Auth.js, Supabase Auth) for the userId, which is the only way to separate one user’s memories from another (don’t take it from the request body).
On the client side, use useChat({ threadId, connection, persistence: true }) which calls this GET handler on mount and paints the stored thread. The above implementation forwards params.resume to enable continuing threads that were paused with a tool approval step.
upstashPersistence() also returns a session index store to facilitate listing chats per user in the sidebar (titles and members). This is documented in the AgentKit docs, or you can use the TanStack AI chat persistence tutorial to set up the client side persistence option.
Give the agent long-term memory
upstashMemory() is a memory adapter for memoryMiddleware().
For each turn, it:
- Before the model runs, it searches the user's memories by keyword and by meaning using the new user message, adding the top 5 to the system prompt.
- It gives the model access to the
save_memorytool for saving relevant facts. - After the response, it saves the user's message as a memory as well.
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 { chat, streamToText } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { memoryMiddleware } from "@tanstack/ai-memory";
import { upstashMemory } from "@upstash/agentkit-tanstack-ai/memory";
const memory = upstashMemory();
const userId = "user-45";
async function ask(threadId: string, prompt: string) {
const saved = Promise.withResolvers<void>();
const stream = chat({
adapter: anthropicText("claude-haiku-5-5"),
messages: [{ role: "user", content: prompt }],
threadId,
middleware: [
memoryMiddleware({
adapter: memory,
scope: { threadId, userId },
onRecall: ({ result }) => console.log(result.systemPrompt || "(no memories)"),
onSave: () => saved.resolve(),
}),
],
});
const { text } = await streamToText(stream);
await saved.promise; // the middleware saves after the reply
console.log(`> ${prompt}\n${text}\n`);
}
await ask("chat-1", "I'm vegetarian and I live in Lisbon.");
await ask("chat-2", "Suggest a dinner place for me tonight.");The output, trimmed:
(no memories)
> I'm vegetarian and I live in Lisbon.
Got it. I've noted that you're vegetarian and live in Lisbon, so I'll keep that in mind for food, restaurant, or travel suggestions.
Relevant long-term memory about this user:
- I'm vegetarian and I live in Lisbon. (the user said this)
- The user is vegetarian. (you saved this)
- The user lives in Lisbon, Portugal. (you saved this)
> Suggest a dinner place for me tonight.
I can't check live hours, reviews, or what's open tonight, so I'd verify any pick before heading out. A few reliable options:
...Memories are saved as a JSON document in agentkit:tanstackMemory:_._.u.<userId>:<id>. The tenant and namespace are inside the _._. In this case, those values are empty. If you use the Upstash Console, you can see the saved memory in the Data Browser.
By default, the adapter waits for the search index after each save, so each memory is available on the very next turn, with no delay between the two threads. The second thread said nothing about diet or location, yet the agent knew both.
How recall finds the right memories
The upstashMemory() API implements keyword (with typo-tolerance, using BM25: a standard text relevance scoring algorithm) and semantic-search in Upstash Redis Search. While saving memory to Upstash Redis, it converts the memory to an embedding. This means that your app can simply pass the text to it, without the need to call any embedding models. Also notice how it has retrieved "The user is vegetarian." memory for query "Suggest a dinner place for me tonight.", without sharing any words. This is semantic search.
To see the meaning half on its own, we ran the same two conversations for a second user with message capture turned off, so only the two facts the model saved were in Redis:
const memory = upstashMemory({ captureUserMessages: false });The second conversation still recalled both facts:
Relevant long-term memory about this user:
- The user is vegetarian. (you saved this)
- The user lives in Lisbon. (you saved this)Hybrid scoring relies on fusing two rankings, and you can't just threshold them. By default, hybrid scoring gets recall for up to topK (default 5) memories per turn. If you want, you can use keyword-only recall, by setting minScore, which keeps only keyword hits above that BM25 score. Interestingly, keyword-only search for this message found nothing over those two facts.
TanStack AI's redis() adapter vs Upstash AgentKit
TanStack AI ships its own redis() memory adapter in @tanstack/ai-memory/redis, and lists upstashMemory() as a third-party adapter for the same memoryMiddleware(). Both plug in the same way, so the route code does not change. They differ in where the ranking happens:
Upstash AgentKit upstashMemory() | TanStack AI redis() | |
|---|---|---|
| Redis client | @upstash/redis over HTTP | ioredis or node-redis over TCP |
| Where ranking happens | In Redis, with a Redis Search query | In your server process, after loading the scope's records |
| How memories are scored | Keyword (BM25, typo tolerant) and meaning, merged in one query | Word overlap, recency, and importance, plus meaning when you add an embedder |
| Embeddings | Computed by Upstash Redis, no model or key to set up | Your own embedding model, called from your server |
| Records per scope | Ranked in the database, so no load per turn | About 10,000 |
| What gets saved | The user's message, plus facts the model saves with save_memory | The user and assistant turn, plus facts from your own extract function |
| Also included | Chat persistence, resumable streams, locks, tool caching, rate limiting, RAG tools | Memory only |
The main difference is that redis() loads each record in the scope into your process for scoring on each turn, while upstashMemory() uses a single search query to load only the top results.
How is this different than the other memory solutions featured in TanStack AI (Hindsight, Mem0, and Honcho)? Those solutions are hosted memory services. For example with Mem0, you send the conversation and they run their own fact extraction on that conversation and store those memories in their service. With upstashMemory(), the model chooses the facts with save_memory during the current model turn, and stores the memories in your own Redis database as JSON documents that you can read and delete.
Which one to use
Use TanStack AI's redis() if you already run a Redis server your app reaches over TCP, and you want to choose and pay for your own embedding model.
Use Upstash AgentKit if you want semantic recall without an embedding model, your routes run on serverless or edge runtimes that work best with an HTTP client, or you want transcripts, memories, and search in the same Upstash Redis database. Recall runs inside the database, so your server never loads a user's whole memory on a turn.
For most TanStack AI apps running on serverless environments, this is enough: withPersistence(upstashPersistence()) for chat history, and memoryMiddleware() with upstashMemory() for what the agent knows about the user.
You can find the full API reference in the AgentKit docs, and the source in the AgentKit repo. You can also read more about resumable streams, locks, and other helpers in the AgentKit for TanStack AI announcement.