@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,642 @@
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 {getSchemaDescriptor} from '@datagrok-libraries/db-explorer/src/utils';
6
+ import {LLMClient} from './LLM-client';
7
+ import {JsonSchema} from '../prompt-engine/interfaces';
8
+
9
+ type DBIDWithSchema = `${string}.${string}`;
10
+ type DBReference = `${string}.${string} -> ${string}.${string}`;
11
+ type SchemaInfo = {
12
+ tableInfos: string[];
13
+ referenceInfos: DBReference[];
14
+ descriptor: Awaited<ReturnType<typeof getSchemaDescriptor>>;
15
+ }
16
+ export class DBSchemaInfo {
17
+ private static _cache: Map<DBIDWithSchema, SchemaInfo> = new Map();
18
+
19
+ static async getSchemaInfo(connectionID: string, schemaName: string): Promise<SchemaInfo> {
20
+ const cacheKey: DBIDWithSchema = `${connectionID}.${schemaName}`;
21
+ if (this._cache.has(cacheKey))
22
+ return this._cache.get(cacheKey)!;
23
+ const schemaDescriptor = await getSchemaDescriptor(connectionID, schemaName);
24
+ const tableInfos: string[] = [];
25
+ const referenceInfos: DBReference[] = [];
26
+ for (const [tableName, tableInfo] of Object.entries(schemaDescriptor.tables))
27
+ tableInfos.push(`${tableName}: (${Object.entries(tableInfo.columns).map(([colName, colType]) => `${colName} (${colType})`).join(', ')})`);
28
+ for (const ref of schemaDescriptor.references)
29
+ referenceInfos.push(`${ref.from} -> ${ref.to}`);
30
+ const schemaInfo: SchemaInfo = {tableInfos, referenceInfos, descriptor: schemaDescriptor};
31
+ this._cache.set(cacheKey, schemaInfo);
32
+ return schemaInfo;
33
+ }
34
+ }
35
+
36
+ export type CommentedEntity = {
37
+ comment?: string;
38
+ LLMComment?: string;
39
+ }
40
+ export type DBColumnMeta = CommentedEntity & {
41
+ name: string;
42
+ table: string;
43
+ schema: string;
44
+ type: string;
45
+ semanticType?: string; // for example molecule, macromolecule, curve, etc.
46
+ isUnique?: boolean;
47
+ min?: number;
48
+ max?: number;
49
+ categoryValues?: string[]; // if less than 100, list them all
50
+ uniqueValueCount?: number;
51
+ };
52
+
53
+ export type DBTableMeta = CommentedEntity & {
54
+ name: string;
55
+ schema: string;
56
+ columns: DBColumnMeta[];
57
+ domains?: string[]; // list of domain names that are related to this table
58
+ rowCount: number;
59
+ }
60
+ export type DBSchemaMeta = CommentedEntity & {
61
+ name: string;
62
+ tables: DBTableMeta[];
63
+ };
64
+
65
+ export type DBConnectionMeta = CommentedEntity & {
66
+ name: string;
67
+ schemas: DBSchemaMeta[];
68
+ relations: DBRelationMeta[];
69
+ };
70
+
71
+
72
+ export type DBRelationMeta = CommentedEntity & {
73
+ fromSchema: string;
74
+ fromTable: string;
75
+ fromColumns: string[];
76
+ toSchema: string;
77
+ toTable: string;
78
+ toColumns: string[];
79
+ cardinality?: typeof DG.DbRelationInfo.prototype.cardinality;
80
+ // comment // from DB FK comment if exists
81
+ // LLMComment // "Each activity belongs to one assay; one assay has many activities"
82
+ IsPrimaryPath?: boolean // recommended join vs weird legacy join
83
+ }
84
+
85
+ async function getTableLength(connection: DG.DataConnection, schemaName: string, tableName: string): Promise<number> {
86
+ const sql = `--name: count-query \n
87
+ SELECT COUNT(*) AS cnt FROM ${schemaName}.${tableName}`;
88
+ const df = await connection.query('count-query', sql).apply({});
89
+ return df.get('cnt', 0) as number;
90
+ }
91
+
92
+ async function get100TableSample(connection: DG.DataConnection, schemaName: string, tableName: string): Promise<DG.DataFrame> {
93
+ const sql = `--name: sample-query \n
94
+ SELECT * FROM ${schemaName}.${tableName} LIMIT 100`;
95
+ return await connection.query('sample-query', sql).apply({});
96
+ }
97
+
98
+ async function getColumnMinMax(connection: DG.DataConnection, schemaName: string, tableName: string, columnName: string): Promise<{min: number; max: number}> {
99
+ const sql = `--name: min-max-query \n
100
+ SELECT MIN(${columnName}) AS min_val, MAX(${columnName}) AS max_val FROM ${schemaName}.${tableName}`;
101
+ const df = await connection.query('min-max-query', sql).apply({});
102
+ return {min: df.get('min_val', 0) as number, max: df.get('max_val', 0) as number};
103
+ }
104
+
105
+ async function getMax100CategoryValues(connection: DG.DataConnection, schemaName: string, tableName: string, columnName: string): Promise<string[] | undefined> {
106
+ const sql = `--name: category-values-query \n
107
+ SELECT DISTINCT ${columnName} AS catVals FROM ${schemaName}.${tableName} LIMIT 102`;
108
+ const df: DG.DataFrame = await connection.query('category-values-query', sql).apply({});
109
+ if (df.rowCount > 100) // too many unique values
110
+ return undefined;
111
+ const values = df.col('catVals')?.toList().map((a) => a?.toString() || 'null') as string[];
112
+ if (values.length === 0 || values.some((v) => v.length > 100)) // there might be some big text values, skip those
113
+ return undefined;
114
+ return values;
115
+ }
116
+
117
+ async function getIsColumnUnique(connection: DG.DataConnection, schemaName: string, tableName: string, columnName: string, totalRowCount: number): Promise<boolean> {
118
+ const sql = `--name: unique-count-query \n
119
+ SELECT COUNT(DISTINCT ${columnName}) AS unique_count FROM ${schemaName}.${tableName}`;
120
+ const df = await connection.query('unique-count-query', sql).apply({});
121
+ const uniqueCount = df.get('unique_count', 0) as number;
122
+ return uniqueCount === totalRowCount;
123
+ }
124
+
125
+
126
+ /**
127
+ * Indexes the whole connection for LLM usage
128
+ * Pass empty schemas array to index all schemas
129
+ * @param connection
130
+ * @param schemas
131
+ */
132
+ export async function genDBConnectionMeta(connection: DG.DataConnection, schemas: string[]) {
133
+ const out: DBConnectionMeta = {
134
+ name: connection.name,
135
+ schemas: [],
136
+ relations: [],
137
+ };
138
+
139
+ const allSchemaNames = await grok.dapi.connections.getSchemas(connection);
140
+ const schemaNames = schemas.length > 0 ? schemas : allSchemaNames;
141
+ console.log(`Indexing schemas: ${schemaNames.join(', ')}`);
142
+ for (const schemaName of schemaNames) {
143
+ console.log(`Indexing schema: ${schemaName}`);
144
+ console.log('Fetching schema descriptor...');
145
+ const dbSchemaDescriptor = (await DBSchemaInfo.getSchemaInfo(connection.id, schemaName)).descriptor;
146
+ // first, fill in the relations data that is already there
147
+ const relations = out.relations;
148
+ for (const ref of dbSchemaDescriptor.references) {
149
+ const [fromTable, fromCol] = ref.from.split('.');
150
+ const [toTable, toCol] = ref.to.split('.');
151
+ relations.push({
152
+ fromSchema: schemaName,
153
+ fromTable,
154
+ fromColumns: [fromCol],
155
+ toSchema: schemaName,
156
+ toTable,
157
+ toColumns: [toCol],
158
+ }); // we will handle cardinality later using LLM and querying the data
159
+ }
160
+ console.log(`Indexed ${relations.length} relations.`);
161
+
162
+
163
+ const tables = Object.keys(dbSchemaDescriptor.tables);
164
+ const schemaMeta: DBSchemaMeta = {
165
+ name: schemaName,
166
+ tables: [],
167
+ };
168
+ console.log(`Indexing ${tables.length} tables...`);
169
+ for (const tableName of tables) {
170
+ console.log(`Indexing table: ${tableName}`);
171
+ // query for row count
172
+ const rowCount = await getTableLength(connection, schemaName, tableName);
173
+ const tableMeta: DBTableMeta = {
174
+ name: tableName,
175
+ schema: schemaName,
176
+ columns: [],
177
+ rowCount,
178
+ };
179
+ // get table sample, detect semtypes
180
+ const tableSample = await get100TableSample(connection, schemaName, tableName);
181
+ await tableSample.meta.detectSemanticTypes();
182
+ console.log(`Indexing ${tableSample.columns.length} columns...`);
183
+ for (const col of tableSample.columns) {
184
+ const colMeta: DBColumnMeta = {
185
+ name: col.name,
186
+ table: tableName,
187
+ schema: schemaName,
188
+ type: dbSchemaDescriptor.tables[tableName]?.columns[col.name] || col.type, // should be always present
189
+ };
190
+ if (rowCount <= 1_000_000) {
191
+ // get min/max for numeric columns
192
+ if (col.isNumerical && col.type !== DG.COLUMN_TYPE.DATE_TIME) {
193
+ const {min, max} = await getColumnMinMax(connection, schemaName, tableName, col.name);
194
+ colMeta.min = min;
195
+ colMeta.max = max;
196
+ } else if (col.isCategorical && !dbSchemaDescriptor.tables[tableName]?.columns[col.name]?.toLowerCase().startsWith('timestamp')) { // we have a bug with timestamps
197
+ const catValues = await getMax100CategoryValues(connection, schemaName, tableName, col.name);
198
+ if (catValues)
199
+ colMeta.categoryValues = catValues;
200
+ }
201
+ if (rowCount > 0) {
202
+ // check if unique
203
+ const isUnique = await getIsColumnUnique(connection, schemaName, tableName, col.name, rowCount);
204
+ colMeta.isUnique = isUnique;
205
+ }
206
+ } else
207
+ console.log(`Skipping detailed indexing for column ${col.name} in table ${tableName} due to large row count (${rowCount}).`);
208
+
209
+
210
+ // get semantic type
211
+ if (col.semType)
212
+ colMeta.semanticType = col.semType;
213
+ tableMeta.columns.push(colMeta);
214
+ }
215
+ schemaMeta.tables.push(tableMeta);
216
+ }
217
+ console.log(`Finished indexing schema: ${schemaName}`);
218
+ out.schemas.push(schemaMeta);
219
+ }
220
+
221
+ //NB: Uncomment the following lines to enable LLM-based post-processing of DB metadata
222
+ //const enrichedMeta = await postProcessDBConnectionMeta(out, 'gpt-4o-mini');
223
+ //return enrichedMeta;
224
+ return out;
225
+ }
226
+
227
+ // Helper schemas for structured LLM output
228
+ const ConnectionCommentSchema: JsonSchema = {
229
+ type: 'object',
230
+ properties: {
231
+ comment: {type: 'string', description: 'Brief overview of the database purpose and domain'},
232
+ LLMComment: {type: 'string', description: 'AI-friendly description of database structure and usage patterns'},
233
+ },
234
+ required: ['comment', 'LLMComment'],
235
+ additionalProperties: false,
236
+ };
237
+
238
+ const SchemaCommentSchema: JsonSchema = {
239
+ type: 'object',
240
+ properties: {
241
+ comment: {type: 'string', description: 'Brief description of schema purpose'},
242
+ LLMComment: {type: 'string', description: 'AI-friendly description for query generation'},
243
+ },
244
+ required: ['comment', 'LLMComment'],
245
+ additionalProperties: false,
246
+ };
247
+
248
+ const TableCommentSchema: JsonSchema = {
249
+ type: 'object',
250
+ properties: {
251
+ comment: {type: 'string', description: 'Brief table description'},
252
+ LLMComment: {type: 'string', description: 'AI-friendly description with domain context'},
253
+ },
254
+ required: ['comment', 'LLMComment'],
255
+ additionalProperties: false,
256
+ };
257
+
258
+ const ColumnCommentsSchema: JsonSchema = {
259
+ type: 'object',
260
+ properties: {
261
+ columns: {
262
+ type: 'array',
263
+ items: {
264
+ type: 'object',
265
+ properties: {
266
+ name: {type: 'string'},
267
+ comment: {type: 'string', description: 'Brief column description or empty if self-evident'},
268
+ LLMComment: {type: 'string', description: 'AI-friendly description or empty if self-evident'},
269
+ },
270
+ required: ['name', 'comment', 'LLMComment'],
271
+ additionalProperties: false,
272
+ },
273
+ },
274
+ },
275
+ required: ['columns'],
276
+ additionalProperties: false,
277
+ };
278
+
279
+ const RelationCommentSchema: JsonSchema = {
280
+ type: 'object',
281
+ properties: {
282
+ comment: {type: 'string', description: 'Brief relation description'},
283
+ LLMComment: {type: 'string', description: 'Natural language explanation (e.g., "Each activity belongs to one assay")'},
284
+ cardinality: {type: 'string', enum: ['one-to-one', 'one-to-many', 'many-to-one', 'many-to-many']},
285
+ IsPrimaryPath: {type: 'boolean', description: 'Is this a recommended join vs legacy join'},
286
+ },
287
+ required: ['comment', 'LLMComment', 'cardinality', 'IsPrimaryPath'],
288
+ additionalProperties: false,
289
+ };
290
+
291
+ const HiddenRelationsSchema: JsonSchema = {
292
+ type: 'object',
293
+ properties: {
294
+ hiddenRelations: {
295
+ type: 'array',
296
+ items: {
297
+ type: 'object',
298
+ properties: {
299
+ fromSchema: {type: 'string'},
300
+ fromTable: {type: 'string'},
301
+ fromColumns: {type: 'array', items: {type: 'string'}},
302
+ toSchema: {type: 'string'},
303
+ toTable: {type: 'string'},
304
+ toColumns: {type: 'array', items: {type: 'string'}},
305
+ comment: {type: 'string'},
306
+ LLMComment: {type: 'string'},
307
+ cardinality: {type: 'string', enum: ['one-to-one', 'one-to-many', 'many-to-one', 'many-to-many']},
308
+ IsPrimaryPath: {type: 'boolean'},
309
+ },
310
+ required: ['fromSchema', 'fromTable', 'fromColumns', 'toSchema', 'toTable', 'toColumns', 'comment', 'LLMComment', 'cardinality'],
311
+ additionalProperties: false,
312
+ },
313
+ },
314
+ },
315
+ required: ['hiddenRelations'],
316
+ additionalProperties: false,
317
+ };
318
+
319
+ /**
320
+ * Post-processes DB metadata by enriching it with LLM-generated comments and insights
321
+ * @param connectionMeta - The raw connection metadata
322
+ * @param openAIModel - The OpenAI model to use (e.g., 'gpt-4o')
323
+ */
324
+ export async function postProcessDBConnectionMeta(connectionMeta: DBConnectionMeta, openAIModel: string): Promise<DBConnectionMeta> {
325
+ const llmClient = LLMClient.getInstance();
326
+ const result = {...connectionMeta};
327
+
328
+ // Step 1: Generate connection-level comment
329
+ console.log('Generating connection-level comment...');
330
+ const connectionOverview = generateConnectionOverview(result);
331
+ const connectionCommentResponse = await llmClient.generalPromptCached(
332
+ openAIModel,
333
+ 'You are a database documentation expert. Generate concise, informative descriptions for database connections.',
334
+ `Database: ${result.name}\n\n${connectionOverview}\n\nGenerate a brief overview (comment) and an AI-friendly description (LLMComment) that helps AI models understand this database's purpose and structure.`,
335
+ ConnectionCommentSchema
336
+ );
337
+ const connectionComment = JSON.parse(connectionCommentResponse);
338
+ result.comment = connectionComment.comment;
339
+ result.LLMComment = connectionComment.LLMComment;
340
+
341
+ // Step 2: Process each schema
342
+ for (const schema of result.schemas) {
343
+ console.log(`Processing schema: ${schema.name}`);
344
+
345
+ // Generate schema comment
346
+ const schemaOverview = generateSchemaOverview(schema);
347
+ const schemaCommentResponse = await llmClient.generalPromptCached(
348
+ openAIModel,
349
+ 'You are a database documentation expert. Generate concise schema descriptions.',
350
+ `Schema: ${schema.name}\n\n${schemaOverview}\n\nGenerate a brief description and AI-friendly context.`,
351
+ SchemaCommentSchema
352
+ );
353
+ const schemaComment = JSON.parse(schemaCommentResponse);
354
+ schema.comment = schemaComment.comment;
355
+ schema.LLMComment = schemaComment.LLMComment;
356
+
357
+ // Step 3: Process tables in batches (to provide context)
358
+ for (const table of schema.tables) {
359
+ console.log(`Processing table: ${table.name}`);
360
+
361
+ // Generate table comment with full context
362
+ const tableContext = generateTableContext(table, schema);
363
+ const tableCommentResponse = await llmClient.generalPromptCached(
364
+ openAIModel,
365
+ 'You are a database documentation expert. Generate table descriptions that help AI understand the domain.',
366
+ `Table: ${schema.name}.${table.name}\n\n${tableContext}\n\nGenerate a brief description and AI-friendly context explaining this table's role.`,
367
+ TableCommentSchema
368
+ );
369
+ const tableComment = JSON.parse(tableCommentResponse);
370
+ table.comment = tableComment.comment;
371
+ table.LLMComment = tableComment.LLMComment;
372
+
373
+ // Step 4: Generate column comments (batch processing for efficiency)
374
+ const columnContext = generateColumnContext(table);
375
+ const columnCommentsResponse = await llmClient.generalPromptCached(
376
+ openAIModel,
377
+ `You are a database documentation expert. For each column, generate a brief description.
378
+ If a column is self-evident (like 'id' in a table named 'users' -> 'User ID'), you can use a very short description or leave empty strings.
379
+ Focus on non-obvious columns, semantic types, and domain-specific meanings.`,
380
+ `Table: ${schema.name}.${table.name}\n\n${columnContext}\n\nFor each column, provide comment and LLMComment. Leave both empty if the column is completely self-evident.`,
381
+ ColumnCommentsSchema
382
+ );
383
+ const columnComments = JSON.parse(columnCommentsResponse);
384
+
385
+ // Apply column comments
386
+ for (const colComment of columnComments.columns) {
387
+ const col = table.columns.find((c) => c.name === colComment.name);
388
+ if (col) {
389
+ col.comment = colComment.comment || undefined;
390
+ col.LLMComment = colComment.LLMComment || undefined;
391
+ }
392
+ }
393
+ }
394
+ }
395
+
396
+ // Step 5: Process relations
397
+ console.log('Processing relations...');
398
+ const relationsContext = generateRelationsContext(result);
399
+ for (let i = 0; i < result.relations.length; i++) {
400
+ const relation = result.relations[i];
401
+ const relationContext = `${relation.fromSchema}.${relation.fromTable}(${relation.fromColumns.join(', ')}) -> ${relation.toSchema}.${relation.toTable}(${relation.toColumns.join(', ')})`;
402
+
403
+ const relationCommentResponse = await llmClient.generalPromptCached(
404
+ openAIModel,
405
+ `You are a database expert. Analyze foreign key relationships and provide:
406
+ 1. Brief comment
407
+ 2. Natural language explanation (e.g., "Each assay_result belongs to one assay; one assay has many assay_results")
408
+ 3. Cardinality (one-to-one, one-to-many, many-to-one, many-to-many)
409
+ 4. Whether this is a primary/recommended join path (true) or a legacy/unusual join (false)`,
410
+ `Relation: ${relationContext}\n\nDatabase context:\n${relationsContext}\n\nAnalyze this relationship.`,
411
+ RelationCommentSchema
412
+ );
413
+ const relationComment = JSON.parse(relationCommentResponse);
414
+ relation.comment = relationComment.comment;
415
+ relation.LLMComment = relationComment.LLMComment;
416
+ relation.cardinality = relationComment.cardinality;
417
+ relation.IsPrimaryPath = relationComment.IsPrimaryPath;
418
+ }
419
+
420
+ // Step 6: Discover hidden relations
421
+ console.log('Discovering hidden relations...');
422
+ const hiddenRelationsResponse = await llmClient.generalPromptCached(
423
+ openAIModel,
424
+ `You are a database expert. Analyze the database schema and identify potential "hidden" relationships that are not defined as foreign keys but could be logically joined.
425
+ Examples:
426
+ - Tables with similar column names (e.g., user_id in different tables)
427
+ - Semantic relationships (e.g., name fields that could match)
428
+ - Domain-specific relationships
429
+
430
+ Only suggest high-confidence relationships that would be useful for queries. Return empty array if no hidden relations are found.`,
431
+ `Database: ${result.name}\n\nSchemas and tables:\n${generateHiddenRelationsContext(result)}\n\nIdentify any hidden relationships.`,
432
+ HiddenRelationsSchema
433
+ );
434
+ const hiddenRelations = JSON.parse(hiddenRelationsResponse);
435
+
436
+ // Add hidden relations to the result
437
+ if (hiddenRelations.hiddenRelations && hiddenRelations.hiddenRelations.length > 0) {
438
+ result.relations.push(...hiddenRelations.hiddenRelations);
439
+ console.log(`Discovered ${hiddenRelations.hiddenRelations.length} hidden relations`);
440
+ }
441
+
442
+ return result;
443
+ }
444
+
445
+ // Helper functions to generate context strings
446
+
447
+ function generateConnectionOverview(conn: DBConnectionMeta): string {
448
+ const schemaCount = conn.schemas.length;
449
+ const tableCount = conn.schemas.reduce((sum, s) => sum + s.tables.length, 0);
450
+ const relationCount = conn.relations.length;
451
+
452
+ return `Schemas: ${schemaCount}, Tables: ${tableCount}, Relations: ${relationCount}
453
+ Schema names: ${conn.schemas.map((s) => s.name).join(', ')}`;
454
+ }
455
+
456
+ function generateSchemaOverview(schema: DBSchemaMeta): string {
457
+ const tableNames = schema.tables.map((t) => t.name).join(', ');
458
+ return `Tables (${schema.tables.length}): ${tableNames}`;
459
+ }
460
+
461
+ function generateTableContext(table: DBTableMeta, schema: DBSchemaMeta): string {
462
+ const colNames = table.columns.map((c) => `${c.name} (${c.type})`).join(', ');
463
+ const relatedTables = schema.tables
464
+ .filter((t) => t.name !== table.name)
465
+ .map((t) => t.name)
466
+ .join(', ');
467
+
468
+ return `Row count: ${table.rowCount}
469
+ Columns: ${colNames}
470
+ Other tables in schema: ${relatedTables}`;
471
+ }
472
+
473
+ function generateColumnContext(table: DBTableMeta): string {
474
+ const columnDetails = table.columns.map((col) => {
475
+ const parts = [`${col.name}: ${col.type}`];
476
+ if (col.semanticType) parts.push(`semantic: ${col.semanticType}`);
477
+ if (col.isUnique) parts.push('unique');
478
+ if (col.min !== undefined) parts.push(`range: ${col.min}-${col.max}`);
479
+ if (col.categoryValues) parts.push(`categories: ${col.categoryValues.slice(0, 5).join(', ')}${col.categoryValues.length > 5 ? '...' : ''}`);
480
+ return parts.join(', ');
481
+ }).join('\n');
482
+
483
+ return `Table: ${table.name} (${table.rowCount} rows)\nColumns:\n${columnDetails}`;
484
+ }
485
+
486
+ function generateRelationsContext(conn: DBConnectionMeta): string {
487
+ // Provide overview of all tables and their columns for context
488
+ const tablesOverview = conn.schemas.flatMap((schema) =>
489
+ schema.tables.map((table) =>
490
+ `${schema.name}.${table.name}: ${table.columns.map((c) => `${c.name}(${c.type})`).join(', ')}`
491
+ )
492
+ ).join('\n');
493
+
494
+ return `Tables in database:\n${tablesOverview}`;
495
+ }
496
+
497
+ function generateHiddenRelationsContext(conn: DBConnectionMeta): string {
498
+ // Generate a compact representation of all tables and columns
499
+ const context = conn.schemas.flatMap((schema) =>
500
+ schema.tables.map((table) => {
501
+ const cols = table.columns.map((c) => {
502
+ const parts = [c.name, c.type];
503
+ if (c.semanticType) parts.push(`sem:${c.semanticType}`);
504
+ if (c.isUnique) parts.push('unique');
505
+ return parts.join(':');
506
+ }).join(', ');
507
+ return `${schema.name}.${table.name} [${cols}]`;
508
+ })
509
+ ).join('\n');
510
+
511
+ // Also include existing relations for reference
512
+ const existingRels = conn.relations.map((r) =>
513
+ `${r.fromSchema}.${r.fromTable}(${r.fromColumns.join(',')}) -> ${r.toSchema}.${r.toTable}(${r.toColumns.join(',')})`
514
+ ).join('\n');
515
+
516
+ return `${context}\n\nExisting relations:\n${existingRels}`;
517
+ }
518
+
519
+
520
+ /**
521
+ * ############################################################################################################################################
522
+ * Up until now is the code for meta generation and post-processing using LLMs
523
+ * ###########################################################################################################################################
524
+ * Bellow is tool to upload these annotations to the sticky meta :3
525
+ */
526
+
527
+ export async function moveDBMetaToStickyMetaOhCoolItEvenRhymes(connectionMeta: DBConnectionMeta) {
528
+ const connection = await grok.dapi.connections.filter(`name="${connectionMeta.name}"`).first();
529
+ if (!connection)
530
+ throw new Error(`Connection ${connectionMeta.name} not found`);
531
+ const dbInfo = (await grok.data.db.getInfo(connection))[0];
532
+
533
+ await dbInfo.clearProperties();
534
+ console.log(`Cleared existing metadata for connection ${connectionMeta.name}`);
535
+ // connection-level comments
536
+ if (connectionMeta.comment) {
537
+ await failable('Setting connection comment', async () => {
538
+ await dbInfo.setComment(connectionMeta.comment!);
539
+ });
540
+ }
541
+ if (connectionMeta.LLMComment) {
542
+ await failable('Setting connection LLMComment', async () => {
543
+ await dbInfo.setLlmComment(connectionMeta.LLMComment!);
544
+ });
545
+ }
546
+ // relation-level annotations
547
+ const relations = connectionMeta.relations ?? [];
548
+
549
+ for (const rel of relations) {
550
+ await failable(`adding relation ${rel.fromSchema}.${rel.fromTable} -> ${rel.toSchema}.${rel.toTable}`, async () => {
551
+ await dbInfo.addRelation(rel.fromTable, rel.fromColumns, rel.toTable, rel.toColumns, {
552
+ fromSchema: rel.fromSchema,
553
+ toSchema: rel.toSchema,
554
+ comment: rel.comment,
555
+ llmComment: rel.LLMComment,
556
+ cardinality: rel.cardinality,
557
+ isPrimaryPath: rel.IsPrimaryPath,
558
+ });
559
+ });
560
+ }
561
+ const schemas = await dbInfo.getSchemas();
562
+ for (const schemaMeta of connectionMeta.schemas) {
563
+ const dbSchema = schemas.find((s) => s.name === schemaMeta.name);
564
+ if (!dbSchema) {
565
+ console.warn(`Schema ${schemaMeta.name} not found in connection ${connectionMeta.name}, skipping`);
566
+ continue;
567
+ }
568
+ // schema-level comments
569
+ if (schemaMeta.comment) {
570
+ await failable(`Setting schema ${schemaMeta.name} comment`, async () => {
571
+ await dbSchema.setComment(schemaMeta.comment!);
572
+ });
573
+ }
574
+ if (schemaMeta.LLMComment) {
575
+ await failable(`Setting schema ${schemaMeta.name} LLMComment`, async () => {
576
+ await dbSchema.setLlmComment(schemaMeta.LLMComment!);
577
+ });
578
+ }
579
+ // moving to tables
580
+ const tables = await dbSchema.getTables();
581
+ for (const tableMeta of schemaMeta.tables) {
582
+ const dbTable = tables.find((t) => t.friendlyName === tableMeta.name || t.name === tableMeta.name);
583
+ if (!dbTable) {
584
+ console.warn(`Table ${tableMeta.name} not found in schema ${schemaMeta.name}, skipping`);
585
+ continue;
586
+ }
587
+ // table-level comments
588
+
589
+ await failable(`Setting table ${schemaMeta.name}.${tableMeta.name} annotations`, async () => {
590
+ await dbSchema.annotateTable(dbTable, removeUndefinesFromObject({
591
+ comment: tableMeta.comment,
592
+ llmComment: tableMeta.LLMComment,
593
+ domains: tableMeta.domains?.join(',') ?? undefined,
594
+ rowCount: tableMeta.rowCount ?? undefined,
595
+ }));
596
+ });
597
+ // move to columns
598
+ const columns = dbTable.columns;
599
+ for (const columnMeta of tableMeta.columns) {
600
+ const dbColumn = columns.find((c) => c.name === columnMeta.name);
601
+ if (!dbColumn) {
602
+ console.warn(`Column ${columnMeta.name} not found in table ${tableMeta.name}, skipping`);
603
+ continue;
604
+ }
605
+ await failable(`Setting column ${schemaMeta.name}.${tableMeta.name}.${columnMeta.name} annotations`, async () => {
606
+ await dbSchema.annotateColumn(dbTable, dbColumn, removeUndefinesFromObject({
607
+ comment: columnMeta.comment ?? undefined,
608
+ llmComment: columnMeta.LLMComment ?? undefined,
609
+ isUnique: columnMeta.isUnique ?? undefined,
610
+ sampleValues: columnMeta.categoryValues?.slice(0, 10) ?? undefined,
611
+ values: columnMeta.categoryValues ?? undefined,
612
+ max: columnMeta.max ?? undefined,
613
+ min: columnMeta.min ?? undefined,
614
+ uniqueCount: columnMeta.uniqueValueCount ?? undefined,
615
+ }));
616
+ });
617
+ }
618
+ }
619
+ }
620
+ console.log(`Finished moving metadata to sticky meta for connection ${connectionMeta.name}`);
621
+ }
622
+
623
+ async function failable(desc: string, f: () => Promise<void>) {
624
+ try {
625
+ console.log(desc);
626
+ await f();
627
+ console.log(`${desc} - done`);
628
+ return;
629
+ } catch (e) {
630
+ console.error('Failable function error:', e);
631
+ return null;
632
+ }
633
+ }
634
+
635
+ function removeUndefinesFromObject<T>(obj: T): T {
636
+ const keys = Object.keys(obj as Object) as (keyof T)[];
637
+ for (const key of keys) {
638
+ if (obj[key] == undefined)
639
+ delete obj[key];
640
+ }
641
+ return obj;
642
+ }