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

custom-adapter.md

207 lines7.1 KB

1---
2title: Custom Adapter
3id: memory-custom-adapter
4order: 4
5description: "Write a recall/save MemoryAdapter for a backend that TanStack AI does not ship, 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​
17A custom memory adapter is an object with `recall` and `save`. Use one for pgvector, MongoDB, DynamoDB, or a hosted memory API.
18​
19This page builds a pgvector adapter. The same shape works for any backend.
20​
21## Quick setup
22​
23### 1. Write the adapter
24​
25`save` stores the turn. `recall` returns the records that match the query, as a prompt block:
26​
27```ts
28// pgvector.ts
29import type {
30 MemoryAdapter,
31 MemoryScope,
32 MemoryTurn,
33 RecallResult,
34 SaveReceipt,
35} from '@tanstack/ai-memory'
36​
37// node-postgres' Pool, minimally. In your project, use the real type instead:
38// import type { Pool } from 'pg'
39type Pool = {
40 query: (
41 text: string,
42 values: Array<unknown>,
43 ) => Promise<{ rows: Array<{ text: string }> }>
45​
46// Your embedding client. Swap in OpenAI, Cohere, a local model, and more.
47type Embed = (text: string) => Promise<Array<number>>
48​
49export function pgvectorMemory(options: { pool: Pool; embed: Embed }): MemoryAdapter {
50 const { pool, embed } = options
51 return {
52 id: 'pgvector',
53​
54 async save(scope: MemoryScope, turn: MemoryTurn): Promise<Array<SaveReceipt>> {
55 const rows = [
56 { role: 'user', text: turn.user },
57 { role: 'assistant', text: turn.assistant },
58 ]
59 for (const row of rows) {
60 const vector = await embed(row.text)
61 await pool.query(
62 `INSERT INTO memory (thread_id, user_id, tenant_id, role, text, embedding)
63 VALUES ($1, $2, $3, $4, $5, $6)`,
64 [
65 scope.threadId,
66 scope.userId ?? null,
67 scope.tenantId ?? null,
68 row.role,
69 row.text,
70 JSON.stringify(vector),
71 ],
72 )
73 }
74 return [{ ok: true }]
75 },
76​
77 async recall(scope: MemoryScope, query: string): Promise<RecallResult> {
78 const q = await embed(query)
79 // Match every isolation field exactly (including NULL). An omitted
80 // tenant or user must not match rows written with a tenant or user.
81 const { rows } = await pool.query(
82 `SELECT text, 1 - (embedding <=> $1::vector) AS score
83 FROM memory
84 WHERE thread_id = $2
85 AND user_id IS NOT DISTINCT FROM $3::text
86 AND tenant_id IS NOT DISTINCT FROM $4::text
87 ORDER BY score DESC
88 LIMIT 6`,
89 [
90 JSON.stringify(q),
91 scope.threadId,
92 scope.userId ?? null,
93 scope.tenantId ?? null,
94 ],
95 )
96 const fragments = rows.map((r) => ({ text: r.text, source: 'pgvector' }))
97 const systemPrompt = fragments.length
98 ? `Relevant memory:\n${fragments.map((f) => `- ${f.text}`).join('\n')}`
99 : ''
100 return { systemPrompt, fragments }
101 },
102 }
104```
105​
106### 2. Run the contract suite
107​
108`runMemoryAdapterContract` from `@tanstack/ai-memory/testkit` is a Vitest suite. Give it a factory that returns a fresh adapter:
109​
110```ts ignore
111// ignore: imports the `../src/pgvector` module you wrote in Step 1.
112// tests/pgvector.test.ts
113import { runMemoryAdapterContract } from '@tanstack/ai-memory/testkit'
114import { pgvectorMemory } from '../src/pgvector'
115​
116runMemoryAdapterContract('pgvectorMemory', async () => {
117 const pool = makeCleanPool() // truncate between tests for a fresh adapter
118 return pgvectorMemory({ pool, embed })
119})
120```
121​
122The suite checks:
123​
124- A saved turn comes back in a later `recall`.
125- `recall` on an empty scope returns an empty prompt.
126- `recall` never returns data from another `threadId`, `userId`, or `tenantId`.
127- `save` returns at least one receipt with `ok: true`.
128- `inspect` and `listFacts`, if you add them, return well-formed data.
129​
130`inMemory()` and `redis()` run the same suite.
131​
132### 3. Add it to `memoryMiddleware`
133​
134When the suite passes, use your adapter like a built-in one:
135​
136```ts ignore
137// ignore: imports the `./pgvector` module you wrote in Step 1, and assumes
138// `pool`, `embed`, `messages`, and `scope` from your app.
139import { chat } from '@tanstack/ai'
140import { openaiText } from '@tanstack/ai-openai'
141import { memoryMiddleware } from '@tanstack/ai-memory'
142import { pgvectorMemory } from './pgvector'
143​
144const memory = pgvectorMemory({ pool, embed })
145​
146const stream = chat({
147 adapter: openaiText('gpt-6.1-sol'),
148 messages,
149 threadId: 'thread-1',
150 middleware: [memoryMiddleware({ adapter: memory, scope })],
151})
152```
153​
154Your backend now gives memory to every chat that uses this middleware.
155​
156## How it works
157​
158The middleware calls only the adapter methods. It never reads your records.
159​
160```ts
161// The shape of the contract, shown for reference.
162import type {
163 MemoryFact,
164 MemoryScope,
165 MemorySnapshot,
166 MemoryTurn,
167 RecallResult,
168 SaveReceipt,
169} from '@tanstack/ai-memory'
170​
171interface MemoryAdapter {
172 id: string
173 name?: string // optional label for logs, defaults to id
174 recall(scope: MemoryScope, query: string): Promise<RecallResult>
175 save(scope: MemoryScope, turn: MemoryTurn): Promise<Array<SaveReceipt>>
176 inspect?(scope: MemoryScope): Promise<MemorySnapshot> // optional (devtools)
177 listFacts?(scope: MemoryScope): Promise<Array<MemoryFact>> // optional (devtools)
179```
180​
181| Member | What it does |
182| --- | --- |
183| `id` | A stable name for logs and devtools. |
184| `name` | Optional. A readable label for logs. The default is `id`. |
185| `recall(scope, query)` | Decides what is relevant. Returns a rendered `systemPrompt` (an empty string when there is nothing), plus optional `fragments`, `tools`, and `toolGuidance`. You choose the ranking: lexical, vector, hybrid, or what your vendor gives. |
186| `save(scope, turn)` | Owns extraction. Turns the `{ user, assistant }` turn into what you store. Returns one `SaveReceipt` per write. |
187| `inspect(scope)` | Optional. A full snapshot for the devtools panel. |
188| `listFacts(scope)` | Optional. A flat fact list for the devtools panel. |
189​
190Your adapter owns scope isolation. A `recall` for one scope must never return data from another scope.
191​
192## Advanced
193​
194### Give the model memory tools
195​
196`recall` can return `tools` and `toolGuidance`. Then the model can read or write memory itself. The `hindsight()` adapter uses this for its retain, recall, and reflect tools.
197​
198- The middleware adds your tools to the tools of the run. It skips a tool when the run already has a tool with the same name.
199- The middleware puts `toolGuidance` in the system prompts before the recalled `systemPrompt`.
200- If your adapter has no tools, return `tools: []` or leave it out.
201​
202### Pitfalls
203​
204- **Keep scopes isolated.** If you put the scope into one composite key, escape the delimiter. Then a `threadId`, `userId`, or `tenantId` that contains the delimiter cannot match another scope.
205- **Do not throw for an empty scope.** Return `{ systemPrompt: '' }` from `recall`.
206- **Do extraction in `save`.** The middleware does not derive facts. It gives you the raw turn. Store it or summarize it as you need.
207- **Backends without search.** Load the records of the scope and rank them in your code.