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

tools.ts

139 lines4.9 KB

1import type { Tool } from '@tanstack/ai'
2import type { MemoryFragment, RecallResult, SaveReceipt } from '../../types'
3import type { HindsightRuntime } from './index'
4​
5export interface HindsightToolDeps {
6 getRuntime: () => Promise<HindsightRuntime>
7 bankId: string
8 budget: string
9 onToolRetain?: (receipt: SaveReceipt) => void
10 onToolRecall?: (query: string, result: RecallResult) => void
12​
13function stringField(args: unknown, key: string): string {
14 if (args && typeof args === 'object' && key in args) {
15 const value = (args as Record<string, unknown>)[key]
16 if (typeof value === 'string') return value
17 }
18 return ''
20​
21/**
22 * Build the hindsight LLM tools (retain / recall / reflect). These let the model
23 * take direct control of long-term memory beyond the automatic recall/save the
24 * middleware performs. Returned in `RecallResult.tools` and merged into the run.
25 */
26export function makeHindsightTools(deps: HindsightToolDeps): Array<Tool> {
27 const retainTool: Tool = {
28 name: 'hindsight_retain',
29 description:
30 'Explicitly store a fact, decision, or piece of context to remember in future sessions. Call this when the user shares something important about themselves, their preferences, their work, or any detail that should persist beyond this conversation.',
31 inputSchema: {
32 type: 'object',
33 properties: {
34 content: {
35 type: 'string',
36 description:
37 'The exact fact, decision, or piece of context to store. Write it as a self-contained statement that will still make sense out of conversation context.',
38 },
39 },
40 required: ['content'],
41 additionalProperties: false,
42 },
43 async execute(args) {
44 const content = stringField(args, 'content')
45 const start = Date.now()
46 try {
47 const { client } = await deps.getRuntime()
48 const data = await client.retain(deps.bankId, content, {
49 context: 'chat:tool',
50 timestamp: new Date(),
51 })
52 deps.onToolRetain?.({
53 ok: true,
54 latencyMs: Date.now() - start,
55 raw: data,
56 })
57 return { ok: true }
58 } catch (err) {
59 const error = err instanceof Error ? err.message : String(err)
60 deps.onToolRetain?.({ ok: false, latencyMs: Date.now() - start, error })
61 return { ok: false, error }
62 }
63 },
64 }
65​
66 const recallTool: Tool = {
67 name: 'hindsight_recall',
68 description:
69 "Query memory directly with a specific question. Use this when you need context that may not have surfaced in the automatic recall — for example, to look up a different topic than the user's last message, or to find facts about an entity mentioned in passing.",
70 inputSchema: {
71 type: 'object',
72 properties: {
73 query: {
74 type: 'string',
75 description: 'Natural-language question or topic to look up.',
76 },
77 },
78 required: ['query'],
79 additionalProperties: false,
80 },
81 async execute(args) {
82 const query = stringField(args, 'query')
83 const start = Date.now()
84 try {
85 const { client, recallToPrompt } = await deps.getRuntime()
86 const data = await client.recall(deps.bankId, query, {
87 budget: deps.budget,
88 })
89 const systemPrompt = recallToPrompt(data)
90 const fragments: Array<MemoryFragment> = (data.results ?? []).map(
91 (r) => ({
92 text: r.text,
93 source: r.type ?? r.id,
94 }),
95 )
96 deps.onToolRecall?.(query, {
97 systemPrompt,
98 fragments,
99 latencyMs: Date.now() - start,
100 raw: data,
101 } as RecallResult)
102 return systemPrompt || '(no relevant memories found)'
103 } catch (err) {
104 const error = err instanceof Error ? err.message : String(err)
105 return `(no memory available: ${error})`
106 }
107 },
108 }
109​
110 const reflectTool: Tool = {
111 name: 'hindsight_reflect',
112 description:
113 'Synthesize across many memories to answer questions that require reasoning over accumulated knowledge, rather than retrieving specific facts. Use this for questions like "what do I know about this user\'s stack?" or "what has the user been working on lately?"',
114 inputSchema: {
115 type: 'object',
116 properties: {
117 query: {
118 type: 'string',
119 description:
120 'The synthesis question to reflect on, e.g. "what do I know about the user\'s preferences?"',
121 },
122 },
123 required: ['query'],
124 additionalProperties: false,
125 },
126 async execute(args) {
127 const query = stringField(args, 'query')
128 try {
129 const { client } = await deps.getRuntime()
130 const data = await client.reflect(deps.bankId, query)
131 return data.text ?? '(no reflection)'
132 } catch (err) {
133 return `(reflection failed: ${err instanceof Error ? err.message : String(err)})`
134 }
135 },
136 }
137​
138 return [retainTool, recallTool, reflectTool]