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

select-relevant-snippets.ts

145 lines4.0 KB

1import { chat } from '@tanstack/ai'
2import type { AnyTextAdapter, ModelMessage, StreamChunk } from '@tanstack/ai'
3import type { Snippet, SnippetIndexEntry, SnippetStorage } from './types'
4​
5interface SelectRelevantSnippetsOptions {
6 /**
7 * Text adapter for snippet selection (should be a cheap/fast model)
8 */
9 adapter: AnyTextAdapter
10​
11 /**
12 * Current conversation messages
13 */
14 messages: Array<ModelMessage>
15​
16 /**
17 * Thread id of the conversation. The selection chat uses
18 * `${threadId}:snippets`.
19 */
20 threadId: string
21​
22 /**
23 * Snippet index (lightweight metadata)
24 */
25 snippetIndex: Array<SnippetIndexEntry>
26​
27 /**
28 * Maximum number of snippets to select
29 */
30 maxSnippets: number
31​
32 /**
33 * Storage to load full snippet data
34 */
35 storage: SnippetStorage
37​
38/**
39 * Use a cheap/fast LLM to select which snippets are relevant for the current conversation
40 */
41export async function selectRelevantSnippets({
42 adapter,
43 messages,
44 threadId,
45 snippetIndex,
46 maxSnippets,
47 storage,
48}: SelectRelevantSnippetsOptions): Promise<Array<Snippet>> {
49 // Early exit conditions
50 if (snippetIndex.length === 0) return []
51 if (messages.length === 0) return []
52​
53 // Build context from recent messages (last 5)
54 const recentMessages = messages.slice(-5)
55 const recentContext = recentMessages
56 .map((m) => {
57 let content: string
58 if (typeof m.content === 'string') {
59 content = m.content
60 } else if (Array.isArray(m.content)) {
61 // Handle content parts (text, images, etc.)
62 content = m.content
63 .map((part: unknown) => {
64 if (typeof part === 'string') return part
65 if (part && typeof part === 'object' && 'text' in part)
66 return (part as { text: string }).text
67 return '[non-text content]'
68 })
69 .join(' ')
70 } else {
71 content = '[complex content]'
72 }
73 return `${m.role}: ${content}`
74 })
75 .join('\n')
76​
77 // Build snippet catalog for selection prompt
78 const snippetCatalog = snippetIndex
79 .map((s) => {
80 const hints = s.usageHints.length > 0 ? ` (${s.usageHints[0]})` : ''
81 return `- ${s.name}: ${s.description}${hints}`
82 })
83 .join('\n')
84​
85 // Ask cheap model to select relevant snippets
86 const selectionPrompt = `Given this conversation context:
87---
88${recentContext}
89---
90​
91Which of these snippets (if any) would be useful for the next response? Return a JSON array of snippet names, max ${maxSnippets}. Return [] if none are relevant.
92​
93Available snippets:
94${snippetCatalog}
95​
96Respond with only the JSON array, no explanation. Example: ["snippet_name_1", "snippet_name_2"]`
97​
98 try {
99 // Use chat to get the selection
100 const stream = chat({
101 adapter,
102 // A thread of its own: the selection call is not a turn of the conversation.
103 threadId: `${threadId}:snippets`,
104 messages: [
105 {
106 role: 'user',
107 content: selectionPrompt,
108 },
109 ],
110 })
111​
112 // Collect the full response
113 let responseText = ''
114 for await (const chunk of stream as AsyncIterable<StreamChunk>) {
115 if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
116 responseText += chunk.delta
117 }
118 }
119​
120 // Parse the JSON response
121 // Handle potential markdown code blocks
122 let jsonText = responseText.trim()
123 if (jsonText.startsWith('```')) {
124 // Remove markdown code block
125 jsonText = jsonText.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '')
126 }
127​
128 const selectedNames: Array<string> = JSON.parse(jsonText)
129​
130 if (!Array.isArray(selectedNames)) {
131 return []
132 }
133​
134 // Load full snippet data for selected snippets
135 const selectedSnippets = await Promise.all(
136 selectedNames.slice(0, maxSnippets).map((name) => storage.get(name)),
137 )
138​
139 return selectedSnippets.filter((s): s is Snippet => s !== null)
140 } catch (error) {
141 // If parsing fails or any error occurs, return empty (safe fallback)
142 console.warn('Snippet selection failed, returning empty selection:', error)
143 return []
144 }