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

structured-output.ts

124 lines4.0 KB

1import { chat, maxIterations } from '@tanstack/ai'
2import {
3 createSnippetManagementTools,
4 createSnippetsSystemPrompt,
5 snippetsToTools,
6} from '@tanstack/ai-code-mode-snippets'
7import { maxTokensModelOptions } from './max-tokens-model-options'
8import type { AnyTextAdapter, AnyTool, SchemaInput } from '@tanstack/ai'
9import type { CodeModeTool, IsolateDriver } from '@tanstack/ai-code-mode'
10import type {
11 SnippetStorage,
12 TrustStrategy,
13} from '@tanstack/ai-code-mode-snippets'
14​
15export interface StructuredOutputOptions<TSchema extends SchemaInput> {
16 adapter: AnyTextAdapter
17 prompt: string
18 outputSchema: TSchema
19 codeMode: {
20 tool: AnyTool
21 systemPrompt: string
22 driver: IsolateDriver
23 codeTools: Array<CodeModeTool>
24 }
25 snippets?: {
26 storage: SnippetStorage
27 trustStrategy: TrustStrategy
28 timeout?: number
29 memoryLimit?: number
30 }
31 tools?: Array<AnyTool>
32 maxIterations?: number
33 maxTokens?: number
35​
36const SNIPPET_REGISTRATION_PROMPT = `## Snippet Registration — MANDATORY
37​
38After every successful \`execute_typescript\` call you MUST register the code as a reusable snippet using \`register_snippet\` — unless an identical snippet already exists.
39​
40Rules:
41- \`name\`: descriptive snake_case (e.g. \`get_average_product_price\`)
42- \`code\`: the TypeScript code, parameterised with an \`input\` variable where useful
43- \`inputSchema\` / \`outputSchema\`: valid JSON Schema **strings**
44- If a snippet with the same name exists, skip registration
45​
46This is not optional — snippet registration is a core part of your workflow.`
47​
48export async function structuredOutput<TSchema extends SchemaInput>(
49 options: StructuredOutputOptions<TSchema>,
50) {
51 const {
52 adapter,
53 prompt,
54 outputSchema,
55 codeMode,
56 snippets,
57 tools = [],
58 maxIterations: maxIter = 10,
59 maxTokens: maxTok = 8192,
60 } = options
61​
62 const snippetGuidance = snippets
63 ? `- If a snippet tool matches what you need, call it directly — snippet tools are faster and preferred over writing new code.
64- Use execute_typescript only for tasks not covered by existing snippet tools. After successful execute_typescript calls, register the code as a reusable snippet.`
65 : `- Use execute_typescript to gather the data you need. Chain multiple tool calls if needed.`
66​
67 const systemPrompt = `${prompt}
68​
69RULES:
70- Do NOT produce conversational text. No greetings, no narration. Only tool calls and the final structured response.
71${snippetGuidance}`
72​
73 let allTools: Array<AnyTool> = [codeMode.tool, ...tools]
74 const systemPrompts = [systemPrompt, codeMode.systemPrompt]
75​
76 if (snippets) {
77 const allSnippets = await snippets.storage.loadAll()
78 const snippetIndex = await snippets.storage.loadIndex()
79​
80 if (allSnippets.length > 0) {
81 const snippetToolsList = snippetsToTools({
82 snippets: allSnippets,
83 driver: codeMode.driver,
84 tools: codeMode.codeTools,
85 storage: snippets.storage,
86 timeout: snippets.timeout ?? 60000,
87 memoryLimit: snippets.memoryLimit ?? 128,
88 })
89 allTools = [...allTools, ...snippetToolsList]
90 }
91​
92 const mgmtTools = createSnippetManagementTools({
93 storage: snippets.storage,
94 trustStrategy: snippets.trustStrategy,
95 })
96 allTools = [...allTools, ...mgmtTools]
97​
98 const libraryPrompt = createSnippetsSystemPrompt({
99 selectedSnippets: allSnippets,
100 totalSnippetCount: snippetIndex.length,
101 snippetsAsTools: true,
102 })
103 systemPrompts.push(libraryPrompt + '\n\n' + SNIPPET_REGISTRATION_PROMPT)
104 }
105​
106 console.log(
107 '[StructuredOutput] Tools passed to chat:',
108 allTools.map((t) => t.name),
109 )
110​
111 const result = await chat({
112 adapter,
113 messages: [{ role: 'user' as const, content: prompt }],
114 tools: allTools,
115 systemPrompts,
116 agentLoopStrategy: maxIterations(maxIter),
117 // Sampling lives in provider-native `modelOptions` now; map the generic
118 // cap to the resolved adapter's wire key.
119 modelOptions: maxTokensModelOptions(adapter, maxTok),
120 outputSchema,
121 })
122​
123 return result