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