@datagrok/grokky 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/.eslintignore +2 -0
  2. package/.eslintrc.json +48 -0
  3. package/CHANGELOG.md +26 -0
  4. package/README.md +3 -0
  5. package/css/ai.css +200 -0
  6. package/detectors.js +9 -0
  7. package/dist/package-test.js +1738 -0
  8. package/dist/package-test.js.map +1 -0
  9. package/dist/package.js +92488 -0
  10. package/dist/package.js.map +1 -0
  11. package/dockerfiles/claude-runtime/.dockerignore +4 -0
  12. package/dockerfiles/claude-runtime/Dockerfile +27 -0
  13. package/dockerfiles/claude-runtime/container.json +5 -0
  14. package/dockerfiles/claude-runtime/package-lock.json +448 -0
  15. package/dockerfiles/claude-runtime/package.json +20 -0
  16. package/dockerfiles/claude-runtime/src/server.ts +273 -0
  17. package/dockerfiles/claude-runtime/src/types.ts +37 -0
  18. package/dockerfiles/claude-runtime/tsconfig.json +15 -0
  19. package/dockerfiles/mcp-server/Dockerfile +12 -0
  20. package/dockerfiles/mcp-server/container.json +1 -0
  21. package/dockerfiles/mcp-server/package-lock.json +1178 -0
  22. package/dockerfiles/mcp-server/package.json +15 -0
  23. package/dockerfiles/mcp-server/src/api-client.ts +100 -0
  24. package/dockerfiles/mcp-server/src/index.ts +155 -0
  25. package/dockerfiles/mcp-server/tsconfig.json +13 -0
  26. package/package.json +126 -0
  27. package/package.png +0 -0
  28. package/src/ai-panel.ts +174 -0
  29. package/src/claude-code/claude-panel.ts +34 -0
  30. package/src/claude-code/claude-runtime-client.ts +148 -0
  31. package/src/llm-utils/LLM-client.ts +251 -0
  32. package/src/llm-utils/combined-search.ts +162 -0
  33. package/src/llm-utils/creds.ts +30 -0
  34. package/src/llm-utils/db-index-tools.ts +642 -0
  35. package/src/llm-utils/deepwikiclient.ts +118 -0
  36. package/src/llm-utils/depr/AI-API-providers/openai-chat-completions-provider.ts +115 -0
  37. package/src/llm-utils/depr/AI-API-providers/openai-responses-provider.ts +108 -0
  38. package/src/llm-utils/depr/AI-API-providers/types.ts +106 -0
  39. package/src/llm-utils/depr/depr.ts +235 -0
  40. package/src/llm-utils/depr/embeddings.ts +58 -0
  41. package/src/llm-utils/depr/sql-utils.ts +377 -0
  42. package/src/llm-utils/indexes/biologics-index.ts +1098 -0
  43. package/src/llm-utils/indexes/chembl-index.ts +10074 -0
  44. package/src/llm-utils/indexes/dg-repository-index.ts +266 -0
  45. package/src/llm-utils/panel.ts +866 -0
  46. package/src/llm-utils/query-matching.ts +370 -0
  47. package/src/llm-utils/query-meta-utils.ts +106 -0
  48. package/src/llm-utils/script-tools.ts +784 -0
  49. package/src/llm-utils/sql-tools.ts +840 -0
  50. package/src/llm-utils/storage.ts +201 -0
  51. package/src/llm-utils/tableview-tools.ts +704 -0
  52. package/src/llm-utils/ui.ts +315 -0
  53. package/src/package-api.ts +83 -0
  54. package/src/package-test.ts +16 -0
  55. package/src/package.g.ts +122 -0
  56. package/src/package.ts +275 -0
  57. package/src/prompt-engine/chatgpt-assistant.ts +257 -0
  58. package/src/prompt-engine/interfaces.ts +170 -0
  59. package/src/prompt-engine/prompt-engine.ts +52 -0
  60. package/src/prompt-engine/rendering-tools.ts +103 -0
  61. package/src/prompts/is-help-request.ts +26 -0
  62. package/src/utils.ts +174 -0
  63. package/src/viewers-ai.ts +67 -0
  64. package/tsconfig.json +72 -0
  65. package/webpack.config.js +49 -0
@@ -0,0 +1,840 @@
1
+ /* eslint-disable max-len */
2
+ import * as grok from 'datagrok-api/grok';
3
+ import * as ui from 'datagrok-api/ui';
4
+ import * as DG from 'datagrok-api/dg';
5
+ import {getAIAbortSubscription} from '../utils';
6
+ import * as _rxjs from 'rxjs';
7
+ import {SemValueObjectHandler} from '@datagrok-libraries/db-explorer/src/object-handlers';
8
+ import {ChatModel} from 'openai/resources/index';
9
+ import {AIPanelFuncs, MessageType} from './panel';
10
+ import {BuiltinDBInfoMeta, getDBColumnMetaData, getDBTableMetaData} from './query-meta-utils';
11
+ import {ModelOption, ModelType, LLMClient} from './LLM-client';
12
+ import {LanguageModelV3FunctionTool, LanguageModelV3Message} from '@ai-sdk/provider';
13
+ import {findLast} from '../utils';
14
+
15
+
16
+ const suspiciousSQlPatterns = ['DROP ', 'DELETE ', 'UPDATE ', 'INSERT ', 'ALTER ', 'CREATE ', 'TRUNCATE ', 'EXEC ', 'MERGE '];
17
+
18
+ type JsonPrimitive = string | number | boolean | null;
19
+ type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
20
+ type JsonObject = { [key: string]: JsonValue };
21
+
22
+ function isJsonObject(value: JsonValue | object | null | undefined): value is JsonObject {
23
+ return !!value && typeof value === 'object' && !Array.isArray(value);
24
+ }
25
+
26
+ function getStringProp(obj: JsonObject | null | undefined, key: string): string | null {
27
+ const v = obj?.[key];
28
+ return typeof v === 'string' ? v : null;
29
+ }
30
+
31
+ function getStringArrayProp(obj: JsonObject | null | undefined, key: string): string[] {
32
+ const v = obj?.[key];
33
+ if (!Array.isArray(v))
34
+ return [];
35
+ return v.filter((item): item is string => typeof item === 'string');
36
+ }
37
+
38
+ function parseJsonObject(text: string): JsonObject | null {
39
+ try {
40
+ const parsed = JSON.parse(text) as JsonValue;
41
+ return isJsonObject(parsed) ? parsed : null;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Generates SQL query using function calling approach where LLM can explore schema interactively
49
+ * @throws Error if SQL generation fails
50
+ * @param prompt - User's natural language query
51
+ * @param connectionID - Database connection ID
52
+ * @param options - Options including catalogName, old messages, AI panel, etc.
53
+ */
54
+ export async function generateAISqlQueryWithTools(
55
+ prompt: string,
56
+ connectionID: string,
57
+ options: {
58
+ catalogName?: string,
59
+ oldMessages?: MessageType[],
60
+ aiPanel?: AIPanelFuncs<MessageType>,
61
+ modelType?: ModelOption,
62
+ disableVerbose?: boolean,
63
+ } = {}
64
+ ): Promise<string> {
65
+ let aborted = false;
66
+
67
+ options.aiPanel?.addUiMessage(prompt, true);
68
+
69
+ // Load pre-indexed metadata if available
70
+ const connection = await grok.dapi.connections.find(connectionID);
71
+ const allDbInfos = await BuiltinDBInfoMeta.allFromConnection(connection);
72
+ const catalogNames = allDbInfos.map((d) => d.name);
73
+ const defaultCatalog = options.catalogName ??
74
+ connection.parameters?.['catalog'] ??
75
+ connection.parameters?.['db'] ??
76
+ catalogNames[0] ??
77
+ '';
78
+ // Create tool execution context
79
+ const context = new SQLGenerationContext(connectionID, defaultCatalog, allDbInfos, connection);
80
+ const abortSub = getAIAbortSubscription().subscribe(() => {
81
+ aborted = true;
82
+ console.log('Aborting SQL generation as per user request');
83
+ try {
84
+ SQLGenerationContext._lastFc?.cancel();
85
+ SQLGenerationContext._lastFc = null;
86
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
87
+ } catch (_) {
88
+ }
89
+ abortSub.unsubscribe();
90
+ });
91
+ try {
92
+ // Initialize OpenAI client provider
93
+ const langTool = LLMClient.getInstance();
94
+ const modelType = options.modelType ?? 'Fast';
95
+ const client = langTool.aiModels[modelType];
96
+
97
+ // Initial system message
98
+ const systemMessage = `You are an expert SQL query generator. You have access to tools to explore a database schema and generate SQL queries.
99
+
100
+ Your name is Datagrok SQL Expert.
101
+
102
+ WORKFLOW:
103
+ 1. You are provided with the default catalog and available schemas
104
+ 2. Use list_tables_in_schema to see what tables are available in a schema
105
+ 3. Use describe_tables to get detailed column information for relevant tables
106
+ 4. Use list_joins to understand relationships between tables
107
+ 5. Use try_sql to test your generated queries (it returns row count and column names)
108
+ 6. Iterate and refine your query based on test results
109
+ 7. Once satisfied, provide the final SQL query
110
+
111
+ CRITICAL RULES:
112
+ - ALWAYS use list_joins to verify relationships before writing JOIN clauses
113
+ - NEVER assume joins exist based on column name similarity (unless no other option, or explicitly instructed by table/column comments)
114
+ - ONLY use relationships explicitly listed by list_joins
115
+ - ALWAYS Use try_sql to validate your query before finalizing and submitting it
116
+ - Pay attention to semantic types, value ranges, and category values from describe_tables
117
+ - The default database catalog is: ${defaultCatalog}. Use list_catalogs if you need to explore other catalogs.
118
+ - Use list_all_schemas and list_tables_in_schema to discover the database structure before writing queries.
119
+ - ALWAYS prefix table names with schema name in SQL or other functions!!!
120
+ - DO NOT USE 'to' as a table alias
121
+ - If some categorical value is supplied to match (e.g. status value or measurement units), use the information from corresponding column's category values (if any). otherwise, try to use multiple options using OR (for example for micromolar units, try 'uM', 'μM', ets).
122
+ - Some queries might require cartridge use (like RDKIT functions for similarity / substructure search). Use provided query examples and your knowledge of such functions as needed.
123
+ - When working with large tables, try not to use order unless explicitly requested.
124
+ - VERY IMPORTANT: IN some cases, user might want to just get a plain reply without sql query. In such cases, Always begin your response with "REPLY ONLY:"!!!
125
+ - If you fail to generate a valid working query, admit it politely instead of making something up and ask for more information from the user.
126
+ - If the user prompt is ambiguous, ask for clarifications instead of guessing.
127
+ - If user is plainly trying to communicate or chat or ask general questions, use REPLY ONLY mode to answer them appropriately.
128
+ - Use the reply_to_user tool to communicate with the user, explain your reasoning during chain of though and execution and so on.
129
+ When you have the final SQL query ready, respond with ONLY the SQL query text (no markdown, no explanation, no semicolon at the end).`;
130
+
131
+ const input: MessageType[] = options.oldMessages ? [...options.oldMessages] : [];
132
+ const addEngineMessage = (message: MessageType) => {
133
+ options.aiPanel?.addEngineMessage(message);
134
+ };
135
+ if (input.length === 0) {
136
+ // Get initial schema list for the default catalog
137
+ const defaultSchemas = await context.listAllSchemas(defaultCatalog);
138
+ let semTypeWithinPromptInfo = '';
139
+ // try to also match some identifiers within the user prompt to provide even more context
140
+ const parsedPrompt = DG.SemanticValue.parse(prompt);
141
+ if (parsedPrompt?.semType && parsedPrompt.value) {
142
+ // @ts-ignore
143
+ const objHandler = DG.ObjectHandler.list().find((oh) => (oh as SemValueObjectHandler)?.columnName && (oh as SemValueObjectHandler)?.tableName && oh.type === parsedPrompt.semType) as SemValueObjectHandler | undefined;
144
+ if (objHandler) {
145
+ // TODO: remove ts ignores after updating db-explorer library in plugins
146
+ // @ts-ignore
147
+ const [entryPointTable, entryPointColumn] = [objHandler.tableName, objHandler.columnName];
148
+ semTypeWithinPromptInfo = `\n\n Note: The ${parsedPrompt.value} mentioned in the prompt is identified as a ${parsedPrompt.semType} type, typically found in the ${entryPointTable}.${entryPointColumn} column. Use this information to guide your SQL generation.`;
149
+ console.log(semTypeWithinPromptInfo);
150
+ }
151
+ }
152
+
153
+ if (grok.ai.config.indexEntities) {
154
+ const similarQueries = await findSimilarQueriesToPrompt(prompt);
155
+ console.log(`found ${similarQueries.n} similar queries for the prompt`);
156
+ if (similarQueries.n > 0 && similarQueries.text) {
157
+ semTypeWithinPromptInfo += `\n\n Additionally, here are some similar previously executed queries that might help you:
158
+ \n${similarQueries.text}
159
+ `;
160
+ }
161
+ }
162
+
163
+ const systemMsg = langTool.createSystemMessage(systemMessage);
164
+ input.push(systemMsg);
165
+ addEngineMessage(systemMsg);
166
+ const initialUserMsg = langTool.createUserMessage(`
167
+ Default catalog: ${defaultCatalog}\n
168
+ Available catalogs: ${catalogNames.join(', ')}\n\n
169
+ Available schemas in catalog '${defaultCatalog}': ${defaultSchemas.join(', ')}\n\nUser Query: ${prompt}\n\n
170
+ Explore the database using the available tools and generate an SQL query to answer this question.
171
+ ${semTypeWithinPromptInfo}`);
172
+ addEngineMessage(initialUserMsg); // prompt will be shown in UI
173
+ input.push(initialUserMsg);
174
+ } else {
175
+ const followUpUserMsg = langTool.createUserMessage(`User Follow up (do modifications as/if needed based on the following): ${prompt}`);
176
+ input.push(followUpUserMsg);
177
+ addEngineMessage(followUpUserMsg);
178
+ }
179
+
180
+ // Define available tools
181
+ const functionTools: LanguageModelV3FunctionTool[] = [
182
+ {
183
+ type: 'function',
184
+ name: 'list_tables_in_schema',
185
+ description: 'Returns the list of all table names along with their descriptions/comments. Use this to understand what data is available.',
186
+ inputSchema: {
187
+ type: 'object',
188
+ properties: {
189
+ schemaName: {
190
+ type: 'string',
191
+ description: 'Name of the schema to list tables from',
192
+ },
193
+ catalogName: {
194
+ type: 'string',
195
+ description: 'Name of the catalog containing the schema',
196
+ },
197
+ },
198
+ required: ['schemaName', 'catalogName'],
199
+ additionalProperties: false,
200
+ },
201
+ strict: true,
202
+ },
203
+ {
204
+ type: 'function',
205
+ name: 'list_all_schemas',
206
+ description: 'Returns the names of all schemas in the specified catalog.',
207
+ inputSchema: {
208
+ type: 'object',
209
+ properties: {
210
+ catalogName: {
211
+ type: 'string',
212
+ description: 'Name of the catalog to list schemas from',
213
+ },
214
+ },
215
+ required: ['catalogName'],
216
+ additionalProperties: false,
217
+ },
218
+ strict: true,
219
+ },
220
+ {
221
+ type: 'function',
222
+ name: 'list_catalogs',
223
+ description: 'Returns the names of all database catalogs available on this connection. Use this if you need to explore data across different catalogs.',
224
+ inputSchema: {
225
+ type: 'object',
226
+ properties: {},
227
+ required: [],
228
+ additionalProperties: false,
229
+ },
230
+ strict: true,
231
+ },
232
+
233
+ {
234
+ type: 'function',
235
+ name: 'describe_tables',
236
+ description: 'Get detailed information about specific table(s) including all columns, their types, semantic types, comments, value ranges, and category values. Essential for understanding what data is in each table.',
237
+ inputSchema: {
238
+ type: 'object',
239
+ properties: {
240
+ tables: {
241
+ type: 'array',
242
+ items: {type: 'string'},
243
+ description: 'List of table names to describe. Use schema.table format (e.g. public.tableName) or catalog.schema.table format for cross-catalog queries.',
244
+ },
245
+ },
246
+ required: ['tables'],
247
+ additionalProperties: false,
248
+ },
249
+ strict: true,
250
+ },
251
+ {
252
+ type: 'function',
253
+ name: 'list_joins',
254
+ description: 'Lists all foreign key relationships (joins) that involve the specified table(s). CRITICAL: Use this before writing any JOIN clause to verify the relationship exists.',
255
+ inputSchema: {
256
+ type: 'object',
257
+ properties: {
258
+ tables: {
259
+ type: 'array',
260
+ items: {type: 'string'},
261
+ description: 'List of table names to find joins for. Use schema.table or catalog.schema.table format.',
262
+ },
263
+ },
264
+ required: ['tables'],
265
+ additionalProperties: false,
266
+ },
267
+ strict: true,
268
+ },
269
+ {
270
+ type: 'function',
271
+ name: 'try_sql',
272
+ description: 'Execute an SQL query to test it. Returns row count and column names (limited to 10 rows). Use this to validate your query before providing the final answer. If row count is 0, the query might be wrong or the data might genuinely be absent. TRY NOT TO USE ORDER BY in YOUR TEST QUERIES on large tables unless absolutely necessary.',
273
+ inputSchema: {
274
+ type: 'object',
275
+ properties: {
276
+ sql: {
277
+ type: 'string',
278
+ description: 'The SQL query to test (will be automatically limited to 10 rows)',
279
+ },
280
+ description: {
281
+ type: 'string',
282
+ description: 'Short description of what this SQL is trying to achieve in markdown format. This will be put in ui for user context.',
283
+ }
284
+ },
285
+ required: ['sql', 'description'],
286
+ additionalProperties: false,
287
+ },
288
+ strict: true,
289
+ },
290
+ // plain function tool for general purpose question answering
291
+ {
292
+ type: 'function',
293
+ name: 'reply_to_user',
294
+ description: 'Use this tool to esentially communicate with the user directly, give feedback, add context to what you are doing, explain reasoning(!!!) and so on. This is NOT for providing the final SQL query, but rather for intermediate communication. When using this tool, always provide a clear, informative and well formatted (markdown) message to the user in the reply parameter.',
295
+ inputSchema: {
296
+ type: 'object',
297
+ properties: {
298
+ reply: {
299
+ type: 'string',
300
+ description: 'Your text reply to the user question/prompt. this message will be shown in the UI, so make it clear, informative and formatted in markdown as needed.',
301
+ },
302
+ },
303
+ required: ['reply'],
304
+ additionalProperties: false,
305
+ },
306
+ strict: true,
307
+ }
308
+ ];
309
+
310
+ // if we have some embeddings, then also add a tool so that LLM can use it to find similar queries
311
+ if (grok.ai.config.indexEntities) {
312
+ functionTools.push({
313
+ type: 'function',
314
+ name: 'find_similar_queries',
315
+ description: 'Finds existing similar queries based on the prompt you provide (which should be based on user question). Use this to get inspiration from previously executed queries that might be similar to the user question. Return up to 3 similar queries with their descriptions/comments. Similarity is based on LLM embeddings and cosine similarity.',
316
+ inputSchema: {
317
+ type: 'object',
318
+ properties: {
319
+ prompt: {
320
+ type: 'string',
321
+ description: 'prompt derived from user question to find similar queries for',
322
+ },
323
+ },
324
+ required: ['prompt'],
325
+ additionalProperties: false,
326
+ },
327
+ strict: true,
328
+ });
329
+ }
330
+
331
+
332
+ async function findSimilarQueriesToPrompt(aiPrompt: string) {
333
+ try {
334
+ const resultEntities = (await grok.ai.searchEntities(aiPrompt, 0.3, 10, ['DataQuery']))
335
+ .filter((e) => !!e && e instanceof DG.DataQuery && e.connection?.id === connectionID)
336
+ .filter((_, i) => i < 4) as DG.DataQuery[]; // limit to top 4
337
+
338
+ if (resultEntities.length === 0)
339
+ return {text: 'No similar queries found for this connection', n: 0};
340
+ return {text: `Here are some similar previously executed queries that might help you.
341
+ Note that these queries might have annotations/comments like name descriptions and so on that can help you understand the schema better.\n\n
342
+ Here they are:
343
+ ${resultEntities.map((q) => `- Query:\n ${q.query} \n`).join('\n\n')}`, n: resultEntities.length};
344
+ } catch (error) {
345
+ console.error('Error generating embedding for similar query search:', error);
346
+ return {text: 'Error generating embedding for similar query search', n: 0};
347
+ }
348
+ };
349
+
350
+ // Function calling loop
351
+ let iterations = 0;
352
+ let maxIterations = 15; // Prevent infinite loops
353
+
354
+ while (iterations < maxIterations) {
355
+ if (aborted) {
356
+ grok.shell.info('SQL generation aborted by user.');
357
+ return '';
358
+ }
359
+ iterations++;
360
+ console.log(`\n=== Iteration ${iterations} ===`);
361
+ const response = await client.doGenerate({
362
+ prompt: input,
363
+ tools: functionTools,
364
+ providerOptions: {
365
+ openai: {
366
+ ...(ModelType.Coding.startsWith('gpt-5') ? {reasoning: {effort: 'medium'}} : {}),
367
+ }
368
+ }
369
+ });
370
+
371
+ // Fix tool_use input fields - Anthropic expects objects, not strings
372
+ // The AI SDK's doGenerate puts item IDs in providerMetadata, but the
373
+ // Responses API input converter only reads reasoning items from providerOptions
374
+ // (tool-call has a fallback to providerMetadata, but reasoning does not).
375
+ // Copy providerMetadata → providerOptions so reasoning item_references are created.
376
+ const fixedContent = response.content.map((item) => {
377
+ const patched = {
378
+ ...item,
379
+ providerOptions: (item as any).providerOptions ?? (item as any).providerMetadata,
380
+ };
381
+ if (item.type === 'tool-call') {
382
+ return {
383
+ ...patched,
384
+ input: typeof item.input === 'string' ? parseJsonObject(item.input) ?? item.input : item.input
385
+ };
386
+ }
387
+ return patched;
388
+ });
389
+
390
+ const formattedOutput: LanguageModelV3Message = {
391
+ role: 'assistant',
392
+ // @ts-ignore
393
+ content: fixedContent
394
+ };
395
+ //const outputs: MessageType[] = response.content.map((item) => ({role: 'assistant', content: [item]} as MessageType));
396
+ input.push(formattedOutput);
397
+ options.aiPanel?.addEngineMessage(formattedOutput);
398
+
399
+ // Execute function calls (if any)
400
+ let hadToolCalls = false;
401
+ for (const call of response.content.filter((c) => c.type === 'tool-call')) {
402
+ hadToolCalls = true;
403
+
404
+ const functionName = call.toolName;
405
+ const callId = call.toolCallId;
406
+ const rawArgs = call.input ?? '{}';
407
+ const args = parseJsonObject(rawArgs);
408
+
409
+ if (!functionName || !callId) {
410
+ const errorText = 'Error: malformed function call (missing name/call_id).';
411
+ const outputItem = langTool.createToolOutputMessage(callId ?? '', functionName ?? '', errorText);
412
+ if (callId)
413
+ input.push(outputItem);
414
+ if (callId)
415
+ addEngineMessage(outputItem);
416
+ continue;
417
+ }
418
+
419
+ let result = '';
420
+ try {
421
+ switch (functionName) {
422
+ case 'list_catalogs':
423
+ options.aiPanel?.addUiMessage(`📂 Listing all catalogs in the database.`, false);
424
+ result = (await context.listCatalogs()).join(', ');
425
+ !options.disableVerbose && options.aiPanel?.addUiMessage(`✅ Catalogs found: *${result}*`, false);
426
+ break;
427
+ case 'list_all_schemas':
428
+ options.aiPanel?.addUiMessage(`📂 Listing all schemas in catalog *${getStringProp(args, 'catalogName') ?? ''}*.`, false);
429
+ result = (await context.listAllSchemas(getStringProp(args, 'catalogName') ?? defaultCatalog)).join(', ');
430
+ !options.disableVerbose && options.aiPanel?.addUiMessage(`✅ Schemas found: *${result}*`, false);
431
+ break;
432
+ case 'reply_to_user':
433
+ options.aiPanel?.addUiMessage(`💬 ${getStringProp(args, 'reply') ?? ''}`, false);
434
+ result = 'Reply sent to user.';
435
+ break;
436
+ case 'list_tables_in_schema':
437
+ options.aiPanel?.addUiMessage(`📑 Listing all tables in schema *${getStringProp(args, 'schemaName') ?? ''}* (catalog: *${getStringProp(args, 'catalogName') ?? ''}*).`, false);
438
+ const res = await context.listTables(false, getStringProp(args, 'schemaName') ?? '', getStringProp(args, 'catalogName') ?? undefined);
439
+ result = res.description;
440
+ !options.disableVerbose && options.aiPanel?.addUiMessage(res.tableCount ? `✅ Found ${res.tableCount} tables` : '⚠️ No tables found', false);
441
+ break;
442
+ case 'describe_tables': {
443
+ const tables = getStringArrayProp(args, 'tables');
444
+ options.aiPanel?.addUiMessage(`📋 Getting content of following tables: *${tables.join(', ')}*.`, false);
445
+ result = await context.describeTables(tables);
446
+ break;
447
+ }
448
+ case 'list_joins': {
449
+ const tables = getStringArrayProp(args, 'tables');
450
+ options.aiPanel?.addUiMessage(`🔗 Listing relations for tables: *${tables.join(', ')}*.`, false);
451
+ result = await context.listJoins(tables);
452
+ break;
453
+ }
454
+ case 'try_sql': {
455
+ const sql = getStringProp(args, 'sql') ?? '';
456
+ const description = getStringProp(args, 'description') ?? '';
457
+ options.aiPanel?.addUiMessage(`🧪 Testing SQL query:\n${description}\n\`\`\`sql\n${sql}\n\`\`\``, false);
458
+ result = await context.trySql(sql, description);
459
+ !options.disableVerbose && options.aiPanel?.addUiMessage(`📊 SQL Test Result: \n\n${result}`, false);
460
+ break;
461
+ }
462
+ case 'find_similar_queries': {
463
+ options.aiPanel?.addUiMessage(`🔍 Searching for similar queries to help with SQL generation.`, false);
464
+ const similarQueries = await findSimilarQueriesToPrompt(getStringProp(args, 'prompt') ?? '');
465
+ !options.disableVerbose && options.aiPanel?.addUiMessage(similarQueries.n > 0 ? `✅ Found ${similarQueries.n} similar queries.` : `⚠️ ${similarQueries.text}`, false);
466
+ result = similarQueries.text;
467
+ break;
468
+ }
469
+ default:
470
+ result = `Error: Unknown function ${functionName}`;
471
+ }
472
+ } catch (error) {
473
+ const message = error instanceof Error ? error.message : String(error);
474
+ result = `Error executing ${functionName}: ${message}`;
475
+ }
476
+
477
+ console.log(`Result: ${result.substring(0, 200)}${result.length > 200 ? '...' : ''}`);
478
+
479
+ const outputItem = langTool.createToolOutputMessage(callId, functionName, result);
480
+ input.push(outputItem);
481
+ addEngineMessage(outputItem);
482
+ }
483
+
484
+ // If the model called tools, we must continue so it can consume tool outputs.
485
+ if (hadToolCalls) {
486
+ if (iterations >= maxIterations && options.aiPanel) {
487
+ const cont = await options.aiPanel.addConfirmMessage('Maximum iterations reached. Do you want to continue generating the SQL query?');
488
+ if (cont)
489
+ maxIterations += 10; // reset max iterations to continue
490
+ }
491
+ continue;
492
+ }
493
+
494
+ const content = findLast(response.content, (c) => c.type === 'text')?.text!;
495
+ if ((content?.length ?? 0) === 0)
496
+ throw new Error('Model returned no text and no tool calls');
497
+
498
+ console.log('Model response:', content);
499
+
500
+ // Check if this looks like SQL (basic heuristic)
501
+ let sql = content;
502
+ if (sql.startsWith('```sql'))
503
+ sql = sql.substring(6);
504
+ if (sql.startsWith('```'))
505
+ sql = sql.substring(3);
506
+ if (sql.endsWith('```'))
507
+ sql = sql.substring(0, sql.length - 3);
508
+ const contentUpperCase = sql.toUpperCase().trim();
509
+ if (contentUpperCase.length > 2 && (contentUpperCase.startsWith('SELECT') || contentUpperCase.startsWith('WITH'))) {
510
+ // Final SQL detected
511
+ const res = sql.trim().replace(/;+$/, ''); // Remove trailing semicolons
512
+ const resUpperCase = res.toUpperCase();
513
+ if (suspiciousSQlPatterns.some((pattern) => resUpperCase.includes(pattern))) {
514
+ const out = await new Promise<string>((resolve) => {
515
+ ui.dialog('Potentially Destructive SQL Detected')
516
+ .add(ui.divText('The generated SQL query contains potentially destructive commands. For safety, please confirm if you want to proceed with this query.'))
517
+ .add(ui.markdown(`\`\`\`sql\n${res}\n\`\`\``))
518
+ .onOK(() => resolve(res))
519
+ .onCancel(() => {
520
+ console.log('User cancelled execution of potentially destructive SQL');
521
+ resolve('');
522
+ })
523
+ .show();
524
+ });
525
+ options.aiPanel?.addUiMessage(!out ? 'User cancelled execution of potentially destructive SQL.' : 'User confirmed execution of potentially destructive SQL.', false);
526
+ if (out)
527
+ !options.disableVerbose && options.aiPanel?.addUiMessage(`Final SQL Query:\n\`\`\`sql\n${out}\n\`\`\``, false, {finalResult: out});
528
+ return out;
529
+ }
530
+ if (res)
531
+ !options.disableVerbose && options.aiPanel?.addUiMessage(`Final SQL Query:\n\`\`\`sql\n${res}\n\`\`\``, false, {finalResult: res});
532
+ return res;
533
+ } else if (contentUpperCase.startsWith('REPLY ONLY:')) {
534
+ const replyText = contentUpperCase.startsWith('REPLY ONLY:') ? content.substring('REPLY ONLY:'.length).trim() : content;
535
+ options.aiPanel?.addUiMessage(replyText, false);
536
+ } else {
537
+ // Not SQL - add a message to AI to remind it that it needs to provide ONLY SQL Beggining with SELECT or WITH
538
+ const reminderMsg = langTool.createUserMessage('The last response was not a valid SQL query. Please provide ONLY the SQL query text beginning with SELECT or WITH statement, without any explanations or additional text. Remember to prefix table names with schema name.');
539
+ input.push(reminderMsg);
540
+ addEngineMessage(reminderMsg);
541
+ }
542
+ }
543
+ // If we exhausted iterations or didn't get a proper response
544
+ throw new Error('Failed to generate SQL query: Maximum iterations reached or no valid SQL returned');
545
+ } finally {
546
+ abortSub.unsubscribe();
547
+ }
548
+ }
549
+
550
+ /**
551
+ * Context class that manages tool execution for SQL generation.
552
+ * Supports multiple catalogs (e.g. for Databricks) with a default catalog.
553
+ */
554
+ export class SQLGenerationContext {
555
+ private dbInfoMap: Map<string, BuiltinDBInfoMeta> = new Map();
556
+
557
+ constructor(
558
+ private connectionID: string,
559
+ private defaultCatalog: string,
560
+ dbInfos: BuiltinDBInfoMeta[],
561
+ private connection: DG.DataConnection
562
+ ) {
563
+ for (const dbInfo of dbInfos)
564
+ this.dbInfoMap.set(dbInfo.name, dbInfo);
565
+ }
566
+
567
+ private getDbInfo(catalogName?: string): BuiltinDBInfoMeta {
568
+ const name = catalogName ?? this.defaultCatalog;
569
+ const dbInfo = this.dbInfoMap.get(name);
570
+ if (!dbInfo)
571
+ throw new Error(`Catalog '${name}' not found. Available catalogs: ${Array.from(this.dbInfoMap.keys()).join(', ')}`);
572
+ return dbInfo;
573
+ }
574
+
575
+ /**
576
+ * Parses a table reference that may include catalog, schema, and table name.
577
+ * Supports: catalog.schema.table, schema.table, or just table
578
+ */
579
+ private parseTableRef(tableRef: string): {catalog: string, schema: string, table: string} {
580
+ const parts = tableRef.trim().split('.');
581
+ if (parts.length >= 3)
582
+ return {catalog: parts[0], schema: parts[1], table: parts.slice(2).join('.')};
583
+ if (parts.length === 2)
584
+ return {catalog: this.defaultCatalog, schema: parts[0], table: parts[1]};
585
+ return {catalog: this.defaultCatalog, schema: '', table: parts[0]};
586
+ }
587
+
588
+ async listCatalogs(): Promise<string[]> {
589
+ return Array.from(this.dbInfoMap.keys());
590
+ }
591
+
592
+ async listAllSchemas(catalogName?: string): Promise<string[]> {
593
+ return (await this.getDbInfo(catalogName).getSchemas()).map((s) => s.name);
594
+ }
595
+
596
+ /**
597
+ * Tool: list_tables
598
+ * Returns all tables with their descriptions
599
+ */
600
+ async listTables(includeAllDescriptions: boolean, schemaName: string, catalogName?: string): Promise<{description: string, tableCount: number}> {
601
+ const dbInfo = this.getDbInfo(catalogName);
602
+
603
+ const schema = (await dbInfo.getSchemas()).find((s) => s.name === schemaName);
604
+ if (!schema)
605
+ return {description: `Schema ${schemaName} not found in catalog ${catalogName ?? this.defaultCatalog}.`, tableCount: 0};
606
+
607
+ const tables = (await schema.getTables());
608
+ const tableDescs = tables.map((table) => {
609
+ const parts = [`${table.friendlyName ?? table.name}`];
610
+ const tableMeta = getDBTableMetaData(table);
611
+ if (includeAllDescriptions) {
612
+ if (tableMeta?.llmComment)
613
+ parts.push(` LLM Comment: ${tableMeta.llmComment.substring(0, 400)}...`);
614
+ else if (tableMeta.comment)
615
+ parts.push(` Description: ${tableMeta.comment.substring(0, 400)}...`);
616
+ }
617
+ parts.push(` Columns: ${table.columns.length}, ${tableMeta?.rowCount ? `Rows: ${tableMeta.rowCount}` : ''}`);
618
+ return parts.join('\n');
619
+ });
620
+ return {description: `Tables in ${schemaName}:\n\n${tableDescs.join('\n')}`, tableCount: tableDescs.length};
621
+ }
622
+
623
+ /**
624
+ * Tool: describe_tables
625
+ * Returns detailed column information for specified tables.
626
+ * Supports catalog.schema.table and schema.table formats.
627
+ */
628
+ async describeTables(tableNames: string[]): Promise<string> {
629
+ const refs = tableNames.map((t) => this.parseTableRef(t));
630
+ const descriptions: string[] = [];
631
+
632
+ // Group by catalog+schema for efficient fetching
633
+ const groupKey = (r: {catalog: string, schema: string}) => `${r.catalog}\0${r.schema}`;
634
+ const schemaTableCache: Map<string, DG.TableInfo[]> = new Map();
635
+
636
+ for (const key of new Set(refs.map(groupKey))) {
637
+ const [catalog, schema] = key.split('\0');
638
+ try {
639
+ const dbInfo = this.getDbInfo(catalog);
640
+ const schemaInfo = (await dbInfo.getSchemas()).find((s) => s.name === schema);
641
+ if (schemaInfo)
642
+ schemaTableCache.set(key, await schemaInfo.getTables());
643
+ } catch { /* catalog not found */ }
644
+ }
645
+
646
+ for (const ref of refs) {
647
+ const tables = schemaTableCache.get(groupKey(ref));
648
+ if (!tables) {
649
+ descriptions.push(`Schema ${ref.schema} not found in catalog ${ref.catalog}`);
650
+ continue;
651
+ }
652
+ const table = tables.find((t) => t.friendlyName === ref.table || t.name === ref.table);
653
+ if (!table) {
654
+ descriptions.push(`Table ${ref.table} not found in ${ref.schema}`);
655
+ continue;
656
+ }
657
+ descriptions.push(this.buildDetailedTableDescription(table));
658
+ }
659
+
660
+ return descriptions.join('\n\n---\n\n');
661
+ }
662
+
663
+ /**
664
+ * Tool: list_joins
665
+ * Returns all foreign key relationships involving the specified tables.
666
+ * Supports catalog.schema.table and schema.table formats.
667
+ */
668
+ async listJoins(tableNames: string[]): Promise<string> {
669
+ const refs = tableNames.map((t) => this.parseTableRef(t));
670
+
671
+ const schemaQualifiedTableSet = new Set<string>();
672
+ for (const ref of refs)
673
+ schemaQualifiedTableSet.add(`${ref.schema}.${ref.table}`);
674
+
675
+ // Collect unique catalog+schema pairs for efficient relation fetching
676
+ const catalogSchemaMap = new Map<string, Set<string>>();
677
+ for (const ref of refs) {
678
+ if (!catalogSchemaMap.has(ref.catalog))
679
+ catalogSchemaMap.set(ref.catalog, new Set());
680
+ catalogSchemaMap.get(ref.catalog)!.add(ref.schema);
681
+ }
682
+
683
+ const allRelations: DG.DbRelationInfo[] = [];
684
+ for (const [catalog, schemas] of catalogSchemaMap) {
685
+ const dbInfo = this.getDbInfo(catalog);
686
+ for (const schema of schemas) {
687
+ const relations = await dbInfo.getRelationsForSchema(schema);
688
+ allRelations.push(...relations);
689
+ }
690
+ }
691
+
692
+ const filteredRelations = allRelations
693
+ .filter((rel) => schemaQualifiedTableSet.has(`${rel.fromSchema}.${rel.fromTable}`) || schemaQualifiedTableSet.has(`${rel.toSchema}.${rel.toTable}`));
694
+ const joins = filteredRelations.map((rel) => this.buildJoinDescription(rel));
695
+
696
+ if (joins.length === 0)
697
+ return `No foreign key relationships found for tables: ${tableNames.join(', ')}`;
698
+
699
+ return `Foreign key relationships involving ${tableNames.join(', ')}:\n\n${joins.join('\n')}`;
700
+ }
701
+
702
+ static _lastFc: DG.FuncCall | null = null;
703
+ /**
704
+ * Tool: try_sql
705
+ * Executes SQL and returns row count and column names
706
+ */
707
+ async trySql(sql: string, description: string): Promise<string> {
708
+ console.log('trySql called with description:', description);
709
+ try {
710
+ // Add LIMIT if not present
711
+ let testSql = sql.trim();
712
+ if (testSql.endsWith(';'))
713
+ testSql = testSql.substring(0, testSql.length - 1);
714
+ if (!testSql.toUpperCase().includes('LIMIT'))
715
+ testSql += ' LIMIT 10';
716
+
717
+ // Basic safety check to prevent destructive queries
718
+ const upperSql = sql.toUpperCase();
719
+ if (suspiciousSQlPatterns.some((pattern) => upperSql.includes(pattern))) {
720
+ // prompt user confirmation
721
+
722
+ const p = new Promise<boolean>((resolve) => {
723
+ ui.dialog('Confirm SQL Execution')
724
+ .add(ui.divText('Our AI is trying to execute a potentially destructive SQL command. For your safety, please confirm if you want to proceed.'))
725
+ .add(ui.markdown(`\`\`\`sql\n${sql}\n\`\`\``))
726
+ .onOK(() => resolve(true))
727
+ .onCancel(() => resolve(false))
728
+ .show();
729
+ });
730
+ const userConfirmed = await p;
731
+ if (!userConfirmed)
732
+ return 'SQL Execution Not allowed by User: Destructive commands are not allowed. Please revise the query.';
733
+ }
734
+ const queryName = `test-query-${Date.now()}`;
735
+ const wrappedSql = `--name: ${queryName}\n${testSql}`;
736
+
737
+ const fc = this.connection.query(queryName, wrappedSql).prepare({});
738
+ SQLGenerationContext._lastFc = fc;
739
+ await fc.call(false, undefined, {processed: true, report: false});
740
+ const df = await fc.getOutputParamValue();
741
+ SQLGenerationContext._lastFc = null;
742
+ if (!df)
743
+ throw new Error('No data returned');
744
+ const result = [
745
+ `Query executed successfully!`,
746
+ `Row count: ${df.rowCount}`,
747
+ `Columns (${df.columns.length}): ${df.columns.toList().map((c: DG.Column) => `${c.name} (${c.type})`).join(', ')}`,
748
+ ];
749
+
750
+ // If there are rows, show a sample
751
+ if (df.rowCount > 0) {
752
+ const sample = df.columns.toList().map((col: DG.Column) => {
753
+ const val = col.get(0);
754
+ return `${col.name}=${this.formatColValue(val)}`; // save some tokens by formatting (molfiles, images, etc.)
755
+ }).join(', ');
756
+ result.push(`Sample row: ${sample}`);
757
+ }
758
+
759
+ return result.join('\n');
760
+ } catch (error) {
761
+ SQLGenerationContext._lastFc = null;
762
+ const message = error instanceof Error ? error.message : String(error);
763
+ return `SQL Error: ${message}\n\nThis query failed to execute. Please revise the SQL based on the schema information.`;
764
+ }
765
+ }
766
+
767
+ private formatColValue(value: string | number | boolean | null | undefined | object): string {
768
+ if (value === null || value === undefined || value === '' || value === DG.FLOAT_NULL || value === DG.INT_NULL)
769
+ return 'NULL';
770
+ try {
771
+ const valueString = value?.toString();
772
+ return valueString.length > 50 ? `'${valueString.substring(0, 47)}...'` : `'${valueString}'`;
773
+ } catch {
774
+ return 'NON-STRINGIFIABLE-VALUE';
775
+ }
776
+ }
777
+
778
+ /**
779
+ * Helper: Build detailed table description
780
+ */
781
+ private buildDetailedTableDescription(table: DG.TableInfo): string {
782
+ const lines: string[] = [];
783
+ const tableMeta = getDBTableMetaData(table);
784
+ lines.push(`TABLE: ${table.friendlyName ?? table.name} (${tableMeta.rowCount ?? 'Unknown ammount of'} rows)`);
785
+ if (tableMeta.comment)
786
+ lines.push(`Comment: ${tableMeta.comment}`);
787
+ if (tableMeta.llmComment)
788
+ lines.push(`LLM Comment: ${tableMeta.llmComment}`);
789
+
790
+ lines.push('\nColumns:');
791
+
792
+ for (const col of table.columns) {
793
+ const colParts: string[] = [` ${col.name} (${col.type})`];
794
+ const colMeta = getDBColumnMetaData(col);
795
+
796
+
797
+ // not working currently, add back later
798
+ // if (col.semanticType)
799
+ // colParts.push(`[Semantic: ${col.semanticType}]`);
800
+ if (colMeta.isUnique)
801
+ colParts.push('[UNIQUE]');
802
+ if (colMeta.llmComment)
803
+ colParts.push(`- ${colMeta.llmComment}`);
804
+ else if (colMeta.comment)
805
+ colParts.push(`- ${colMeta.comment}`);
806
+ if (colMeta.min !== undefined && colMeta.max !== undefined)
807
+ colParts.push(`Range: ${colMeta.min} to ${colMeta.max}`);
808
+ if ((colMeta.values && colMeta.values.length > 0) || (colMeta.sampleValues && colMeta.sampleValues.length > 0)) {
809
+ const values = (Array.isArray(colMeta.values) ? colMeta.values : undefined) ?? colMeta.sampleValues!;
810
+ colParts.push(`Values: ${values.slice(0, 15).join(', ')}${values.length > 15 ? ', ...' : ''}`);
811
+ }
812
+ if (colMeta.uniqueCount)
813
+ colParts.push(`Unique Values Count: ${colMeta.uniqueCount}`);
814
+
815
+ lines.push(colParts.join(' '));
816
+ }
817
+
818
+ return lines.join('\n');
819
+ }
820
+
821
+ /**
822
+ * Helper: Build join description
823
+ */
824
+ private buildJoinDescription(relation: DG.DbRelationInfo): string {
825
+ const parts: string[] = [];
826
+
827
+ parts.push(`${relation.fromSchema}.${relation.fromTable}(${(relation.fromColumns ?? ['Unknown Column']).join(', ')}) -> ${relation.toSchema}.${relation.toTable}(${(relation.toColumns ?? ['Unknown Column']).join(', ')})`);
828
+
829
+ if (relation.cardinality)
830
+ parts.push(`[${relation.cardinality}]`);
831
+ if (relation.isPrimaryPath === false)
832
+ parts.push('[LEGACY - prefer other paths if available]');
833
+ if (relation.llmComment)
834
+ parts.push(`- ${relation.llmComment}`);
835
+ else if (relation.comment)
836
+ parts.push(`- ${relation.comment}`);
837
+
838
+ return parts.join(' ');
839
+ }
840
+ }