Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

overview.md

132 lines4.8 KB

1---
2title: Overview
3id: memory-overview
4order: 1
5description: "Give a TanStack AI chat() call memory. memoryMiddleware recalls relevant memory into the prompt before the model runs, then saves each finished turn through an adapter that you choose."
6keywords:
7 - tanstack ai
8 - memory
9 - long-term memory
10 - retrieval
11 - persistence
12 - middleware
13 - rag
14 - personalization
15---
16​
17Memory stores facts from earlier turns and puts them back into the next request. The model then keeps the user's name, stack, and preferences.
18​
19`memoryMiddleware` finds the memory that matters for each new message, adds it to the prompt, and saves each finished turn for later.
20​
21## Quick setup
22​
23### 1. Install the package
24​
25<!-- ::start:tabs variant="package-manager" mode="install" -->
26​
27react: @tanstack/ai-memory
28vue: @tanstack/ai-memory
29solid: @tanstack/ai-memory
30svelte: @tanstack/ai-memory
31preact: @tanstack/ai-memory
32angular: @tanstack/ai-memory
33vanilla: @tanstack/ai-memory
34octane: @tanstack/ai-memory
35​
36<!-- ::end:tabs -->
37​
38### 2. Add the middleware to `chat()`
39​
40```ts
41import { chat } from '@tanstack/ai'
42import { openaiText } from '@tanstack/ai-openai'
43import { memoryMiddleware } from '@tanstack/ai-memory'
44import { inMemory } from '@tanstack/ai-memory/in-memory'
45​
46const memory = inMemory()
47​
48const stream = chat({
49 adapter: openaiText('gpt-6.1-sol'),
50 messages: [{ role: 'user', content: 'Hello' }],
51 threadId: 'demo-thread',
52 middleware: [
53 memoryMiddleware({
54 adapter: memory,
55 scope: { threadId: 'demo-thread', userId: 'alice' },
56 }),
57 ],
58})
59```
60​
61That is all the wiring. Memory runs on the server only, so your client code does not change.
62​
63The [Quickstart](./quickstart) puts this in a real server route with a client, and then makes it ready for production.
64​
65## How it works
66​
67Each run has two memory steps:
68​
691. **Recall.** Before the model runs, the middleware sends the last user message to `adapter.recall(scope, query)`. The adapter returns a prompt block, and the middleware adds it to the system prompts. Some adapters also return tools that let the model read and write memory.
702. **Save.** After the stream finishes, the middleware gives the `{ user, assistant }` turn to `adapter.save(scope, turn)`. The save is deferred, so it never blocks the response.
71​
72The adapter does the rest: it extracts, ranks, renders, and stores. The middleware never reads a stored record.
73​
74If `recall` or `save` fails, the chat continues without memory. See [Operating memory](./operating).
75​
76## Pick an adapter
77​
78| You need | Use |
79| --- | --- |
80| Local development, tests, a demo | `inMemory()` |
81| Memory that survives a restart and is shared across processes | `redis()` |
82| A hosted memory service | `hindsight()`, `mem0()`, or `honcho()` |
83| A backend that is not in the list | A [custom adapter](./custom-adapter) |
84​
85Every adapter has the same `recall` and `save` methods, so you can swap one for another and keep the rest of your code. [Adapters](./adapters) lists the options for each one.
86​
87> [!TIP]
88> Memory is for context from earlier turns or earlier sessions. To keep the last few messages of the current request, send them in `messages`. You do not need memory for that.
89​
90## Scope: whose memory is it
91​
92`scope` tells the adapter which memory to read and write. `MemoryScope` is the same `Scope` type that `@tanstack/ai` uses for persistence:
93​
94```ts
95type MemoryScope = {
96 threadId: string // required, the same value as ChatMiddlewareContext.threadId
97 userId?: string
98 tenantId?: string
99 namespace?: string // reserved, no adapter uses it yet
101```
102​
103Set the scope on the server, from the session of the signed-in user:
104​
105- Read `userId` and `tenantId` from your auth session. Never read them from the request body.
106- If the client sends `threadId`, make sure that the thread belongs to the session user before you use it.
107​
108Use the function form of `scope` to set the scope for each request. It gets the chat context:
109​
110```ts
111import { memoryMiddleware } from '@tanstack/ai-memory'
112import { inMemory } from '@tanstack/ai-memory/in-memory'
113​
114// Replace with your auth. Return the user from the session, not from the body.
115function getUserId(): string {
116 return 'demo-user'
118​
119const middleware = memoryMiddleware({
120 adapter: inMemory(),
121 scope: (ctx) => ({ threadId: ctx.threadId, userId: getUserId() }),
122})
123```
124​
125The built-in adapters match every scope field exactly. A read with no `tenantId` does not find a record written with a `tenantId`. For the fields that each adapter uses, see [Which Scope fields each adapter honors](./adapters#which-scope-fields-each-adapter-honors).
126​
127## Next
128​
129- [Quickstart](./quickstart): a full server route, a client, and a production adapter.
130- [Adapters](./adapters): every adapter and its options.
131- [Custom Adapter](./custom-adapter): write `recall` and `save` for your own backend.
132- [Operating memory](./operating): telemetry, devtools, and what happens when memory fails.