@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.
- package/.eslintignore +2 -0
- package/.eslintrc.json +48 -0
- package/CHANGELOG.md +26 -0
- package/README.md +3 -0
- package/css/ai.css +200 -0
- package/detectors.js +9 -0
- package/dist/package-test.js +1738 -0
- package/dist/package-test.js.map +1 -0
- package/dist/package.js +92488 -0
- package/dist/package.js.map +1 -0
- package/dockerfiles/claude-runtime/.dockerignore +4 -0
- package/dockerfiles/claude-runtime/Dockerfile +27 -0
- package/dockerfiles/claude-runtime/container.json +5 -0
- package/dockerfiles/claude-runtime/package-lock.json +448 -0
- package/dockerfiles/claude-runtime/package.json +20 -0
- package/dockerfiles/claude-runtime/src/server.ts +273 -0
- package/dockerfiles/claude-runtime/src/types.ts +37 -0
- package/dockerfiles/claude-runtime/tsconfig.json +15 -0
- package/dockerfiles/mcp-server/Dockerfile +12 -0
- package/dockerfiles/mcp-server/container.json +1 -0
- package/dockerfiles/mcp-server/package-lock.json +1178 -0
- package/dockerfiles/mcp-server/package.json +15 -0
- package/dockerfiles/mcp-server/src/api-client.ts +100 -0
- package/dockerfiles/mcp-server/src/index.ts +155 -0
- package/dockerfiles/mcp-server/tsconfig.json +13 -0
- package/package.json +126 -0
- package/package.png +0 -0
- package/src/ai-panel.ts +174 -0
- package/src/claude-code/claude-panel.ts +34 -0
- package/src/claude-code/claude-runtime-client.ts +148 -0
- package/src/llm-utils/LLM-client.ts +251 -0
- package/src/llm-utils/combined-search.ts +162 -0
- package/src/llm-utils/creds.ts +30 -0
- package/src/llm-utils/db-index-tools.ts +642 -0
- package/src/llm-utils/deepwikiclient.ts +118 -0
- package/src/llm-utils/depr/AI-API-providers/openai-chat-completions-provider.ts +115 -0
- package/src/llm-utils/depr/AI-API-providers/openai-responses-provider.ts +108 -0
- package/src/llm-utils/depr/AI-API-providers/types.ts +106 -0
- package/src/llm-utils/depr/depr.ts +235 -0
- package/src/llm-utils/depr/embeddings.ts +58 -0
- package/src/llm-utils/depr/sql-utils.ts +377 -0
- package/src/llm-utils/indexes/biologics-index.ts +1098 -0
- package/src/llm-utils/indexes/chembl-index.ts +10074 -0
- package/src/llm-utils/indexes/dg-repository-index.ts +266 -0
- package/src/llm-utils/panel.ts +866 -0
- package/src/llm-utils/query-matching.ts +370 -0
- package/src/llm-utils/query-meta-utils.ts +106 -0
- package/src/llm-utils/script-tools.ts +784 -0
- package/src/llm-utils/sql-tools.ts +840 -0
- package/src/llm-utils/storage.ts +201 -0
- package/src/llm-utils/tableview-tools.ts +704 -0
- package/src/llm-utils/ui.ts +315 -0
- package/src/package-api.ts +83 -0
- package/src/package-test.ts +16 -0
- package/src/package.g.ts +122 -0
- package/src/package.ts +275 -0
- package/src/prompt-engine/chatgpt-assistant.ts +257 -0
- package/src/prompt-engine/interfaces.ts +170 -0
- package/src/prompt-engine/prompt-engine.ts +52 -0
- package/src/prompt-engine/rendering-tools.ts +103 -0
- package/src/prompts/is-help-request.ts +26 -0
- package/src/utils.ts +174 -0
- package/src/viewers-ai.ts +67 -0
- package/tsconfig.json +72 -0
- package/webpack.config.js +49 -0
|
@@ -0,0 +1,370 @@
|
|
|
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 {ChatGPTPromptEngine, GeminiPromptEngine, PromptEngine} from '../prompt-engine/prompt-engine';
|
|
6
|
+
import {_package} from '../package';
|
|
7
|
+
import {dartLike, fireAIAbortEvent} from '../utils';
|
|
8
|
+
import {AIPanelFuncs, MessageType} from './panel';
|
|
9
|
+
import {generateAISqlQueryWithTools} from './sql-tools';
|
|
10
|
+
import {ModelType} from './LLM-client';
|
|
11
|
+
import {JsonSchema} from '../prompt-engine/interfaces';
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
/// Prompt API: https://developer.chrome.com/docs/ai/prompt-api
|
|
15
|
+
/// Enable all Gemini Nano-related flags here:
|
|
16
|
+
/// chrome://flags/#prompt-api-for-gemini-nano
|
|
17
|
+
|
|
18
|
+
let _progress: DG.TaskBarProgressIndicator | null = null;
|
|
19
|
+
|
|
20
|
+
export interface QueryMatchResult {
|
|
21
|
+
searchPattern: string;
|
|
22
|
+
parameters: Record<string, string>;
|
|
23
|
+
confidence: number;
|
|
24
|
+
suggestedConnection?: string | null;
|
|
25
|
+
reasoning?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function geminiDownloadMonitor(m: CreateMonitor) {
|
|
29
|
+
m.addEventListener('downloadprogress', (e) => {
|
|
30
|
+
if (!_progress) {
|
|
31
|
+
grok.shell.info('Gemini model download started. This might take a few minutes.');
|
|
32
|
+
_progress = DG.TaskBarProgressIndicator.create('Downloading Gemini...');
|
|
33
|
+
}
|
|
34
|
+
_progress.update(e.loaded * 100, 'Downloading Gemini...');
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
type PatternQueryMatchResult = {
|
|
39
|
+
searchPattern: string;
|
|
40
|
+
parameters: Record<string, string>;
|
|
41
|
+
confidence: number;
|
|
42
|
+
suggestedConnection?: string | null;
|
|
43
|
+
reasoning?: string;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export async function findBestMatchingQuery(
|
|
47
|
+
question: string,
|
|
48
|
+
): Promise<QueryMatchResult | null> {
|
|
49
|
+
const schema: JsonSchema = {
|
|
50
|
+
type: 'object',
|
|
51
|
+
properties: {
|
|
52
|
+
searchPattern: {type: 'string'},
|
|
53
|
+
parameters: {
|
|
54
|
+
type: 'array',
|
|
55
|
+
description: 'Array of parameter key-value pairs extracted from the search pattern.',
|
|
56
|
+
items: {
|
|
57
|
+
type: 'object',
|
|
58
|
+
properties: {
|
|
59
|
+
key: {type: 'string'},
|
|
60
|
+
value: {type: 'string'},
|
|
61
|
+
},
|
|
62
|
+
required: ['key', 'value'],
|
|
63
|
+
additionalProperties: false,
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
confidence: {type: 'number'},
|
|
67
|
+
suggestedConnection: {type: ['string', 'null']},
|
|
68
|
+
reasoning: {type: 'string'},
|
|
69
|
+
},
|
|
70
|
+
required: ['searchPattern', 'parameters', 'confidence', 'suggestedConnection', 'reasoning'],
|
|
71
|
+
additionalProperties: false,
|
|
72
|
+
} as const;
|
|
73
|
+
const tableQueriesSearchFunctions = DG.Func.find({meta: {searchPattern: null}, returnType: 'dataframe'})
|
|
74
|
+
.filter((f) => f.options['searchPattern']);
|
|
75
|
+
|
|
76
|
+
const searchPatterns = tableQueriesSearchFunctions.map((f) => f.options['searchPattern'] as string);
|
|
77
|
+
const descriptions = tableQueriesSearchFunctions.map((f) => f.description ?? 'No description');
|
|
78
|
+
const connectionIds = tableQueriesSearchFunctions.map((c) => (c instanceof DG.DataQuery) ? c.connection.id ?? 'unknown' : 'unknown');
|
|
79
|
+
const idSet = new Set(connectionIds.filter((id) => id !== 'unknown'));
|
|
80
|
+
const allConnections = await grok.dapi.connections.list();
|
|
81
|
+
const validConnections = allConnections.filter((conn) => idSet.has(conn.id));
|
|
82
|
+
const connections = connectionIds.map((id) => {
|
|
83
|
+
const conn = validConnections.find((c) => c.id === id);
|
|
84
|
+
return conn ? conn.nqName : 'unknown';
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const systemPrompt = `
|
|
88
|
+
You are a precise semantic query matcher with strict validation rules. Your goal is to match user requests to database queries ONLY when you are highly confident.
|
|
89
|
+
|
|
90
|
+
CRITICAL RULES TO PREVENT HALLUCINATION:
|
|
91
|
+
1. NEVER fabricate or guess information not present in the user's request
|
|
92
|
+
2. ONLY match if the user request clearly relates to the query's purpose
|
|
93
|
+
3. Be conservative with confidence scores - use 0.8+ only for clear matches
|
|
94
|
+
4. Parameters MUST be explicitly mentioned or strongly implied in the user's request
|
|
95
|
+
5. Connection names are critical - mismatched connections should significantly lower confidence
|
|
96
|
+
6. If unsure between multiple patterns, choose the more specific one but lower the confidence
|
|
97
|
+
|
|
98
|
+
CONFIDENCE SCORING GUIDE:
|
|
99
|
+
- 0.9-1.0: Perfect semantic match, all parameters clear, connection aligns
|
|
100
|
+
- 0.7-0.89: Good match but minor ambiguity in parameters or connection
|
|
101
|
+
- 0.5-0.69: Weak match, significant uncertainty or missing context
|
|
102
|
+
- Below 0.5: Poor match, should not be used
|
|
103
|
+
|
|
104
|
+
YOUR TASK:
|
|
105
|
+
|
|
106
|
+
STEP 1 — Evaluate each query pattern:
|
|
107
|
+
- Does the user's intent semantically match the query description?
|
|
108
|
+
- Are the required parameters explicitly or clearly implied in the user's request?
|
|
109
|
+
- Does the connection name (if not "unknown") match the user's context?
|
|
110
|
+
- If connection mismatches, reduce confidence significantly
|
|
111
|
+
|
|
112
|
+
STEP 2 — Connection Inference (especially for LOW CONFIDENCE scenarios):
|
|
113
|
+
- Look for ANY clues in the user's request about which data source they might want
|
|
114
|
+
- This includes: explicit database/connection names, domain keywords, data types, or context
|
|
115
|
+
- Be LIBERAL with connection suggestions - it's better to suggest a connection than return null
|
|
116
|
+
- Even if confidence in pattern matching is low, try to infer the most likely connection
|
|
117
|
+
- Match connection names flexibly (e.g., "Northwind", "northwind db", "nw" could all map to Northwind)
|
|
118
|
+
- If multiple connections seem possible, choose the most likely one based on context
|
|
119
|
+
- Only return null for suggestedConnection if there's truly no indication of data source
|
|
120
|
+
|
|
121
|
+
STEP 3 — Extract parameters:
|
|
122
|
+
- Identify parameters in format \${parameterName} from the selected pattern
|
|
123
|
+
- Extract corresponding values ONLY if explicitly stated or clearly implied
|
|
124
|
+
- Use empty string if a parameter cannot be determined
|
|
125
|
+
- Return as array of objects with 'key' (parameter name) and 'value' (extracted value) properties
|
|
126
|
+
|
|
127
|
+
STEP 4 — Provide reasoning:
|
|
128
|
+
- In 1-2 sentences, explain why you chose this pattern and confidence level
|
|
129
|
+
- Mention any concerns or ambiguities
|
|
130
|
+
|
|
131
|
+
OUTPUT REQUIREMENTS:
|
|
132
|
+
- Return ONLY valid JSON matching the exact schema
|
|
133
|
+
- NO markdown, NO backticks, NO code blocks, NO explanations outside JSON
|
|
134
|
+
- ALL required fields must be present: searchPattern, parameters, confidence, suggestedConnection, reasoning
|
|
135
|
+
- Confidence must be a number between 0 and 1
|
|
136
|
+
- suggestedConnection must be a string from the connections list or null
|
|
137
|
+
`;
|
|
138
|
+
|
|
139
|
+
const userPrompt = `
|
|
140
|
+
Available connections (nqNames):
|
|
141
|
+
${Array.from(new Set(connections.filter((c) => c !== 'unknown'))).join(', ')}
|
|
142
|
+
|
|
143
|
+
Available search patterns with metadata:
|
|
144
|
+
${searchPatterns.map((p, i) => `
|
|
145
|
+
Pattern #${i + 1}:
|
|
146
|
+
Description: ${descriptions[i] || 'No description provided'}
|
|
147
|
+
Connection: ${connections[i]}
|
|
148
|
+
Pattern: ${p}
|
|
149
|
+
`).join('\n')}
|
|
150
|
+
|
|
151
|
+
User request:
|
|
152
|
+
"${question}"
|
|
153
|
+
|
|
154
|
+
Analyze the user request and return a JSON object with:
|
|
155
|
+
- searchPattern: the exact pattern string from above (or closest match if confidence is low)
|
|
156
|
+
- parameters: array of objects with 'key' and 'value' properties for extracted parameter values
|
|
157
|
+
- confidence: your confidence score (0 to 1)
|
|
158
|
+
- suggestedConnection: infer the most likely connection from available list (be generous with inference); return null only if truly no clues exist
|
|
159
|
+
- reasoning: brief explanation of your decision, including why you chose/didn't choose a connection
|
|
160
|
+
`;
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
let engine: PromptEngine;
|
|
164
|
+
|
|
165
|
+
const isGeminiAvailable = await ('LanguageModel' in window ? LanguageModel : null)?.availability();
|
|
166
|
+
if (isGeminiAvailable === 'available') {
|
|
167
|
+
_package.logger.info('Using built-in Gemini model for fuzzy matching.');
|
|
168
|
+
engine = GeminiPromptEngine.getInstance(geminiDownloadMonitor);
|
|
169
|
+
} else {
|
|
170
|
+
_package.logger.info('Using GPT engine for fuzzy matching.');
|
|
171
|
+
engine = ChatGPTPromptEngine.getInstance(ModelType.Fast);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const responseText = await engine.generate(userPrompt, systemPrompt, schema);
|
|
175
|
+
|
|
176
|
+
// Robust parsing with validation
|
|
177
|
+
let result: QueryMatchResult;
|
|
178
|
+
try {
|
|
179
|
+
// Remove any potential markdown formatting that might slip through
|
|
180
|
+
const cleanedResponse = responseText
|
|
181
|
+
.replace(/^```json\s*/i, '')
|
|
182
|
+
.replace(/^```\s*/i, '')
|
|
183
|
+
.replace(/```\s*$/i, '')
|
|
184
|
+
.trim();
|
|
185
|
+
|
|
186
|
+
const rawResult = JSON.parse(cleanedResponse) as {
|
|
187
|
+
searchPattern: string;
|
|
188
|
+
parameters: Array<{key: string; value: string}>;
|
|
189
|
+
confidence: number;
|
|
190
|
+
suggestedConnection?: string | null;
|
|
191
|
+
reasoning?: string;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
// Validate required fields
|
|
195
|
+
if (typeof rawResult.searchPattern !== 'string')
|
|
196
|
+
throw new Error('searchPattern must be a string');
|
|
197
|
+
if (!Array.isArray(rawResult.parameters))
|
|
198
|
+
throw new Error('parameters must be an array');
|
|
199
|
+
if (typeof rawResult.confidence !== 'number' || rawResult.confidence < 0 || rawResult.confidence > 1)
|
|
200
|
+
throw new Error('confidence must be a number between 0 and 1');
|
|
201
|
+
if (rawResult.suggestedConnection !== undefined && rawResult.suggestedConnection !== null && typeof rawResult.suggestedConnection !== 'string')
|
|
202
|
+
throw new Error('suggestedConnection must be a string or null');
|
|
203
|
+
if (rawResult.reasoning !== undefined && typeof rawResult.reasoning !== 'string')
|
|
204
|
+
throw new Error('reasoning must be a string');
|
|
205
|
+
|
|
206
|
+
// Convert array format to Record format
|
|
207
|
+
const parametersRecord: Record<string, string> = {};
|
|
208
|
+
for (const param of rawResult.parameters) {
|
|
209
|
+
if (typeof param.key !== 'string' || typeof param.value !== 'string')
|
|
210
|
+
throw new Error('Each parameter must have string key and value properties');
|
|
211
|
+
parametersRecord[param.key] = param.value;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
result = {
|
|
215
|
+
searchPattern: rawResult.searchPattern,
|
|
216
|
+
parameters: parametersRecord,
|
|
217
|
+
confidence: rawResult.confidence,
|
|
218
|
+
suggestedConnection: rawResult.suggestedConnection ?? null,
|
|
219
|
+
reasoning: rawResult.reasoning ?? 'No reasoning provided',
|
|
220
|
+
};
|
|
221
|
+
} catch (parseError) {
|
|
222
|
+
_package.logger.error(`Failed to parse LLM response: ${parseError}. Response was: ${responseText}`);
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
_package.logger.info(`Match found with confidence ${result.confidence}. Reasoning: ${result.reasoning}`);
|
|
227
|
+
if (result.suggestedConnection)
|
|
228
|
+
_package.logger.info(`Suggested connection: ${result.suggestedConnection}`);
|
|
229
|
+
|
|
230
|
+
return result;
|
|
231
|
+
} catch (error) {
|
|
232
|
+
_package.logger.error(`Error finding best function: ${error}`);
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export async function tableQueriesFunctionsSearchLlm(s: string): Promise<DG.Widget> {
|
|
238
|
+
const tvWidgeFunc = DG.Func.find({name: 'getFuncTableViewWidget'})[0];
|
|
239
|
+
if (!tvWidgeFunc)
|
|
240
|
+
return DG.Widget.fromRoot(ui.divText('Power Pack plugin not installed'));
|
|
241
|
+
try {
|
|
242
|
+
const tableQueriesSearchFunctions = DG.Func.find({meta: {searchPattern: null}, returnType: 'dataframe'})
|
|
243
|
+
.filter((f) => f.options['searchPattern']);
|
|
244
|
+
const matches: PatternQueryMatchResult | null = JSON.parse(await grok.functions
|
|
245
|
+
.call('ChatGPT:findMatchingPatternQuery', {prompt: s}));
|
|
246
|
+
|
|
247
|
+
if (!matches)
|
|
248
|
+
return DG.Widget.fromRoot(ui.divText('Unable to process query. Please try rephrasing.'));
|
|
249
|
+
|
|
250
|
+
_package.logger.info(`Match result - Confidence: ${matches.confidence}, Reasoning: ${matches.reasoning || 'N/A'}`);
|
|
251
|
+
|
|
252
|
+
if (matches.confidence > 0.7 && matches.searchPattern && matches.parameters) {
|
|
253
|
+
console.log(`Function matched with high confidence ${matches.confidence}`);
|
|
254
|
+
const sf = tableQueriesSearchFunctions.find((f) => {
|
|
255
|
+
const pattern: string = removeTrailingQuotes(f.options['searchPattern']) ?? '';
|
|
256
|
+
return pattern === matches.searchPattern;
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
if (sf) {
|
|
260
|
+
const widget = await tvWidgeFunc.apply({func: sf, inputParams: matches.parameters});
|
|
261
|
+
return widget;
|
|
262
|
+
}
|
|
263
|
+
_package.logger.warning(`Pattern ${matches.searchPattern} not found in available functions`);
|
|
264
|
+
} else {
|
|
265
|
+
console.info(`Low confidence (${matches.confidence}). ${matches.reasoning || 'No suitable match found.'}`);
|
|
266
|
+
|
|
267
|
+
// If there's a suggested connection, provide helpful feedback
|
|
268
|
+
if (matches.suggestedConnection && matches.suggestedConnection.includes(':')) {
|
|
269
|
+
const nqNameSplit = matches.suggestedConnection.split(':');
|
|
270
|
+
const connection = await grok.dapi.connections.filter(`namespace = "${nqNameSplit[0]}:" and shortName = "${nqNameSplit[1]}"`).first();
|
|
271
|
+
if (!connection) {
|
|
272
|
+
return DG.Widget.fromRoot(ui.divText(
|
|
273
|
+
`Low confidence match. Your query seems related to connection "${matches.suggestedConnection}", ` +
|
|
274
|
+
`but the connection was not found. Please refine your query with more specific details.`
|
|
275
|
+
));
|
|
276
|
+
}
|
|
277
|
+
return runQueryAIprompt(s, connection, tvWidgeFunc);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return DG.Widget.fromRoot(ui.divText(
|
|
281
|
+
'No matching query or connection found. Please try rephrasing your request or check available query patterns.'
|
|
282
|
+
));
|
|
283
|
+
}
|
|
284
|
+
} catch (error) {
|
|
285
|
+
console.error('Error calling ChatGPT:findMatchingPatternQuery', error);
|
|
286
|
+
return DG.Widget.fromRoot(ui.divText(`Error during AI-powered table query search. Check console for details.`));
|
|
287
|
+
}
|
|
288
|
+
return DG.Widget.fromRoot(ui.divText('No matching query found via AI'));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function runQueryAIprompt(userPrompt: string, connection: DG.DataConnection, tvWidgetFunc: DG.Func): DG.Widget {
|
|
292
|
+
const outputDiv = ui.divV([
|
|
293
|
+
ui.h2(`Looks like you are trying to query the "${connection.name}" database`),
|
|
294
|
+
ui.divText('Your prompt did not match any known query patterns.'),
|
|
295
|
+
ui.divText('Would you like me to help you construct a query?'),
|
|
296
|
+
ui.button('Generate Query', async () => {
|
|
297
|
+
await runPrompt();
|
|
298
|
+
})
|
|
299
|
+
], {style: {width: '100%', height: '100%'}});
|
|
300
|
+
const outputWidget = DG.Widget.fromRoot(outputDiv);
|
|
301
|
+
const abort = () => {
|
|
302
|
+
fireAIAbortEvent();
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
const dummyAIPanelFuncs: AIPanelFuncs<MessageType> = {
|
|
307
|
+
addUserMessage: (_aiMsg: any, _msg: string) => {},
|
|
308
|
+
addAIMessage: (_aiMsg: any, _title: string, _msg: string) => {},
|
|
309
|
+
addEngineMessage: (_aiMsg: any) => {},
|
|
310
|
+
addUiMessage: (msg: string, fromUser: boolean, _messageOptions?: any) => {
|
|
311
|
+
if (!fromUser)
|
|
312
|
+
ui.setUpdateIndicator(outputDiv, true, msg.substring(0, 40) + (msg.length > 40 ? '...' : ''), abort);
|
|
313
|
+
},
|
|
314
|
+
addConfirmMessage: (_msg?: string) => Promise.resolve(true),
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
async function runPrompt() {
|
|
318
|
+
try {
|
|
319
|
+
ui.setUpdateIndicator(outputDiv, true, 'Generating query...', abort);
|
|
320
|
+
const sqlResult = await generateAISqlQueryWithTools(
|
|
321
|
+
userPrompt,
|
|
322
|
+
connection.id!,
|
|
323
|
+
{
|
|
324
|
+
aiPanel: dummyAIPanelFuncs,
|
|
325
|
+
modelType: 'Deep Research',
|
|
326
|
+
disableVerbose: true
|
|
327
|
+
}
|
|
328
|
+
);
|
|
329
|
+
ui.setUpdateIndicator(outputDiv, false);
|
|
330
|
+
if (sqlResult && sqlResult.trim().length > 0) {
|
|
331
|
+
const queryFunc = connection.query(userPrompt, sqlResult);
|
|
332
|
+
const outWidget = await tvWidgetFunc.apply({func: queryFunc, inputParams: {}});
|
|
333
|
+
if (!outWidget)
|
|
334
|
+
throw new Error('Failed to generate widget from AI query');
|
|
335
|
+
// replace the output div content with the result widget
|
|
336
|
+
outputDiv.replaceWith(outWidget.root);
|
|
337
|
+
setTimeout(() => {
|
|
338
|
+
const plusIcon = outWidget.root.querySelector('.d4-dialog-header .grok-icon.fal.fa-plus');
|
|
339
|
+
if (!plusIcon)
|
|
340
|
+
return;
|
|
341
|
+
const editIcon = ui.icons.edit(() => {
|
|
342
|
+
setTimeout(() => {
|
|
343
|
+
const qf = connection.query(userPrompt, sqlResult);
|
|
344
|
+
const v = DG.DataQueryView.create(qf);
|
|
345
|
+
grok.shell.addView(v);
|
|
346
|
+
// grok.shell.v = av;
|
|
347
|
+
});
|
|
348
|
+
}, 'Edit query');
|
|
349
|
+
dartLike(editIcon.style).set('fontSize', '14px').set('width', '20px');
|
|
350
|
+
plusIcon.parentNode?.insertBefore(editIcon, plusIcon);
|
|
351
|
+
}, 1000);
|
|
352
|
+
} else
|
|
353
|
+
grok.shell.error('No SQL query was generated from the prompt. Please try rephrasing your request.');
|
|
354
|
+
} catch (error: any) {
|
|
355
|
+
ui.setUpdateIndicator(outputDiv, false);
|
|
356
|
+
grok.shell.error(`Error during AI query generation`);
|
|
357
|
+
console.error('Error during AI query generation:', error);
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
return outputWidget;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function removeTrailingQuotes(s: string): string {
|
|
364
|
+
let ms = s;
|
|
365
|
+
if (s.startsWith('"') || s.startsWith('\''))
|
|
366
|
+
ms = ms.substring(1);
|
|
367
|
+
if (s.endsWith('"') || s.endsWith('\''))
|
|
368
|
+
ms = ms.substring(0, ms.length - 1);
|
|
369
|
+
return ms;
|
|
370
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
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 {DBSchemaInfo} from './db-index-tools';
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* a subclass of DG.DbInfo that adds support for built-in DB relations that might not be indexed yet
|
|
10
|
+
*/
|
|
11
|
+
export class BuiltinDBInfoMeta extends DG.DbInfo {
|
|
12
|
+
constructor(dart: any) {
|
|
13
|
+
super(dart);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
public static async fromConnection(connection: DG.DataConnection, catalog?: string): Promise<BuiltinDBInfoMeta> {
|
|
17
|
+
const dbInfos = await grok.data.db.getInfo(connection, catalog ?? null);
|
|
18
|
+
if (dbInfos.length === 0)
|
|
19
|
+
throw new Error(`No database info found for connection '${connection.name}'${catalog ? ` and catalog '${catalog}'` : ''}`);
|
|
20
|
+
return new BuiltinDBInfoMeta(dbInfos[0].dart);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
public static async allFromConnection(connection: DG.DataConnection): Promise<BuiltinDBInfoMeta[]> {
|
|
24
|
+
const dbInfos = await grok.data.db.getInfo(connection);
|
|
25
|
+
return dbInfos.map((d) => new BuiltinDBInfoMeta(d.dart));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
private _cachedRelations: Map<string, DG.DbRelationInfo[]> = new Map();
|
|
29
|
+
async getRelationsForSchema(schemaName: string): Promise<DG.DbRelationInfo[]> {
|
|
30
|
+
if (this._cachedRelations.has(schemaName))
|
|
31
|
+
return this._cachedRelations.get(schemaName)!;
|
|
32
|
+
// for dbs without schemas, return all relations
|
|
33
|
+
const annotatedRelations: DG.DbRelationInfo[] = (await super.getRelations())
|
|
34
|
+
.filter((rel) => (!rel.fromSchema && !rel.toSchema) ||
|
|
35
|
+
(rel.fromSchema == schemaName || rel.toSchema == schemaName));
|
|
36
|
+
|
|
37
|
+
this._cachedRelations.set(schemaName, annotatedRelations);
|
|
38
|
+
// this._relations = annotatedRelations;
|
|
39
|
+
const annotatedRelationsSet = new Set<string>();
|
|
40
|
+
annotatedRelations.forEach((rel) => {
|
|
41
|
+
annotatedRelationsSet.add(`${rel.fromSchema}.${rel.fromTable}.${(rel.fromColumns ?? []).join(',')}->${rel.toSchema}.${rel.toTable}.${(rel.toColumns ?? []).join(',')}`);
|
|
42
|
+
});
|
|
43
|
+
// collect builtin relations here and add to _relations. remove this chunk in future once everything is indexed
|
|
44
|
+
const conInfo = await DBSchemaInfo.getSchemaInfo(this.connection.id, schemaName);
|
|
45
|
+
conInfo.descriptor.references
|
|
46
|
+
.forEach((ref) => {
|
|
47
|
+
const f = ref.from.split('.');
|
|
48
|
+
const t = ref.to.split('.');
|
|
49
|
+
const ft = f[0];
|
|
50
|
+
const fc = f[1];
|
|
51
|
+
const tt = t[0];
|
|
52
|
+
const tc = t[1];
|
|
53
|
+
if (annotatedRelationsSet.has(`${schemaName}.${ft}.${fc}->${schemaName}.${tt}.${tc}`))
|
|
54
|
+
return;
|
|
55
|
+
const meta = new BuiltinRelationMeta(
|
|
56
|
+
schemaName,
|
|
57
|
+
ft,
|
|
58
|
+
[fc],
|
|
59
|
+
schemaName,
|
|
60
|
+
tt,
|
|
61
|
+
[tc],
|
|
62
|
+
);
|
|
63
|
+
annotatedRelations.push(meta);
|
|
64
|
+
});
|
|
65
|
+
return annotatedRelations;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
class BuiltinRelationMeta implements DG.DbRelationInfo {
|
|
70
|
+
get comment() {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
get llmComment() {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
get cardinality() {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
dart: any = null;
|
|
81
|
+
get connection(): DG.DataConnection {
|
|
82
|
+
throw new Error('Method not implemented.');
|
|
83
|
+
}
|
|
84
|
+
get isPrimaryPath(): boolean {
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
constructor(
|
|
88
|
+
public fromSchema: string,
|
|
89
|
+
public fromTable: string,
|
|
90
|
+
public fromColumns: string[],
|
|
91
|
+
public toSchema: string,
|
|
92
|
+
public toTable: string,
|
|
93
|
+
public toColumns: string[],
|
|
94
|
+
) {
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function getDBTableMetaData(table: DG.TableInfo): DG.DbTableProperties {
|
|
99
|
+
const props: (keyof DG.DbTableProperties)[] = ['comment', 'llmComment', 'domains', 'rowCount'];
|
|
100
|
+
return Object.fromEntries(props.map((key) => ([key, table.tags.get(key) ?? undefined])));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function getDBColumnMetaData(column: DG.ColumnInfo): DG.DbColumnProperties {
|
|
104
|
+
const props: (keyof DG.DbColumnProperties)[] = ['comment', 'llmComment', 'isUnique', 'min', 'max', 'values', 'sampleValues', 'uniqueCount'];
|
|
105
|
+
return Object.fromEntries(props.map((key) => ([key, column.tags.get(key) ?? undefined])));
|
|
106
|
+
}
|