Open History to see the last commit
1---
2title: Quickstart
3id: memory-quickstart
4order: 2
5description: "Add cross-session memory to a TanStack AI chat() call: install the package, pick a recall/save adapter, wire memoryMiddleware, and derive scope server-side."
6keywords:
7 - tanstack ai
8 - memory
9 - quickstart
10 - in-memory adapter
11 - redis adapter
12 - chat middleware
13---
14
15You have a working `chat()` call and you want it to remember context across turns or
16sessions. By the end of this guide, `memoryMiddleware` recalls relevant memory into the
17prompt and saves each finished turn through a real adapter, scoped safely from your
18server-validated session.
19
20> Want the full contract first? See the [Overview](./overview).
21
22## Step 1: Install the package
23
24<!-- ::start:tabs variant="package-manager" mode="install" -->
25
26react: @tanstack/ai-memory
27vue: @tanstack/ai-memory
28solid: @tanstack/ai-memory
29svelte: @tanstack/ai-memory
30preact: @tanstack/ai-memory
31angular: @tanstack/ai-memory
32vanilla: @tanstack/ai-memory
33octane: @tanstack/ai-memory
34
35<!-- ::end:tabs -->
36
37`@tanstack/ai-memory` ships `memoryMiddleware`, the `MemoryAdapter` contract, and the
38built-in and vendor adapters (each on its own subpath).
39
40## Step 2: Pick an adapter
41
42> **In-memory:** `inMemory()` is zero-dependency and stores records in a `Map`. Use it
43> for local development, tests, and single-process demos. Records vanish on restart.
44>
45> **Redis:** `redis({ redis })` persists across restarts and shares state across
46> processes. Bring your own client (`ioredis`, or `redis` via `fromNodeRedis`).
47>
48> **Vendors:** `hindsight()`, `mem0()`, and `honcho()` delegate to a hosted memory service.
49
50Custom adapters implement the `recall`/`save` contract. See [Custom Adapter](./custom-adapter).
51
52## Step 3: Wire `memoryMiddleware` into `chat()`
53
54Start with the in-memory adapter, the fastest path to a working setup:
55
56```ts
57import { chat } from '@tanstack/ai'
58import { openaiText } from '@tanstack/ai-openai'
59import { memoryMiddleware } from '@tanstack/ai-memory'
60import { inMemory } from '@tanstack/ai-memory/in-memory'
61
62const memory = inMemory()
63
64const stream = chat({
65 adapter: openaiText('gpt-5.5'),
66 messages: [{ role: 'user', content: 'Hello' }],
67 middleware: [
68 memoryMiddleware({
69 adapter: memory,
70 scope: { threadId: 'demo-thread', userId: 'alice' },
71 }),
72 ],
73})
74```
75
76Each turn, the middleware recalls relevant memory into the system prompt (lexical scoring
77by default), then deferred-saves the user and assistant turn after the stream finishes.
78
79When you're ready to ship, swap the adapter and keep everything else the same:
80
81```ts
82import Redis from 'ioredis'
83import { memoryMiddleware } from '@tanstack/ai-memory'
84import { redis } from '@tanstack/ai-memory/redis'
85import type { MemoryScope } from '@tanstack/ai-memory'
86
87declare const scope: MemoryScope // from Step 5
88
89const client = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
90const memory = redis({ redis: client })
91
92memoryMiddleware({ adapter: memory, scope })
93```
94
95> Using a hosted service? Swap `inMemory()` for `hindsight({ user })`, `mem0({ user })`,
96> or `honcho({ user })`. The middleware wiring is identical. The adapter maps
97> `recall`/`save` onto the vendor API.
98
99## Step 4: Semantic scoring (optional)
100
101The built-in adapters score lexically by default. Pass an `embedder` for semantic recall
102when scopes grow large or queries don't share keywords with stored text:
103
104```ts
105import OpenAI from 'openai'
106import { inMemory } from '@tanstack/ai-memory/in-memory'
107
108const openai = new OpenAI()
109
110const memory = inMemory({
111 embedder: {
112 async embed(text) {
113 const result = await openai.embeddings.create({
114 model: 'text-embedding-3-small',
115 input: text,
116 })
117 const embedding = result.data[0]?.embedding
118 if (!embedding) throw new Error('embedding request returned no vector')
119 return embedding
120 },
121 },
122})
123```
124
125## Step 5: Derive scope server-side
126
127`scope` is the isolation boundary. Static scopes are fine for fixtures, but in any real
128app derive scope per request from server-validated session data, never from the request
129body.
130
131```ts
132import { chat } from '@tanstack/ai'
133import { openaiText } from '@tanstack/ai-openai'
134import { memoryMiddleware } from '@tanstack/ai-memory'
135import type { ModelMessage } from '@tanstack/ai'
136import type { MemoryAdapter } from '@tanstack/ai-memory'
137
138// From earlier steps / your auth layer.
139declare const messages: Array<ModelMessage>
140declare const memory: MemoryAdapter
141declare const session: { userId: string; threadId: string }
142declare function getSession(ctx: unknown): { threadId: string; userId: string }
143
144const stream = chat({
145 adapter: openaiText('gpt-5.5'),
146 messages,
147 context: { session }, // attached by your auth middleware, not from req.body
148 middleware: [
149 memoryMiddleware({
150 adapter: memory,
151 scope: (ctx) => {
152 const session = getSession(ctx)
153 return { threadId: session.threadId, userId: session.userId }
154 },
155 }),
156 ],
157})
158```
159
160On the client, nothing changes for memory wiring — consume the same stream as any
161other `chat()` endpoint:
162
163```ts
164import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
165
166function Chat() {
167 const { messages, sendMessage, isLoading } = useChat({
168 connection: fetchServerSentEvents('/api/chat'),
169 })
170 // Memory is entirely server-side; the client only sees the usual message stream.
171 return (
172 // render messages, input, sendMessage, isLoading…
173 null
174 )
175}
176```
177
178## Where to go next
179
180- [Overview](./overview): the `recall`/`save` contract, scope, and how a turn flows
181- [Adapters](./adapters): every adapter's options, with an example of each
182- [Operating memory](./operating): options, telemetry, devtools events, and failures
183- [Custom Adapter](./custom-adapter): implement `recall`/`save` for a backend that isn't shipped