Open History to see the last commit
1import { renderLazyCatalogEntry } from '@tanstack/ai'
2import { toolsToBindings } from './bindings/tool-to-binding'
3import { generateTypeStubs } from './type-generator/json-schema-to-ts'
4import type { CodeModeToolConfig } from './types'
5
6/**
7 * Create a system prompt snippet that documents the execute_typescript tool
8 * and all available external_* functions.
9 *
10 * Add this to your system prompts array when using createCodeModeTool.
11 *
12 * @example
13 * ```typescript
14 * import { createCodeMode } from '@tanstack/ai-code-mode'
15 * import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
16 *
17 * const { tool, systemPrompt } = createCodeMode({
18 * driver: createNodeIsolateDriver(),
19 * tools: [weatherTool, dbTool],
20 * })
21 *
22 * chat({
23 * systemPrompts: ['You are a helpful assistant.', systemPrompt],
24 * tools: [tool, ...otherTools],
25 * })
26 * ```
27 */
28export function createCodeModeSystemPrompt(config: CodeModeToolConfig): string {
29 const { tools } = config
30 const include = config.lazyToolsConfig?.includeDescription ?? 'none'
31
32 const eagerTools = tools.filter((t) => !t.lazy)
33 const lazyTools = tools.filter((t) => t.lazy)
34
35 // Only eager tools get full type stubs + doc lines.
36 const bindings = toolsToBindings(eagerTools, 'external_')
37 const typeStubs = generateTypeStubs(bindings)
38
39 const functionDocs = Object.entries(bindings)
40 .map(([name, binding]) => `- \`${name}(input)\`: ${binding.description}`)
41 .join('\n')
42
43 const discoverableSection =
44 lazyTools.length > 0
45 ? `
46
47### Discoverable APIs
48
49These additional functions are available but not yet documented. Before calling \`external_<name>\` for any of them inside \`execute_typescript\`, call the \`discover_tools\` tool with their names to get full TypeScript signatures:
50
51${lazyTools
52 .map(
53 (t) =>
54 `- ${renderLazyCatalogEntry(`external_${t.name}`, t.description, include)}`,
55 )
56 .join('\n')}`
57 : ''
58
59 return `## Code Execution Tool
60
61You have access to \`execute_typescript\` which runs TypeScript code in a sandboxed environment.
62
63### When to Use
64
65Use \`execute_typescript\` when you need to:
66- Process data with loops, conditionals, or complex logic
67- Make multiple API calls in parallel (Promise.all)
68- Transform, filter, or aggregate data
69- Perform calculations or data analysis
70
71For simple operations, prefer calling tools directly.
72
73### Available External APIs
74
75Inside your TypeScript code, you can call these async functions:
76
77${functionDocs}
78
79### Type Definitions
80
81\`\`\`typescript
82${typeStubs}
83\`\`\`${discoverableSection}
84
85### Example
86
87\`\`\`typescript
88// Fetch weather for multiple cities in parallel
89const cities = ["Tokyo", "Paris", "NYC"];
90const results = await Promise.all(
91 cities.map(city => external_fetchWeather({ location: city }))
92);
93
94// Find the warmest city
95const warmest = results.reduce((prev, curr) =>
96 curr.temperature > prev.temperature ? curr : prev
97);
98
99return { warmestCity: warmest.location, temperature: warmest.temperature };
100\`\`\`
101
102### Important Notes
103
104- All \`external_*\` calls are async - always use \`await\`
105- Return a value to pass results back to you
106- Use \`console.log()\` for debugging (logs are captured)
107- The sandbox is isolated - no network access or file system
108- Each execution is independent (no shared state between calls)
109`
110}