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

custom-adapter.md

209 lines7.0 KB

1---
2title: Custom Adapter
3id: memory-custom-adapter
4order: 4
5description: "Write a recall/save MemoryAdapter for a backend that isn't shipped, such as pgvector, MongoDB, DynamoDB, or a hosted memory service. Two methods, one shared contract test."
6keywords:
7 - tanstack ai
8 - memory
9 - custom adapter
10 - MemoryAdapter
11 - recall
12 - save
13 - pgvector
14 - contract suite
15---
16​
17You have a backend in mind (pgvector, MongoDB, DynamoDB, a hosted memory API) and the
18built-in `inMemory()` / `redis()` adapters don't fit. A memory adapter is just an object
19with two methods, `recall` and `save`, so this is a short guide.
20​
21> **First time looking at memory?** Start with the [Overview](./overview) for what the
22> contract is and how the middleware uses it.
23​
24## The contract
25​
26```ts
27// The MemoryAdapter contract, from `@tanstack/ai-memory`:
28import type { MemoryAdapter } from '@tanstack/ai-memory'
29```
30​
31```ts
32// The shape of the contract, shown for reference.
33import type {
34 MemoryFact,
35 MemoryScope,
36 MemorySnapshot,
37 MemoryTurn,
38 RecallResult,
39 SaveReceipt,
40} from '@tanstack/ai-memory'
41​
42interface MemoryAdapter {
43 id: string
44 recall(scope: MemoryScope, query: string): Promise<RecallResult>
45 save(scope: MemoryScope, turn: MemoryTurn): Promise<Array<SaveReceipt>>
46 inspect?(scope: MemoryScope): Promise<MemorySnapshot> // optional (devtools)
47 listFacts?(scope: MemoryScope): Promise<Array<MemoryFact>> // optional (devtools)
49```
50​
51Two rules the middleware relies on:
52​
531. **`recall` decides relevance.** Return a rendered `systemPrompt` (empty string when
54 there's nothing), plus optional `fragments`, `tools`, and `toolGuidance`. Ranking
55 strategy is entirely yours: lexical, vector, hybrid, or vendor-native.
562. **`save` owns extraction.** Turn the `{ user, assistant }` turn into whatever you
57 persist. Return one `SaveReceipt` per underlying write.
58​
59Scope isolation is your responsibility: a `recall` for one `scope` must never surface
60another scope's data.
61​
62## Step 1: Scaffold
63​
64```ts
65import type {
66 MemoryAdapter,
67 MemoryScope,
68 MemoryTurn,
69 RecallResult,
70 SaveReceipt,
71} from '@tanstack/ai-memory'
72​
73// node-postgres' Pool, minimally. In your project, use the real type instead:
74// import type { Pool } from 'pg'
75type Pool = {
76 query: (
77 text: string,
78 values: Array<unknown>,
79 ) => Promise<{ rows: Array<{ text: string }> }>
81​
82// Your embedding client. Swap in OpenAI, Cohere, a local model, etc.
83type Embed = (text: string) => Promise<Array<number>>
84​
85export function pgvectorMemory(options: { pool: Pool; embed: Embed }): MemoryAdapter {
86 const { pool, embed } = options
87 return {
88 id: 'pgvector',
89​
90 async save(scope: MemoryScope, turn: MemoryTurn): Promise<Array<SaveReceipt>> {
91 const rows = [
92 { role: 'user', text: turn.user },
93 { role: 'assistant', text: turn.assistant },
94 ]
95 for (const row of rows) {
96 const vector = await embed(row.text)
97 await pool.query(
98 `INSERT INTO memory (thread_id, user_id, tenant_id, role, text, embedding)
99 VALUES ($1, $2, $3, $4, $5, $6)`,
100 [
101 scope.threadId,
102 scope.userId ?? null,
103 scope.tenantId ?? null,
104 row.role,
105 row.text,
106 JSON.stringify(vector),
107 ],
108 )
109 }
110 return [{ ok: true }]
111 },
112​
113 async recall(scope: MemoryScope, query: string): Promise<RecallResult> {
114 const q = await embed(query)
115 // Match every isolation dim exactly (including NULL). Omitted tenant/user
116 // must not match rows written with a tenant/user set.
117 const { rows } = await pool.query(
118 `SELECT text, 1 - (embedding <=> $1::vector) AS score
119 FROM memory
120 WHERE thread_id = $2
121 AND user_id IS NOT DISTINCT FROM $3::text
122 AND tenant_id IS NOT DISTINCT FROM $4::text
123 ORDER BY score DESC
124 LIMIT 6`,
125 [
126 JSON.stringify(q),
127 scope.threadId,
128 scope.userId ?? null,
129 scope.tenantId ?? null,
130 ],
131 )
132 const fragments = rows.map((r) => ({ text: r.text, source: 'pgvector' }))
133 const systemPrompt = fragments.length
134 ? `Relevant memory:\n${fragments.map((f) => `- ${f.text}`).join('\n')}`
135 : ''
136 return { systemPrompt, fragments }
137 },
138 }
140```
141​
142The shape generalizes: every method takes a `scope`, does its backend-specific work,
143and keeps scopes isolated. For a backend without native search, load the scope's
144records and rank them yourself.
145​
146## Step 2: Run the contract suite
147​
148`@tanstack/ai-memory/testkit` exports `runMemoryAdapterContract`. `inMemory` and `redis`
149run this suite. Point it at a factory that returns a fresh adapter. It verifies the save then recall round-trip, scope
150isolation, empty recall, receipt shape, and the optional introspection methods.
151​
152```ts ignore
153// ignore: imports the `../src/pgvector` module you wrote in Step 1.
154// tests/pgvector.test.ts
155import { runMemoryAdapterContract } from '@tanstack/ai-memory/testkit'
156import { pgvectorMemory } from '../src/pgvector'
157​
158runMemoryAdapterContract('pgvectorMemory', async () => {
159 const pool = makeCleanPool() // truncate between tests for a fresh adapter
160 return pgvectorMemory({ pool, embed })
161})
162```
163​
164## Step 3: Wire it into `memoryMiddleware`
165​
166Once the suite is green, the adapter is interchangeable with the built-ins:
167​
168```ts ignore
169// ignore: imports the `./pgvector` module you wrote in Step 1, and assumes
170// `messages` / `scope` from your app.
171import { chat } from '@tanstack/ai'
172import { openaiText } from '@tanstack/ai-openai'
173import { memoryMiddleware } from '@tanstack/ai-memory'
174import { pgvectorMemory } from './pgvector'
175​
176const memory = pgvectorMemory({ pool, embed })
177​
178const stream = chat({
179 adapter: openaiText('gpt-5.5'),
180 messages,
181 middleware: [memoryMiddleware({ adapter: memory, scope })],
182})
183```
184​
185The middleware never inspects the adapter's internals. `recall`/`save` is the entire
186interface.
187​
188## Exposing tools (optional)
189​
190`recall` can return `tools` and `toolGuidance` to give the model direct control over
191memory (this is how the `hindsight()` adapter exposes retain/recall/reflect tools). The
192middleware merges them into the run's tools and injects the guidance ahead of the
193recalled prompt. Return `tools: []` (or omit it) when your adapter exposes none.
194​
195## Pitfalls
196​
197- **Keep scopes isolated.** If you serialize scope into a composite key, escape your
198 delimiter so a `threadId`/`userId`/`tenantId` containing it can't collide with another
199 scope.
200- **`recall` must not throw for an empty scope.** Return `{ systemPrompt: '' }`.
201- **Extraction lives in `save`.** Don't expect the middleware to derive facts. The raw
202 turn is handed to you; store or summarize it however you like.
203​
204## Where to go next
205​
206- [Overview](./overview): the `recall`/`save` contract, scope, and how a turn flows
207- [Adapters](./adapters): the built-in and vendor adapters, with every option
208- [Quickstart](./quickstart): wire `memoryMiddleware` into a real `chat()` call
209- [Operating memory](./operating): options, telemetry, devtools events, and failures