@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,58 @@
|
|
|
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 OpenAI from 'openai';
|
|
6
|
+
// import {LLMClient} from '../LLM-client';
|
|
7
|
+
|
|
8
|
+
// // no longer in use, always use core embeddings instead. keeping code for reference
|
|
9
|
+
|
|
10
|
+
// export async function embedConnectionQueries(connectionId: string) {
|
|
11
|
+
// const queries = (await grok.dapi.queries.filter(`connection.id = "${connectionId}"`).list())
|
|
12
|
+
// .filter((q) => q.query?.trim());
|
|
13
|
+
// const openai = LLMClient.getInstance().openai;
|
|
14
|
+
// const output: {query: string, embedding: number[]}[] = [];
|
|
15
|
+
// const pg = DG.TaskBarProgressIndicator.create('Generating embeddings for queries...');
|
|
16
|
+
// let count = 0;
|
|
17
|
+
// for (const query of queries) {
|
|
18
|
+
// const emb = await getVectorEmbedding(openai, query.query!);
|
|
19
|
+
// output.push({query: query.query!, embedding: emb});
|
|
20
|
+
// count++;
|
|
21
|
+
// pg.update((count / queries.length) * 100, 'Generating embeddings for queries...');
|
|
22
|
+
// }
|
|
23
|
+
// pg.close();
|
|
24
|
+
// return output;
|
|
25
|
+
// }
|
|
26
|
+
|
|
27
|
+
// export async function getVectorEmbedding(openai: OpenAI, text: string): Promise<number[]> {
|
|
28
|
+
// const response = await openai.embeddings.create({
|
|
29
|
+
// model: 'text-embedding-3-small',
|
|
30
|
+
// input: text,
|
|
31
|
+
// });
|
|
32
|
+
// return response.data[0].embedding;
|
|
33
|
+
// }
|
|
34
|
+
|
|
35
|
+
// export function cosineDistance(vecA: number[], vecB: number[]): number {
|
|
36
|
+
// let dotProduct = 0;
|
|
37
|
+
// let normA = 0;
|
|
38
|
+
// let normB = 0;
|
|
39
|
+
// for (let i = 0; i < vecA.length; i++) {
|
|
40
|
+
// dotProduct += vecA[i] * vecB[i];
|
|
41
|
+
// normA += vecA[i] * vecA[i];
|
|
42
|
+
// normB += vecB[i] * vecB[i];
|
|
43
|
+
// }
|
|
44
|
+
// return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
45
|
+
// }
|
|
46
|
+
|
|
47
|
+
// export function getTopKSimilarQueries(textEmbedding: number[],
|
|
48
|
+
// candidates: {query: string, embedding: number[]}[], topK: number, threshold = 0.3): {query: string, score: number}[] {
|
|
49
|
+
// const scores: {query: string, score: number}[] = candidates.map((candidate) => {
|
|
50
|
+
// return {
|
|
51
|
+
// query: candidate.query,
|
|
52
|
+
// score: cosineDistance(textEmbedding, candidate.embedding),
|
|
53
|
+
// };
|
|
54
|
+
// });
|
|
55
|
+
// const out = scores.filter((s) => s.score > threshold);
|
|
56
|
+
// out.sort((a, b) => b.score - a.score);
|
|
57
|
+
// return out.slice(0, topK);
|
|
58
|
+
// }
|
|
@@ -0,0 +1,377 @@
|
|
|
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 {OpenAIHelpClient} from '../openAI-client';
|
|
6
|
+
// import {modelName} from '../../package';
|
|
7
|
+
// import {DBSchemaInfo, DBConnectionMeta, DBTableMeta, DBRelationMeta} from '../db-index-tools';
|
|
8
|
+
// import {JsonSchema} from '../../prompt-engine/interfaces';
|
|
9
|
+
// import {chemblIndex} from '../indexes/chembl-index';
|
|
10
|
+
// import {biologicsIndex} from '../indexes/biologics-index';
|
|
11
|
+
|
|
12
|
+
// // Schema for table selection
|
|
13
|
+
// const TableSelectionSchema: JsonSchema = {
|
|
14
|
+
// type: 'object',
|
|
15
|
+
// properties: {
|
|
16
|
+
// tables: {
|
|
17
|
+
// type: 'array',
|
|
18
|
+
// items: {type: 'string'},
|
|
19
|
+
// description: 'List of table names that are needed to answer the user query',
|
|
20
|
+
// },
|
|
21
|
+
// reasoning: {
|
|
22
|
+
// type: 'string',
|
|
23
|
+
// description: 'Brief explanation of why these tables were selected',
|
|
24
|
+
// },
|
|
25
|
+
// },
|
|
26
|
+
// required: ['tables', 'reasoning'],
|
|
27
|
+
// additionalProperties: false,
|
|
28
|
+
// };
|
|
29
|
+
|
|
30
|
+
// interface TableSelection {
|
|
31
|
+
// tables: string[];
|
|
32
|
+
// reasoning: string;
|
|
33
|
+
// }
|
|
34
|
+
|
|
35
|
+
// /**
|
|
36
|
+
// * Generates an SQL query using a two-step approach:
|
|
37
|
+
// * 1. First, identify relevant tables needed for the query
|
|
38
|
+
// * 2. Then, generate SQL with focused context on those tables
|
|
39
|
+
// * @deprecated in favor of generateAISqlQueryWithTools in sql-tools.ts
|
|
40
|
+
// * @param prompt - User's natural language query
|
|
41
|
+
// * @param connectionID - Database connection ID
|
|
42
|
+
// * @param schemaName - Schema name
|
|
43
|
+
// * @param dbMeta - Optional DBConnectionMeta object with enriched metadata
|
|
44
|
+
// */
|
|
45
|
+
// export async function generateAISqlQuery(
|
|
46
|
+
// prompt: string,
|
|
47
|
+
// connectionID: string,
|
|
48
|
+
// schemaName: string,
|
|
49
|
+
// dbMeta?: DBConnectionMeta
|
|
50
|
+
// ): Promise<string> {
|
|
51
|
+
// // Step 1: Identify relevant tables
|
|
52
|
+
// const connection = await grok.dapi.connections.find(connectionID);
|
|
53
|
+
// if (connection.name.toLowerCase() === 'chembl')
|
|
54
|
+
// dbMeta = chemblIndex;
|
|
55
|
+
// else if (connection.name.toLowerCase() === 'biologics')
|
|
56
|
+
// dbMeta = biologicsIndex;
|
|
57
|
+
// console.log('Step 1: Identifying relevant tables for query...');
|
|
58
|
+
// const tableSelection = await identifyRelevantTables(connectionID, prompt, schemaName, dbMeta);
|
|
59
|
+
// console.log(`Selected tables: ${tableSelection.tables.join(', ')}`);
|
|
60
|
+
// console.log(`Reasoning: ${tableSelection.reasoning}`);
|
|
61
|
+
|
|
62
|
+
// // Step 2: Get focused schema context
|
|
63
|
+
// let focusedContext: FocusedSchemaContext;
|
|
64
|
+
// if (dbMeta)
|
|
65
|
+
// focusedContext = extractFocusedContext(dbMeta, schemaName, tableSelection.tables);
|
|
66
|
+
// else {
|
|
67
|
+
// // Fallback to schema descriptor approach
|
|
68
|
+
// const schema = await DBSchemaInfo.getSchemaInfo(connectionID, schemaName);
|
|
69
|
+
// focusedContext = buildFocusedContextFromDescriptor(schema, tableSelection.tables);
|
|
70
|
+
// }
|
|
71
|
+
|
|
72
|
+
// if (focusedContext.tableInfos.length === 0)
|
|
73
|
+
// throw new Error('No schema information available for selected tables.');
|
|
74
|
+
|
|
75
|
+
// // Step 3: Generate SQL query with focused context
|
|
76
|
+
// console.log('Step 2: Generating SQL query with focused context...');
|
|
77
|
+
// const sqlQuery = await generateSqlWithContext(prompt, schemaName, focusedContext);
|
|
78
|
+
|
|
79
|
+
// if (sqlQuery.startsWith('```sql') && sqlQuery.endsWith('```'))
|
|
80
|
+
// return sqlQuery.substring(6, sqlQuery.length - 3).trim();
|
|
81
|
+
|
|
82
|
+
// return sqlQuery;
|
|
83
|
+
// }
|
|
84
|
+
|
|
85
|
+
// interface FocusedSchemaContext {
|
|
86
|
+
// tableInfos: string[];
|
|
87
|
+
// relationInfos: string[];
|
|
88
|
+
// columnDetails: string[];
|
|
89
|
+
// }
|
|
90
|
+
|
|
91
|
+
// /**
|
|
92
|
+
// * First LLM call: Identify which tables are needed for the query
|
|
93
|
+
// */
|
|
94
|
+
// async function identifyRelevantTables(
|
|
95
|
+
// connectionID: string,
|
|
96
|
+
// prompt: string,
|
|
97
|
+
// schemaName: string,
|
|
98
|
+
// dbMeta?: DBConnectionMeta
|
|
99
|
+
// ): Promise<TableSelection> {
|
|
100
|
+
// const client = OpenAIHelpClient.getInstance();
|
|
101
|
+
|
|
102
|
+
// // Build table overview for selection
|
|
103
|
+
// let tableOverview: string;
|
|
104
|
+
// if (dbMeta) {
|
|
105
|
+
// const schema = dbMeta.schemas.find((s) => s.name === schemaName);
|
|
106
|
+
// if (!schema)
|
|
107
|
+
// throw new Error(`Schema ${schemaName} not found in DBConnectionMeta`);
|
|
108
|
+
|
|
109
|
+
// tableOverview = schema.tables.map((table) => {
|
|
110
|
+
// const parts = [`${table.name}`];
|
|
111
|
+
// if (table.LLMComment) parts.push(` ${table.LLMComment}`);
|
|
112
|
+
// else if (table.comment) parts.push(`- ${table.comment}`);
|
|
113
|
+
// parts.push(` Columns: ${table.columns.map((c) => c.name).join(', ')}`);
|
|
114
|
+
// return parts.join('\n');
|
|
115
|
+
// }).join('\n\n');
|
|
116
|
+
// } else {
|
|
117
|
+
// const schema = await DBSchemaInfo.getSchemaInfo(connectionID, schemaName);
|
|
118
|
+
// tableOverview = schema.tableInfos.join('\n');
|
|
119
|
+
// }
|
|
120
|
+
|
|
121
|
+
// const systemPrompt = `You are a database expert. Given a list of available tables in a database schema, identify which tables are needed to answer the user's query.
|
|
122
|
+
|
|
123
|
+
// Consider:
|
|
124
|
+
// - Direct tables mentioned or implied in the query
|
|
125
|
+
// - Related tables needed for joins (check foreign key relationships)
|
|
126
|
+
// - Intermediate tables required for multi-hop joins
|
|
127
|
+
// - Tables containing relevant attributes even if not explicitly mentioned
|
|
128
|
+
|
|
129
|
+
// Be inclusive but focused - include tables that might be needed, it is much better to have something extra rather than lack it, but avoid including the entire schema unless necessary.`;
|
|
130
|
+
|
|
131
|
+
// const userPrompt = `Schema: ${schemaName}
|
|
132
|
+
|
|
133
|
+
// Available tables:
|
|
134
|
+
// ${tableOverview}
|
|
135
|
+
|
|
136
|
+
// User query: "${prompt}"
|
|
137
|
+
|
|
138
|
+
// Identify which tables are needed to answer this query. Return ONLY the table names (without schema prefix).`;
|
|
139
|
+
|
|
140
|
+
// const response = await client.generalPromptCached(
|
|
141
|
+
// modelName,
|
|
142
|
+
// systemPrompt,
|
|
143
|
+
// userPrompt,
|
|
144
|
+
// TableSelectionSchema
|
|
145
|
+
// );
|
|
146
|
+
|
|
147
|
+
// return JSON.parse(response) as TableSelection;
|
|
148
|
+
// }
|
|
149
|
+
|
|
150
|
+
// /**
|
|
151
|
+
// * Extract focused context from DBConnectionMeta for selected tables
|
|
152
|
+
// */
|
|
153
|
+
// function extractFocusedContext(
|
|
154
|
+
// dbMeta: DBConnectionMeta,
|
|
155
|
+
// schemaName: string,
|
|
156
|
+
// selectedTables: string[]
|
|
157
|
+
// ): FocusedSchemaContext {
|
|
158
|
+
// const schema = dbMeta.schemas.find((s) => s.name === schemaName);
|
|
159
|
+
// if (!schema)
|
|
160
|
+
// throw new Error(`Schema ${schemaName} not found in DBConnectionMeta`);
|
|
161
|
+
|
|
162
|
+
// const tableInfos: string[] = [];
|
|
163
|
+
// const columnDetails: string[] = [];
|
|
164
|
+
// const selectedTableSet = new Set(selectedTables);
|
|
165
|
+
|
|
166
|
+
// // Extract table and column information for selected tables
|
|
167
|
+
// for (const table of schema.tables) {
|
|
168
|
+
// if (!selectedTableSet.has(table.name)) continue;
|
|
169
|
+
|
|
170
|
+
// // Build table info with comments
|
|
171
|
+
// const tableInfo = buildTableInfo(table);
|
|
172
|
+
// tableInfos.push(tableInfo);
|
|
173
|
+
|
|
174
|
+
// // Build detailed column info
|
|
175
|
+
// const colDetail = buildColumnDetails(table);
|
|
176
|
+
// columnDetails.push(colDetail);
|
|
177
|
+
// }
|
|
178
|
+
|
|
179
|
+
// // Extract relevant relations (only between selected tables or involving selected tables)
|
|
180
|
+
// const relationInfos: string[] = [];
|
|
181
|
+
// for (const relation of dbMeta.relations) {
|
|
182
|
+
// if (relation.fromSchema !== schemaName && relation.toSchema !== schemaName)
|
|
183
|
+
// continue;
|
|
184
|
+
|
|
185
|
+
// // Include relation if either table is selected, or if it's a bridge between selected tables
|
|
186
|
+
// const fromSelected = selectedTableSet.has(relation.fromTable);
|
|
187
|
+
// const toSelected = selectedTableSet.has(relation.toTable);
|
|
188
|
+
|
|
189
|
+
// if (fromSelected || toSelected) {
|
|
190
|
+
// // Add the intermediate table if this relation connects to selected tables
|
|
191
|
+
// if (fromSelected && !toSelected)
|
|
192
|
+
// selectedTableSet.add(relation.toTable);
|
|
193
|
+
// else if (!fromSelected && toSelected)
|
|
194
|
+
// selectedTableSet.add(relation.fromTable);
|
|
195
|
+
|
|
196
|
+
// const relInfo = buildRelationInfo(relation);
|
|
197
|
+
// relationInfos.push(relInfo);
|
|
198
|
+
// }
|
|
199
|
+
// }
|
|
200
|
+
|
|
201
|
+
// // Second pass: add any missing tables that were identified as intermediates
|
|
202
|
+
// for (const table of schema.tables) {
|
|
203
|
+
// if (selectedTableSet.has(table.name) && !selectedTables.includes(table.name)) {
|
|
204
|
+
// const tableInfo = buildTableInfo(table);
|
|
205
|
+
// tableInfos.push(tableInfo);
|
|
206
|
+
|
|
207
|
+
// const colDetail = buildColumnDetails(table);
|
|
208
|
+
// columnDetails.push(colDetail);
|
|
209
|
+
// }
|
|
210
|
+
// }
|
|
211
|
+
|
|
212
|
+
// return {tableInfos, relationInfos, columnDetails};
|
|
213
|
+
// }
|
|
214
|
+
|
|
215
|
+
// /**
|
|
216
|
+
// * Build table info string with comments
|
|
217
|
+
// */
|
|
218
|
+
// function buildTableInfo(table: DBTableMeta): string {
|
|
219
|
+
// const columns = table.columns.map((c) => {
|
|
220
|
+
// const parts = [c.name, c.type];
|
|
221
|
+
// if (c.semanticType) parts.push(`sem:${c.semanticType}`);
|
|
222
|
+
// if (c.isUnique) parts.push('UNIQUE');
|
|
223
|
+
// return parts.join(' ');
|
|
224
|
+
// }).join(', ');
|
|
225
|
+
|
|
226
|
+
// const parts = [`${table.name}: (${columns})`];
|
|
227
|
+
// if (table.comment) parts.push(` // ${table.comment}`);
|
|
228
|
+
// if (table.LLMComment) parts.push(` // AI Context: ${table.LLMComment}`);
|
|
229
|
+
|
|
230
|
+
// return parts.join('\n');
|
|
231
|
+
// }
|
|
232
|
+
|
|
233
|
+
// /**
|
|
234
|
+
// * Build detailed column information
|
|
235
|
+
// */
|
|
236
|
+
// function buildColumnDetails(table: DBTableMeta): string {
|
|
237
|
+
// const details = table.columns.map((col) => {
|
|
238
|
+
// const parts = [` ${col.name} (${col.type})`];
|
|
239
|
+
// if (col.LLMComment) parts.push(`- ${col.LLMComment}`);
|
|
240
|
+
// else if (col.comment) parts.push(`- ${col.comment}`);
|
|
241
|
+
// if (col.semanticType) parts.push(`- Semantic type: ${col.semanticType}`);
|
|
242
|
+
// if (col.isUnique) parts.push('- UNIQUE');
|
|
243
|
+
// if (col.min !== undefined && col.max !== undefined)
|
|
244
|
+
// parts.push(`- Range: ${col.min} to ${col.max}`);
|
|
245
|
+
// if (col.categoryValues && col.categoryValues.length > 0) {
|
|
246
|
+
// const values = col.categoryValues.slice(0, 10);
|
|
247
|
+
// parts.push(`- Values: ${values.join(', ')}${col.categoryValues.length > 10 ? '...' : ''}`);
|
|
248
|
+
// }
|
|
249
|
+
// return parts.join(' ');
|
|
250
|
+
// }).join('\n');
|
|
251
|
+
|
|
252
|
+
// return `Table: ${table.name} (${table.rowCount} rows)\n${details}`;
|
|
253
|
+
// }
|
|
254
|
+
|
|
255
|
+
// /**
|
|
256
|
+
// * Build relation info string with cardinality and comments
|
|
257
|
+
// */
|
|
258
|
+
// function buildRelationInfo(relation: DBRelationMeta): string {
|
|
259
|
+
// const relStr = `${relation.fromTable}(${relation.fromColumns.join(', ')}) -> ${relation.toTable}(${relation.toColumns.join(', ')})`;
|
|
260
|
+
// const parts = [relStr];
|
|
261
|
+
|
|
262
|
+
// if (relation.cardinality) parts.push(`[${relation.cardinality}]`);
|
|
263
|
+
// if (relation.IsPrimaryPath === false) parts.push('[LEGACY]');
|
|
264
|
+
// if (relation.LLMComment) parts.push(`// ${relation.LLMComment}`);
|
|
265
|
+
// else if (relation.comment) parts.push(`// ${relation.comment}`);
|
|
266
|
+
|
|
267
|
+
// return parts.join(' ');
|
|
268
|
+
// }
|
|
269
|
+
|
|
270
|
+
// /**
|
|
271
|
+
// * Fallback: Build focused context from schema descriptor (when DBConnectionMeta is not available)
|
|
272
|
+
// */
|
|
273
|
+
// function buildFocusedContextFromDescriptor(
|
|
274
|
+
// schema: {tableInfos: string[]; referenceInfos: string[]},
|
|
275
|
+
// selectedTables: string[]
|
|
276
|
+
// ): FocusedSchemaContext {
|
|
277
|
+
// const selectedTableSet = new Set(selectedTables);
|
|
278
|
+
|
|
279
|
+
// // Filter table infos to only selected tables
|
|
280
|
+
// const tableInfos = schema.tableInfos.filter((info) => {
|
|
281
|
+
// const tableName = info.split(':')[0].trim();
|
|
282
|
+
// return selectedTableSet.has(tableName);
|
|
283
|
+
// });
|
|
284
|
+
|
|
285
|
+
// // Filter references to only those involving selected tables
|
|
286
|
+
// const relationInfos = schema.referenceInfos.filter((ref) => {
|
|
287
|
+
// const [from, to] = ref.split('->').map((s) => s.trim());
|
|
288
|
+
// const fromTable = from.split('.')[0];
|
|
289
|
+
// const toTable = to.split('.')[0];
|
|
290
|
+
// return selectedTableSet.has(fromTable) || selectedTableSet.has(toTable);
|
|
291
|
+
// });
|
|
292
|
+
|
|
293
|
+
// return {
|
|
294
|
+
// tableInfos,
|
|
295
|
+
// relationInfos,
|
|
296
|
+
// columnDetails: [], // Not available in descriptor mode
|
|
297
|
+
// };
|
|
298
|
+
// }
|
|
299
|
+
|
|
300
|
+
// /**
|
|
301
|
+
// * Second LLM call: Generate SQL query with focused context
|
|
302
|
+
// * @deprecated in favor of sql-tools.ts version
|
|
303
|
+
// */
|
|
304
|
+
// async function generateSqlWithContext(
|
|
305
|
+
// prompt: string,
|
|
306
|
+
// schemaName: string,
|
|
307
|
+
// context: FocusedSchemaContext
|
|
308
|
+
// ): Promise<string> {
|
|
309
|
+
// const client = OpenAIHelpClient.getInstance();
|
|
310
|
+
|
|
311
|
+
// const systemPrompt = `You are an expert SQL generator. Given the database schema below, with tables, their columns, types and reference info (foreign keys), write a SQL query for the user question.
|
|
312
|
+
|
|
313
|
+
// CRITICAL JOIN RULES:
|
|
314
|
+
// - ALWAYS follow the foreign key relationships provided in the References section
|
|
315
|
+
// - NEVER create direct joins between tables that don't have a direct foreign key relationship
|
|
316
|
+
// - If table A needs data from table C, but only A->B and B->C relationships exist, you MUST join through B (the intermediate table)
|
|
317
|
+
// - Before writing any JOIN, verify the relationship exists in the References section
|
|
318
|
+
// - DO NOT assume relationships exist between tables based on column name similarity (e.g., user_id in different tables)
|
|
319
|
+
// - ONLY use relationships explicitly listed in the References section
|
|
320
|
+
// - Pay attention to [LEGACY] markers - prefer non-legacy relationships when multiple paths exist
|
|
321
|
+
// - Pay attention to relationship cardinality (one-to-many, many-to-one, etc.) when writing JOINs
|
|
322
|
+
|
|
323
|
+
// QUERY PLANNING PROCESS (follow these steps mentally before writing SQL):
|
|
324
|
+
// 1. Identify all needed tables mentioned in the user question
|
|
325
|
+
// 2. Trace the foreign key path between these tables using ONLY the References section
|
|
326
|
+
// 3. List all intermediate tables needed for joins
|
|
327
|
+
// 4. Verify each join relationship exists in the References section
|
|
328
|
+
// 5. Write the query following this foreign key path
|
|
329
|
+
|
|
330
|
+
// EXAMPLE - Multi-hop join:
|
|
331
|
+
// Question: "Get events for a specific user"
|
|
332
|
+
// CORRECT Path: events -> users_sessions -> users (follow the FK chain through intermediate table)
|
|
333
|
+
// WRONG Path: events -> users (no direct relationship exists - this will fail)
|
|
334
|
+
|
|
335
|
+
// COLUMN SELECTION:
|
|
336
|
+
// - Use column comments and AI context to understand what columns mean
|
|
337
|
+
// - Pay attention to semantic types (e.g., Molecule, Macromolecule) when filtering or selecting
|
|
338
|
+
// - Use category values when filtering on categorical columns
|
|
339
|
+
// - Consider value ranges when writing WHERE clauses
|
|
340
|
+
|
|
341
|
+
// OUTPUT REQUIREMENTS:
|
|
342
|
+
// - Only return one SQL statement
|
|
343
|
+
// - No explanation, no semicolon at the end
|
|
344
|
+
// - No markdown or any extra text
|
|
345
|
+
// - NO \`\`\`sql prefix
|
|
346
|
+
// - ONLY THE SQL AND NOTHING ELSE!!!
|
|
347
|
+
// - DO NOT USE 'to' alias (or any prohibited aliases) for any table
|
|
348
|
+
// - Use aliases as much as possible to shorten the SQL (except for prohibited ones)
|
|
349
|
+
// - When referencing tables, always use the schema name as prefix
|
|
350
|
+
// - Schema name is: ${schemaName}
|
|
351
|
+
// - Make sure the SQL query is nicely formatted for better readability
|
|
352
|
+
|
|
353
|
+
// CRITICAL VALIDATION:
|
|
354
|
+
// - DO NOT MAKE UP TABLES OR COLUMNS THAT DO NOT EXIST IN THE SCHEMA PROVIDED BELOW
|
|
355
|
+
// - DO NOT CREATE JOINS THAT ARE NOT LISTED IN THE REFERENCES SECTION
|
|
356
|
+
// - For each JOIN you write, verify the exact relationship exists in References
|
|
357
|
+
// - If the query is not possible with the given schema and available foreign keys, RETURN: SELECT * FROM ${schemaName}.${context.tableInfos[0]?.split(':')[0] || 'table'} WHERE 1=0
|
|
358
|
+
|
|
359
|
+
// Here is the focused database schema for your query:
|
|
360
|
+
|
|
361
|
+
// Tables:
|
|
362
|
+
// ${context.tableInfos.join('\n')}
|
|
363
|
+
|
|
364
|
+
// ${context.columnDetails.length > 0 ? `\nDetailed Column Information:\n${context.columnDetails.join('\n\n')}` : ''}
|
|
365
|
+
|
|
366
|
+
// References (Foreign Key Relationships - USE ONLY THESE FOR JOINS):
|
|
367
|
+
// ${context.relationInfos.join('\n')}
|
|
368
|
+
|
|
369
|
+
// User prompt:
|
|
370
|
+
// ${prompt}
|
|
371
|
+
|
|
372
|
+
// DO NOT MAKE UP TABLES OR COLUMNS THAT DO NOT EXIST IN THE SCHEMA PROVIDED ABOVE!
|
|
373
|
+
// DO NOT USE 'to' alias (or any prohibited aliases) for any table.
|
|
374
|
+
// MAKE SURE THE SQL QUERY IS NICELY FORMATTED FOR BETTER READABILITY.`;
|
|
375
|
+
|
|
376
|
+
// return await client.generalPromptCached(modelName, '', systemPrompt);
|
|
377
|
+
// }
|