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

adapters.md

237 lines10.3 KB

1---
2title: Adapters
3id: memory-adapters
4order: 3
5description: "Every built-in and vendor memory adapter in @tanstack/ai-memory, with all options and an example of each: inMemory, redis, hindsight, mem0, honcho."
6keywords:
7 - tanstack ai
8 - memory
9 - adapters
10 - inMemory
11 - redis
12 - hindsight
13 - mem0
14 - honcho
15 - options
16---
17​
18Each memory adapter implements `recall` and `save`. Swap one for another in `memoryMiddleware`.
19​
20| Adapter | Import | Use it for | Extra install |
21| --- | --- | --- | --- |
22| [`inMemory()`](#inmemory) | `@tanstack/ai-memory/in-memory` | Development, tests, demos | None |
23| [`redis()`](#redis) | `@tanstack/ai-memory/redis` | Production on your own Redis | `ioredis` or `redis` |
24| [`hindsight()`](#hindsight) | `@tanstack/ai-memory/hindsight` | Hindsight server, with memory tools for the model | `@vectorize-io/hindsight-client` |
25| [`mem0()`](#mem0) | `@tanstack/ai-memory/mem0` | mem0 server, over HTTP | None |
26| [`honcho()`](#honcho) | `@tanstack/ai-memory/honcho` | Honcho server | `@honcho-ai/sdk` |
27​
28All extra installs are optional peer dependencies. Install only the one that your adapter needs.
29​
30## Common options
31​
32`inMemory()` and `redis()` rank records in your server process with the same code, so they share these options:
33​
34| Option | Type | Default | Purpose |
35| --- | --- | --- | --- |
36| `topK` | `number` | `6` | Maximum number of hits that `recall` returns. |
37| `minScore` | `number` | `0.15` | Hits with a lower score are dropped. |
38| `kinds` | `Array<MemoryKind>` | all | Recall only these record kinds: `'message'`, `'summary'`, `'fact'`, `'preference'`. |
39| `embedder` | `{ embed(text): Promise<number[]> }` | none | Adds semantic scoring. Runs on `recall` and on `save`. |
40| `extract` | `(turn, scope) => ExtractedFact[]` | none | Saves derived facts on `save`, next to the raw turn. |
41| `render` | `(hits) => string` | built-in | Replaces the prompt renderer. |
42​
43All options in one adapter:
44​
45```ts
46import { inMemory } from '@tanstack/ai-memory/in-memory'
47​
48// `embedText` stands in for your embedding client (OpenAI, Cohere, a local model).
49declare function embedText(text: string): Promise<Array<number>>
50​
51const memory = inMemory({
52 topK: 8, // return up to 8 hits
53 minScore: 0.2, // ignore weak matches
54 kinds: ['message', 'fact', 'preference'], // skip summaries
55 embedder: { embed: embedText }, // semantic + lexical scoring
56 extract: (turn) => [
57 // store a derived fact next to the raw turn
58 { text: `User said: ${turn.user}`, kind: 'fact', importance: 0.8 },
59 ],
60 render: (hits) =>
61 // custom prompt block instead of the default renderer
62 `What I remember:\n${hits.map((h) => `- ${h.record.text}`).join('\n')}`,
63})
64```
65​
66- **`extract`** returns `ExtractedFact[]` (`{ text, kind?, importance?, metadata? }`), or `undefined` to save nothing extra. Put an LLM-based fact extractor here. The adapter does not depend on a model.
67- **`embedder`** embeds the query on `recall` and the stored text on `save`. With no embedder, the score uses word overlap, recency, and importance only.
68​
69## `inMemory()`
70​
71Records live in a `Map` and are lost when the process restarts. Each server process has its own `Map`. It takes only the [common options](#common-options).
72​
73```ts
74import { inMemory } from '@tanstack/ai-memory/in-memory'
75​
76const memory = inMemory() // all options are optional
77```
78​
79## `redis()`
80​
81Plain Redis, no vector index. It adds two options to the [common options](#common-options):
82​
83| Option | Type | Default | Purpose |
84| --- | --- | --- | --- |
85| `redis` | `RedisLike` | (required) | Your Redis client: `ioredis`, or node-redis through `fromNodeRedis`. |
86| `prefix` | `string` | `'tanstack-ai:memory'` | Key namespace. |
87​
88```ts
89import Redis from 'ioredis'
90import { redis } from '@tanstack/ai-memory/redis'
91​
92const memory = redis({
93 redis: new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379'), // required
94 prefix: 'myapp:memory', // key namespace
95 topK: 8, // common options apply here too
96 minScore: 0.2,
97})
98```
99​
100If you use **node-redis** (the `redis` package), wrap the client with `fromNodeRedis`. Its camelCase methods do not match `RedisLike`:
101​
102```ts
103import { createClient } from 'redis'
104import { redis, fromNodeRedis } from '@tanstack/ai-memory/redis'
105​
106const client = createClient({ url: process.env.REDIS_URL })
107await client.connect()
108​
109const memory = redis({ redis: fromNodeRedis(client) })
110```
111​
112`redis()` loads all records of a scope and ranks them in your process. This suits up to about 10,000 records per scope. For the key layout, see [Redis keys](#redis-keys).
113​
114## `hindsight()`
115​
116Hindsight does extraction and ranking on its server. `recall` also gives the model three tools: `hindsight_retain`, `hindsight_recall`, and `hindsight_reflect`. The client package loads only when the adapter first runs.
117​
118| Option | Type | Default | Purpose |
119| --- | --- | --- | --- |
120| `user` | `string` | `scope.userId`, then `'demo-user'` | User id in the bank id. |
121| `baseUrl` | `string` | `HINDSIGHT_URL` or `http://localhost:8888` | Server URL. |
122| `budget` | `'low' \| 'mid' \| 'high'` | `'mid'` | Recall budget. |
123| `onToolRetain` | `(receipt) => void` | none | Runs when the model calls `hindsight_retain`. |
124| `onToolRecall` | `(query, result) => void` | none | Runs when the model calls `hindsight_recall`. |
125​
126```ts
127import { hindsight } from '@tanstack/ai-memory/hindsight'
128​
129const memory = hindsight({
130 user: 'alice',
131 baseUrl: 'https://hindsight.internal', // default: HINDSIGHT_URL
132 budget: 'high', // deeper recall
133 onToolRetain: (receipt) => console.log('model retained', receipt.ok),
134 onToolRecall: (query, result) =>
135 console.log('model recalled', query, result.fragments?.length),
136})
137```
138​
139## `mem0()`
140​
141mem0 does extraction and ranking on its server. The adapter uses plain HTTP, so it needs no SDK. You need a running mem0 server.
142​
143| Option | Type | Default | Purpose |
144| --- | --- | --- | --- |
145| `user` | `string` | `scope.userId`, then `'demo-user'` | mem0 `user_id`. |
146| `baseUrl` | `string` | `MEM0_URL` or `http://localhost:8000` | Server URL. |
147| `apiKey` | `string` | `MEM0_ADMIN_API_KEY` | Bearer token. |
148| `rerank` | `boolean` | `true` | Ask mem0 to rerank search results. |
149| `threshold` | `number` | `0.1` | Minimum search score. |
150​
151```ts
152import { mem0 } from '@tanstack/ai-memory/mem0'
153​
154const memory = mem0({
155 user: 'alice', // mem0 user_id
156 baseUrl: 'https://mem0.internal', // default: MEM0_URL
157 apiKey: process.env.MEM0_ADMIN_API_KEY, // bearer token
158 rerank: true, // rerank results
159 threshold: 0.2, // stricter score floor
160})
161```
162​
163## `honcho()`
164​
165Honcho stores the turn as messages in a session. `recall` returns one written answer about the user, built by Honcho, with no separate fragments.
166​
167| Option | Type | Default | Purpose |
168| --- | --- | --- | --- |
169| `user` | `string` | `scope.userId`, then `'demo-user'` | User peer id. |
170| `baseURL` | `string` | `HONCHO_URL` or `http://localhost:8001` | Server URL. |
171| `workspaceId` | `string` | `HONCHO_APP_NAME` or `'ai-memory'` | Workspace id. |
172| `apiKey` | `string` | `HONCHO_API_KEY` or `'dev-no-auth'` | API key. |
173| `assistantId` | `string` | `'assistant'` | Assistant peer id. |
174​
175```ts
176import { honcho } from '@tanstack/ai-memory/honcho'
177​
178const memory = honcho({
179 user: 'alice', // user peer
180 baseURL: 'https://honcho.internal', // default: HONCHO_URL
181 workspaceId: 'my-app', // default: HONCHO_APP_NAME
182 apiKey: process.env.HONCHO_API_KEY, // default: 'dev-no-auth'
183 assistantId: 'support-bot', // default: 'assistant'
184})
185```
186​
187## Which `Scope` fields each adapter honors
188​
189| Adapter | `threadId` | `userId` | `tenantId` | `namespace` |
190| --- | --- | --- | --- | --- |
191| `inMemory()` | yes (exact) | yes (exact) | yes (exact) | ignored |
192| `redis()` | yes (key segment) | yes (key segment) | yes (key segment) | ignored |
193| `hindsight()` | yes (bank id) | yes (bank id or `user` option) | yes (bank prefix, `_` when unset) | ignored |
194| `mem0()` | yes (`run_id`) | yes (`user_id` or `user` option) | **no** | ignored |
195| `honcho()` | yes (session key) | yes (peer id or `user` option) | yes (session and peer prefix) | ignored |
196​
197An optional field matches exactly. A read with no `tenantId` does not match a record written with one. mem0 does not model tenants, so for multi-tenant isolation, put the tenant into the `user` option.
198​
199## Third-party adapters
200​
201These adapters are published outside TanStack AI. They have the same `recall` and `save` methods, so they work in `memoryMiddleware` like the ones above.
202​
203| Adapter | Package | Backend | Recall |
204| --- | --- | --- | --- |
205| [`upstashMemory()`](../community-adapters/upstash#memory) | `@upstash/agentkit-tanstack-ai/memory` | Upstash Redis (HTTP client) | BM25 full-text query in Redis Search |
206​
207`upstashMemory()` passes `runMemoryAdapterContract` from `@tanstack/ai-memory/testkit`. It ranks inside Redis, so it does not load records into your process. It honors `namespace` as well as `tenantId`, `userId`, and `threadId`.
208​
209## Advanced
210​
211### Redis keys
212​
213`redis()` writes two kinds of keys:
214​
215```text
216{prefix}:record:{id} -> JSON record
217{prefix}:index:{tenantId or _}:{userId or _}:{threadId} -> Set of record ids
218```
219​
220- Each scope value is escaped, so `:`, `\`, and `_` in a value cannot make two scopes share a key.
221- A missing optional field becomes `_`. A write with `tenantId` and a read without it use different keys. Always read with the same fields that you wrote with.
222- The adapter reads only this index layout. If you wrote memory under a different layout, reindex it or delete it.
223- If a stored record is not valid JSON, recall skips it, logs a warning, and leaves it in Redis.
224​
225### Vendor ids
226​
227- **Hindsight** bank id: `{tenantId or _}__{user}__{threadId}`.
228- **mem0** requests send `user_id` and `run_id` (the `threadId`). They do not send `tenantId`.
229- **Honcho** session key: `{tenantId or _}__{threadId}`. The user peer id is `{tenantId}__{user}` when `tenantId` is set, and the bare user id when it is not.
230​
231### How `inMemory()` and `redis()` score
232​
233- Each record gets a weighted score: semantic match 0.55, word overlap 0.20, recency 0.15, importance 0.10.
234- Recency halves every 30 days.
235- A raw user or assistant message is saved with importance 0.4. An extracted fact uses the `importance` that `extract` returns, or 0.
236- With no `embedder`, the semantic part is 0.
237- The default renderer quotes each record with `JSON.stringify`, so stored text with new lines or instructions cannot break out of the memory list.