@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,704 @@
|
|
|
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 {ModelOption, ModelType, LLMClient} from './LLM-client';
|
|
6
|
+
import {ChatModel} from 'openai/resources/shared';
|
|
7
|
+
import {findLast, getAIAbortSubscription} from '../utils';
|
|
8
|
+
import {AIPanelFuncs, MessageType} from './panel';
|
|
9
|
+
import {LLMCredsManager} from './creds';
|
|
10
|
+
import {LanguageModelV3, LanguageModelV3FunctionTool, LanguageModelV3Message} from '@ai-sdk/provider';
|
|
11
|
+
|
|
12
|
+
type JsonPrimitive = string | number | boolean | null;
|
|
13
|
+
type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
|
|
14
|
+
type JsonObject = { [key: string]: JsonValue };
|
|
15
|
+
|
|
16
|
+
type ViewerProps = Record<string, JsonValue>;
|
|
17
|
+
|
|
18
|
+
function isJsonObject(value: JsonValue | object | null | undefined): value is JsonObject {
|
|
19
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function getStringProp(obj: JsonObject | null | undefined, key: string): string | null {
|
|
23
|
+
const v = obj?.[key];
|
|
24
|
+
return typeof v === 'string' ? v : null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function getNumberProp(obj: JsonObject | null | undefined, key: string): number | null {
|
|
28
|
+
const v = obj?.[key];
|
|
29
|
+
return typeof v === 'number' ? v : null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function parseJsonObject(text: string): JsonObject | null {
|
|
33
|
+
try {
|
|
34
|
+
const parsed = JSON.parse(text) as JsonValue;
|
|
35
|
+
return isJsonObject(parsed) ? parsed : null;
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Handles AI-assisted table view interactions with ask and agent modes
|
|
43
|
+
* @throws Error if processing fails
|
|
44
|
+
* @param prompt - User's natural language query
|
|
45
|
+
* @param tableView - The table view to work with
|
|
46
|
+
* @param mode - 'ask' for highlighting elements or 'agent' for full viewer manipulation
|
|
47
|
+
* @param options - Additional options including message history and AI panel functions
|
|
48
|
+
*/
|
|
49
|
+
export async function processTableViewAIRequest(
|
|
50
|
+
prompt: string,
|
|
51
|
+
tableView: DG.TableView,
|
|
52
|
+
options: {
|
|
53
|
+
oldMessages?: MessageType[],
|
|
54
|
+
aiPanel?: AIPanelFuncs<MessageType>,
|
|
55
|
+
modelType?: ModelOption,
|
|
56
|
+
} = {}
|
|
57
|
+
): Promise<void> {
|
|
58
|
+
let aborted = false;
|
|
59
|
+
// Create tool execution context
|
|
60
|
+
const context = new TableViewContext(tableView);
|
|
61
|
+
const abortSub = getAIAbortSubscription().subscribe(() => {
|
|
62
|
+
aborted = true;
|
|
63
|
+
console.log('Aborting table view AI processing as per user request');
|
|
64
|
+
abortSub.unsubscribe();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
// Initialize OpenAI client
|
|
69
|
+
const langTool = LLMClient.getInstance();
|
|
70
|
+
const modelType = options.modelType ?? 'Fast';
|
|
71
|
+
const client = langTool.aiModels[modelType];
|
|
72
|
+
// Always use agent mode workflow with conditional system prompt
|
|
73
|
+
await processAgentMode(client, langTool, prompt, context, options, () => aborted);
|
|
74
|
+
} finally {
|
|
75
|
+
abortSub.unsubscribe();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Unified agent workflow with conditional system prompt based on mode
|
|
81
|
+
*/
|
|
82
|
+
async function processAgentMode(
|
|
83
|
+
client: LanguageModelV3,
|
|
84
|
+
langTool: LLMClient,
|
|
85
|
+
prompt: string,
|
|
86
|
+
context: TableViewContext,
|
|
87
|
+
options: {
|
|
88
|
+
oldMessages?: MessageType[],
|
|
89
|
+
aiPanel?: AIPanelFuncs<MessageType>,
|
|
90
|
+
modelType?: ModelOption
|
|
91
|
+
},
|
|
92
|
+
isAborted: () => boolean,
|
|
93
|
+
): Promise<void> {
|
|
94
|
+
let maxIterations = 15;
|
|
95
|
+
let iterations = 0;
|
|
96
|
+
|
|
97
|
+
const vectorStoreId = LLMCredsManager.getVectorStoreId();
|
|
98
|
+
|
|
99
|
+
// Conditional system prompt based on mode
|
|
100
|
+
const systemMessage =
|
|
101
|
+
`You are Datagrok Table View Assistant, an expert in data visualization and analysis using Datagrok viewers.
|
|
102
|
+
|
|
103
|
+
Your name is Datagrok Table View Assistant.
|
|
104
|
+
|
|
105
|
+
WORKFLOW:
|
|
106
|
+
1. You have access to the current table structure and available viewer types
|
|
107
|
+
2. Use describe_viewer to understand viewer properties before adding/modifying
|
|
108
|
+
3. Use add_viewer to create new visualizations
|
|
109
|
+
4. Use adjust_viewer to modify existing viewers (if you know the ID) or find_viewers_by_type to find viewer IDs
|
|
110
|
+
5. Use list_current_viewers to see what's currently displayed
|
|
111
|
+
6. Iterate and refine based on user feedback
|
|
112
|
+
|
|
113
|
+
CRITICAL RULES:
|
|
114
|
+
- ALWAYS use describe_viewer before adding a viewer to understand its properties
|
|
115
|
+
- When setting viewer properties, use exact column names from the table structure
|
|
116
|
+
- For categorical columns, leverage the category information provided
|
|
117
|
+
- Pay attention to semantic types (semType) and units when relevant
|
|
118
|
+
- Use list_current_viewers to understand the current state before making changes
|
|
119
|
+
- If user mentions "this viewer" or "that chart", use find_viewers_by_type to identify which one
|
|
120
|
+
- If adjust_viewer fails because viewer doesn't exist, add it instead
|
|
121
|
+
- Format your responses in markdown for better readability
|
|
122
|
+
- If the user asks a general question that doesn't require viewer manipulation, just answer it conversationally
|
|
123
|
+
- When user request is ambiguous, ask for clarification
|
|
124
|
+
- ALWAYS use highlight_element to guide users to UI elements when relevant!${vectorStoreId ? '\n- DOCUMENTATION SEARCH: Use search_documentation tool IMMEDIATELY when the user asks about any Datagrok features, functionality, or workflows that are not directly related to adding/modifying viewers in the current table. This includes questions like "how do I do X" or "where is feature Y". NEVER invent or assume information about Datagrok features, menu locations, package names, or workflows - ALWAYS search documentation first! If documentation search returns no results, tell the user you cannot find information rather than making assumptions.' : ''}
|
|
125
|
+
- STRICT NO-INVENTION POLICY: Do NOT make up menu locations, feature names, dialog boxes, keyboard shortcuts, package names, or step-by-step instructions unless they come directly from documentation search results or are about the specific table/viewer tools you have access to.
|
|
126
|
+
|
|
127
|
+
Your responses should be informative, explaining what you're doing and why.`;
|
|
128
|
+
|
|
129
|
+
const input: MessageType[] = options.oldMessages ? [...options.oldMessages] : [];
|
|
130
|
+
|
|
131
|
+
if (input.length === 0) {
|
|
132
|
+
const tableDescription = context.getTableDescription();
|
|
133
|
+
const availableViewers = context.getAvailableViewers();
|
|
134
|
+
|
|
135
|
+
const initialContext = `${tableDescription}\n\n${availableViewers}`;
|
|
136
|
+
|
|
137
|
+
const systemMsg = langTool.createSystemMessage(systemMessage);
|
|
138
|
+
const userMsg = langTool.createUserMessage(`${initialContext}\n\nUser request: ${prompt}`);
|
|
139
|
+
input.push(systemMsg);
|
|
140
|
+
input.push(userMsg);
|
|
141
|
+
options.aiPanel?.addEngineMessage(systemMsg);
|
|
142
|
+
options.aiPanel?.addUserMessage(userMsg, prompt);
|
|
143
|
+
} else {
|
|
144
|
+
const userMsg = langTool.createUserMessage(prompt);
|
|
145
|
+
input.push(userMsg);
|
|
146
|
+
options.aiPanel?.addUserMessage(userMsg, prompt);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const tools: LanguageModelV3FunctionTool[] = [
|
|
150
|
+
{
|
|
151
|
+
type: 'function',
|
|
152
|
+
name: 'list_ui_elements',
|
|
153
|
+
description: 'Get a list of all available UI elements in the table view with their IDs and descriptions. Use this when users ask where to find features or how to access functionality. Call this before highlight_element to know which elements are available.',
|
|
154
|
+
inputSchema: {
|
|
155
|
+
type: 'object',
|
|
156
|
+
properties: {},
|
|
157
|
+
required: [],
|
|
158
|
+
additionalProperties: false,
|
|
159
|
+
},
|
|
160
|
+
strict: true,
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
type: 'function',
|
|
164
|
+
name: 'highlight_element',
|
|
165
|
+
description: 'Highlights a UI element to guide the user. Use this when you want to show users where specific features or controls are located. Use list_ui_elements first to get valid element ID or names.',
|
|
166
|
+
inputSchema: {
|
|
167
|
+
type: 'object',
|
|
168
|
+
properties: {
|
|
169
|
+
elementId: {
|
|
170
|
+
type: 'string',
|
|
171
|
+
description: 'ID or name of the UI element to highlight'
|
|
172
|
+
},
|
|
173
|
+
description: {
|
|
174
|
+
type: 'string',
|
|
175
|
+
description: 'Brief description of why this element is being highlighted'
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
required: ['elementId', 'description'],
|
|
179
|
+
additionalProperties: false,
|
|
180
|
+
},
|
|
181
|
+
strict: true,
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
type: 'function',
|
|
185
|
+
name: 'get_available_viewers',
|
|
186
|
+
description: 'Get a list of all available viewer types that can be added to the table view. Use this if you forget which viewer types are available or need to remind yourself of the options.',
|
|
187
|
+
inputSchema: {
|
|
188
|
+
type: 'object',
|
|
189
|
+
properties: {},
|
|
190
|
+
required: [],
|
|
191
|
+
additionalProperties: false,
|
|
192
|
+
},
|
|
193
|
+
strict: true,
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
type: 'function',
|
|
197
|
+
name: 'describe_viewer',
|
|
198
|
+
description: 'Get detailed information about a viewer type including all its properties and their types. ALWAYS call this BEFORE adding a new viewer to understand what properties are available and their correct names/types. This describes the viewer type schema, not existing viewer instances.',
|
|
199
|
+
inputSchema: {
|
|
200
|
+
type: 'object',
|
|
201
|
+
properties: {
|
|
202
|
+
viewerType: {
|
|
203
|
+
type: 'string',
|
|
204
|
+
description: 'Type of the viewer to describe (e.g., "Histogram", "Scatter plot"). must match exactly one of the available viewer types supplied.'
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
required: ['viewerType'],
|
|
208
|
+
additionalProperties: false,
|
|
209
|
+
},
|
|
210
|
+
strict: true,
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
type: 'function',
|
|
214
|
+
name: 'add_viewer',
|
|
215
|
+
description: 'Add a new viewer to the table view with specified properties. IMPORTANT: Set all desired properties during creation using the viewerProperties parameter - avoid creating a viewer with empty properties and then adjusting it separately. Use describe_viewer first to understand available properties.',
|
|
216
|
+
inputSchema: {
|
|
217
|
+
type: 'object',
|
|
218
|
+
properties: {
|
|
219
|
+
viewerType: {
|
|
220
|
+
type: 'string',
|
|
221
|
+
description: 'Type of viewer to add'
|
|
222
|
+
},
|
|
223
|
+
viewerProperties: {
|
|
224
|
+
type: 'object',
|
|
225
|
+
description: 'Properties to configure for the viewer (e.g., {"valueColumnName": "Age", "markerSize": 15})',
|
|
226
|
+
properties: {},
|
|
227
|
+
required: [],
|
|
228
|
+
patternProperties: {
|
|
229
|
+
'.*': {type: 'string'},
|
|
230
|
+
},
|
|
231
|
+
additionalProperties: false,
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
required: ['viewerType', 'viewerProperties'],
|
|
235
|
+
additionalProperties: false,
|
|
236
|
+
},
|
|
237
|
+
// strict: true,
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
type: 'function',
|
|
241
|
+
name: 'find_viewers_by_type',
|
|
242
|
+
description: 'Find all viewers of a specific type that are already added to the table view and get their IDs and current properties. Use this when you need to identify existing viewers of a certain type before modifying them, or when the user refers to "the histogram" or "the scatter plot".',
|
|
243
|
+
inputSchema: {
|
|
244
|
+
type: 'object',
|
|
245
|
+
properties: {
|
|
246
|
+
viewerType: {
|
|
247
|
+
type: 'string',
|
|
248
|
+
description: 'Type of viewers to find'
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
required: ['viewerType'],
|
|
252
|
+
additionalProperties: false,
|
|
253
|
+
},
|
|
254
|
+
strict: true,
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
type: 'function',
|
|
258
|
+
name: 'adjust_viewer',
|
|
259
|
+
description: 'Adjust properties of an EXISTING viewer by its ID. Use this to modify viewers that are already created, not for initial configuration. If viewer is not found, will inform you to add it instead. For new viewers, use add_viewer with all properties set from the start.',
|
|
260
|
+
inputSchema: {
|
|
261
|
+
type: 'object',
|
|
262
|
+
properties: {
|
|
263
|
+
viewerId: {
|
|
264
|
+
type: 'string',
|
|
265
|
+
description: 'ID of the viewer to adjust'
|
|
266
|
+
},
|
|
267
|
+
viewerProperties: {
|
|
268
|
+
type: 'object',
|
|
269
|
+
description: 'Properties to update',
|
|
270
|
+
properties: {},
|
|
271
|
+
required: [],
|
|
272
|
+
patternProperties: {
|
|
273
|
+
'.*': {type: 'string'},
|
|
274
|
+
},
|
|
275
|
+
additionalProperties: false,
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
required: ['viewerId', 'viewerProperties'],
|
|
279
|
+
additionalProperties: false,
|
|
280
|
+
},
|
|
281
|
+
// strict: true,
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
type: 'function',
|
|
285
|
+
name: 'list_current_viewers',
|
|
286
|
+
description: 'Get a list of all currently added viewers with their IDs, types, and configured properties. Use this to see what viewers already exist before adding new ones or to find viewer IDs for adjustment.',
|
|
287
|
+
inputSchema: {
|
|
288
|
+
type: 'object',
|
|
289
|
+
properties: {},
|
|
290
|
+
required: [],
|
|
291
|
+
additionalProperties: false,
|
|
292
|
+
},
|
|
293
|
+
strict: true,
|
|
294
|
+
},
|
|
295
|
+
{
|
|
296
|
+
type: 'function',
|
|
297
|
+
name: 'reply_to_user',
|
|
298
|
+
description: 'Send a message to the user to explain reasoning, ask for clarification, or provide updates',
|
|
299
|
+
inputSchema: {
|
|
300
|
+
type: 'object',
|
|
301
|
+
properties: {
|
|
302
|
+
message: {
|
|
303
|
+
type: 'string',
|
|
304
|
+
description: 'Message to send to the user'
|
|
305
|
+
}
|
|
306
|
+
},
|
|
307
|
+
required: ['message'],
|
|
308
|
+
additionalProperties: false,
|
|
309
|
+
},
|
|
310
|
+
strict: true,
|
|
311
|
+
}
|
|
312
|
+
];
|
|
313
|
+
|
|
314
|
+
// Add search_documentation tool only if vectorStoreId is provided
|
|
315
|
+
if (vectorStoreId) {
|
|
316
|
+
tools.push({
|
|
317
|
+
type: 'function',
|
|
318
|
+
name: 'search_documentation',
|
|
319
|
+
description: 'Search external Datagrok documentation for authoritative information. CRITICAL: Use this tool IMMEDIATELY when user asks ANY question about: 1) How to access Datagrok features/functionality, 2) Where to find menu items or commands, 3) How to perform operations not directly related to viewer manipulation, 4) Package names or requirements, 5) Keyboard shortcuts, 6) Dialogs or workflows. DO NOT make assumptions or invent UI locations, feature names, or steps - ALWAYS search documentation first! If you are even slightly uncertain about something, USE THIS TOOL. Only skip this tool for questions that are purely about manipulating viewers in the current table.',
|
|
320
|
+
inputSchema: {
|
|
321
|
+
type: 'object',
|
|
322
|
+
properties: {
|
|
323
|
+
query: {
|
|
324
|
+
type: 'string',
|
|
325
|
+
description: 'The search query for finding relevant documentation'
|
|
326
|
+
},
|
|
327
|
+
maxResults: {
|
|
328
|
+
type: 'integer',
|
|
329
|
+
description: 'Maximum number of results to return (1-50)',
|
|
330
|
+
default: 5
|
|
331
|
+
}
|
|
332
|
+
},
|
|
333
|
+
required: ['query', 'maxResults'],
|
|
334
|
+
additionalProperties: false,
|
|
335
|
+
},
|
|
336
|
+
strict: true,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
while (iterations < maxIterations) {
|
|
341
|
+
if (isAborted()) {
|
|
342
|
+
options.aiPanel?.addUiMessage('**Processing aborted by user**', false);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
iterations++;
|
|
347
|
+
const response = await client.doGenerate({
|
|
348
|
+
prompt: input,
|
|
349
|
+
tools,
|
|
350
|
+
providerOptions: {
|
|
351
|
+
openai: {
|
|
352
|
+
...(ModelType.Coding.startsWith('gpt-5') ? {reasoning: {effort: 'medium'}} : {}),
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// The AI SDK's doGenerate puts item IDs in providerMetadata, but the
|
|
358
|
+
// Responses API input converter only reads reasoning items from providerOptions
|
|
359
|
+
// (tool-call has a fallback to providerMetadata, but reasoning does not).
|
|
360
|
+
// Copy providerMetadata → providerOptions so reasoning item_references are created.
|
|
361
|
+
const fixedContent = response.content.map((item) => {
|
|
362
|
+
const patched = {
|
|
363
|
+
...item,
|
|
364
|
+
providerOptions: (item as any).providerOptions ?? (item as any).providerMetadata,
|
|
365
|
+
};
|
|
366
|
+
if (item.type === 'tool-call') {
|
|
367
|
+
return {
|
|
368
|
+
...patched,
|
|
369
|
+
input: typeof item.input === 'string' ? parseJsonObject(item.input) ?? item.input : item.input
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
return patched;
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
const formattedOutput: LanguageModelV3Message = {
|
|
376
|
+
role: 'assistant',
|
|
377
|
+
// @ts-ignore
|
|
378
|
+
content: fixedContent
|
|
379
|
+
};
|
|
380
|
+
//const outputs: MessageType[] = response.content.map((item) => ({role: 'assistant', content: [item]} as MessageType));
|
|
381
|
+
input.push(formattedOutput);
|
|
382
|
+
options.aiPanel?.addEngineMessage(formattedOutput);
|
|
383
|
+
|
|
384
|
+
let hadToolCalls = false;
|
|
385
|
+
for (const call of response.content.filter((c) => c.type === 'tool-call')) {
|
|
386
|
+
hadToolCalls = true;
|
|
387
|
+
|
|
388
|
+
const functionName = call.toolName;
|
|
389
|
+
const callId = call.toolCallId;
|
|
390
|
+
const rawArgs = call.input ?? '{}';
|
|
391
|
+
const argsObj = parseJsonObject(rawArgs);
|
|
392
|
+
|
|
393
|
+
if (!functionName || !callId) {
|
|
394
|
+
const outputItem = langTool.createToolOutputMessage(callId ?? '', functionName ?? '', 'Error: malformed function call (missing name/call_id).');
|
|
395
|
+
if (callId) {
|
|
396
|
+
input.push(outputItem);
|
|
397
|
+
options.aiPanel?.addEngineMessage(outputItem);
|
|
398
|
+
}
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
let result: string;
|
|
403
|
+
try {
|
|
404
|
+
switch (functionName) {
|
|
405
|
+
case 'list_ui_elements':
|
|
406
|
+
result = await context.listUIElements();
|
|
407
|
+
options.aiPanel?.addUiMessage('🔍 Looking for available UI elements', false);
|
|
408
|
+
break;
|
|
409
|
+
case 'get_available_viewers':
|
|
410
|
+
result = context.getAvailableViewers();
|
|
411
|
+
options.aiPanel?.addUiMessage('📊 Getting available viewer types', false);
|
|
412
|
+
break;
|
|
413
|
+
case 'highlight_element': {
|
|
414
|
+
result = 'Element highlighted';
|
|
415
|
+
const elementId = getStringProp(argsObj, 'elementId') ?? '';
|
|
416
|
+
const description = getStringProp(argsObj, 'description') ?? '';
|
|
417
|
+
const actRes = await context.highlightElement(elementId, description);
|
|
418
|
+
options.aiPanel?.addUiMessage(`Highlighting: **${elementId}**`, false);
|
|
419
|
+
if (actRes != null) {
|
|
420
|
+
// if it is not null, then it is an error message
|
|
421
|
+
result = actRes;
|
|
422
|
+
options.aiPanel?.addUiMessage(`⚠️ ${actRes}`, false);
|
|
423
|
+
}
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
case 'describe_viewer': {
|
|
427
|
+
const viewerType = getStringProp(argsObj, 'viewerType') ?? '';
|
|
428
|
+
result = await context.describeViewer(viewerType);
|
|
429
|
+
options.aiPanel?.addUiMessage(`📋 Getting available properties for **${viewerType}** viewer`, false);
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
case 'add_viewer': {
|
|
433
|
+
const viewerType = getStringProp(argsObj, 'viewerType') ?? '';
|
|
434
|
+
const viewerProps = (isJsonObject(argsObj?.viewerProperties) ? argsObj.viewerProperties :
|
|
435
|
+
isJsonObject(argsObj?.properties) ? argsObj.properties : {}) as ViewerProps;
|
|
436
|
+
result = await context.addViewer(viewerType, viewerProps);
|
|
437
|
+
options.aiPanel?.addUiMessage(`➕ Added **${viewerType}** viewer ${viewerProps && Object.keys(viewerProps).length > 0 ? `with properties: \n\`\`\`json\n${JSON.stringify(viewerProps, null, 2)}\n\`\`\`` : ''}`, false);
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
case 'find_viewers_by_type': {
|
|
441
|
+
const viewerType = getStringProp(argsObj, 'viewerType') ?? '';
|
|
442
|
+
options.aiPanel?.addUiMessage(`🔎 Searching for **${viewerType}** viewers`, false);
|
|
443
|
+
result = await context.findViewersByType(viewerType);
|
|
444
|
+
break;
|
|
445
|
+
}
|
|
446
|
+
case 'adjust_viewer': {
|
|
447
|
+
const viewerId = getStringProp(argsObj, 'viewerId') ?? '';
|
|
448
|
+
const viewerProps = (isJsonObject(argsObj?.viewerProperties) ? argsObj.viewerProperties :
|
|
449
|
+
isJsonObject(argsObj?.properties) ? argsObj.properties : {}) as ViewerProps;
|
|
450
|
+
result = await context.adjustViewer(viewerId, viewerProps);
|
|
451
|
+
options.aiPanel?.addUiMessage(`⚙️ Setting properties to the viewer: \n\`\`\`json\n${JSON.stringify(viewerProps, null, 2)}\n\`\`\``, false);
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
case 'list_current_viewers':
|
|
455
|
+
result = await context.listCurrentViewers();
|
|
456
|
+
options.aiPanel?.addUiMessage('📝 Listing currently open viewers', false);
|
|
457
|
+
break;
|
|
458
|
+
case 'reply_to_user': {
|
|
459
|
+
const message = getStringProp(argsObj, 'message') ?? '';
|
|
460
|
+
result = 'Message sent to user';
|
|
461
|
+
options.aiPanel?.addUiMessage(`💬 ${message}`, false);
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
case 'search_documentation': {
|
|
465
|
+
const query = getStringProp(argsObj, 'query') ?? '';
|
|
466
|
+
const maxResults = getNumberProp(argsObj, 'maxResults') ?? 4;
|
|
467
|
+
// Ask for user confirmation before searching external docs (example of using confirmations)
|
|
468
|
+
// const confirmSearch = options.aiPanel ? await options.aiPanel.addConfirmMessage('Datagrok wants to search platform documentation for additional context. Do you want to allow this action?') : true;
|
|
469
|
+
// if (!confirmSearch) {
|
|
470
|
+
// result = 'Documentation search prohibited by user. Please answer based on the available context without using external documentation.';
|
|
471
|
+
// options.aiPanel?.addUiMessage('⚠️ External documentation search prohibited by user.', false);
|
|
472
|
+
// break;
|
|
473
|
+
// }
|
|
474
|
+
options.aiPanel?.addUiMessage(`🔍 Searching documentation for: **${query}**`, false);
|
|
475
|
+
try {
|
|
476
|
+
const searchData = await langTool.openai.vectorStores.search(vectorStoreId, {
|
|
477
|
+
query,
|
|
478
|
+
max_num_results: maxResults,
|
|
479
|
+
rewrite_query: false,
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
// Format the search results
|
|
483
|
+
if (searchData.data && searchData.data.length > 0) {
|
|
484
|
+
let formattedResults = `Found ${searchData.data.length} relevant documentation sections:\n\n`;
|
|
485
|
+
for (const item of searchData.data) {
|
|
486
|
+
formattedResults += `**Source**: ${item.filename} (score: ${item.score.toFixed(2)})\n`;
|
|
487
|
+
for (const content of item.content) {
|
|
488
|
+
if (content.type === 'text')
|
|
489
|
+
formattedResults += `${content.text}\n\n`;
|
|
490
|
+
}
|
|
491
|
+
formattedResults += '---\n\n';
|
|
492
|
+
}
|
|
493
|
+
result = formattedResults;
|
|
494
|
+
options.aiPanel?.addUiMessage(`✅ Found ${searchData.data.length} relevant documentation sections`, false);
|
|
495
|
+
} else {
|
|
496
|
+
result = 'No relevant documentation found for this query.';
|
|
497
|
+
options.aiPanel?.addUiMessage('ℹ️ No relevant documentation found', false);
|
|
498
|
+
}
|
|
499
|
+
} catch (error) {
|
|
500
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
501
|
+
result = `Error searching documentation: ${msg}`;
|
|
502
|
+
options.aiPanel?.addUiMessage(`⚠️ Error searching documentation: ${msg}`, false);
|
|
503
|
+
}
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
default:
|
|
507
|
+
result = `Unknown function: ${functionName}`;
|
|
508
|
+
}
|
|
509
|
+
} catch (error) {
|
|
510
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
511
|
+
result = `Error: ${msg}`;
|
|
512
|
+
options.aiPanel?.addUiMessage(`⚠️ Error executing ${functionName}: ${msg}`, false);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
const outputItem = langTool.createToolOutputMessage(callId, functionName, result);
|
|
516
|
+
input.push(outputItem);
|
|
517
|
+
options.aiPanel?.addEngineMessage(outputItem);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
if (hadToolCalls) {
|
|
521
|
+
if (iterations >= maxIterations) {
|
|
522
|
+
const continueProcessing = await new Promise<boolean>((resolve) => {
|
|
523
|
+
ui.dialog('Maximum Iterations Reached')
|
|
524
|
+
.add(ui.divText(`The AI has reached the maximum iteration limit (${maxIterations}). Would you like to continue for 10 more iterations?`))
|
|
525
|
+
.onOK(() => resolve(true))
|
|
526
|
+
.onCancel(() => resolve(false))
|
|
527
|
+
.show();
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
if (continueProcessing) {
|
|
531
|
+
maxIterations += 10;
|
|
532
|
+
options.aiPanel?.addUiMessage(`ℹ️ Continuing processing for ${maxIterations - iterations} more iterations...`, false);
|
|
533
|
+
} else {
|
|
534
|
+
options.aiPanel?.addUiMessage('⚠️ Processing stopped by user.', false);
|
|
535
|
+
break;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const content = findLast(response.content, (c) => c.type === 'text')?.text;
|
|
542
|
+
if ((content?.length ?? 0) > 0) {
|
|
543
|
+
options.aiPanel?.addUiMessage(content!, false, {
|
|
544
|
+
finalResult: content
|
|
545
|
+
});
|
|
546
|
+
break;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
if (iterations >= maxIterations)
|
|
551
|
+
options.aiPanel?.addUiMessage('⚠️ Maximum iteration limit reached. Please refine your request.', false);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const AI_GENERATED_IDENTIFIER_TAG = 'AI-generated-identifier';
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Context class that manages tool execution for table view operations
|
|
558
|
+
*/
|
|
559
|
+
export class TableViewContext {
|
|
560
|
+
private dummy: DG.DataFrame;
|
|
561
|
+
constructor(private tableView: DG.TableView) {
|
|
562
|
+
// Initialize with existing viewers
|
|
563
|
+
this.dummy = grok.data.testData('demog', 100);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
getTableDescription(): string {
|
|
567
|
+
const df = this.tableView.dataFrame;
|
|
568
|
+
let description = `## Current Table: ${df.name}\n\n`;
|
|
569
|
+
description += `**${df.columns.length} Columns:**\n`;
|
|
570
|
+
|
|
571
|
+
for (const col of df.columns.toList()) {
|
|
572
|
+
description += `- **${col.name}** (${col.type})`;
|
|
573
|
+
|
|
574
|
+
if (col.semType)
|
|
575
|
+
description += ` - semType: ${col.semType}`;
|
|
576
|
+
|
|
577
|
+
if (col.meta.units)
|
|
578
|
+
description += ` - units: ${col.meta.units}`;
|
|
579
|
+
|
|
580
|
+
if (col.isCategorical)
|
|
581
|
+
description += ` - categorical (${col.categories.length} categories)`;
|
|
582
|
+
|
|
583
|
+
description += '\n';
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
return description;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
getAvailableViewers(): string {
|
|
590
|
+
let description = `## Available Viewer Types:\n\n`;
|
|
591
|
+
description += DG.Viewer.CORE_VIEWER_TYPES.join(', ');
|
|
592
|
+
description += '\n\nUse describe_viewer to get detailed information about any viewer type.';
|
|
593
|
+
return description;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
async describeViewer(viewerType: string): Promise<string> {
|
|
597
|
+
const commonProps = ['rowSource', 'filter', 'table'];
|
|
598
|
+
try {
|
|
599
|
+
const viewer = DG.Viewer.fromType(viewerType, this.dummy);
|
|
600
|
+
let result = `Viewer properties for ${viewerType}:\n\n`;
|
|
601
|
+
for (const prop of viewer.getProperties()) {
|
|
602
|
+
if (!commonProps.includes(prop.name))
|
|
603
|
+
result += `${prop.name} - ${prop.type} - (${prop.description || 'No Description'})` + '\n';
|
|
604
|
+
}
|
|
605
|
+
return result;
|
|
606
|
+
} catch (e) {
|
|
607
|
+
console.error(e);
|
|
608
|
+
return `Error describing viewer ${viewerType}: ${e}`;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
getViewerIdentifier(viewer: DG.Viewer): string {
|
|
613
|
+
// use viewer tags to identify viewers
|
|
614
|
+
const getRndHash = () => Math.random().toString(36).substring(2, 8);
|
|
615
|
+
if (!viewer.tags.get(AI_GENERATED_IDENTIFIER_TAG)) {
|
|
616
|
+
// generate a random and unique identifier
|
|
617
|
+
const identifier = `viewer-${getRndHash()}-${getRndHash()}-${getRndHash()}`;
|
|
618
|
+
viewer.tags.set(AI_GENERATED_IDENTIFIER_TAG, identifier);
|
|
619
|
+
}
|
|
620
|
+
return viewer.tags.get(AI_GENERATED_IDENTIFIER_TAG)!;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
async addViewer(viewerType: string, properties: ViewerProps): Promise<string> {
|
|
624
|
+
const newViewer = this.tableView.addViewer(viewerType, properties as Record<string, string | number | boolean | null | object>);
|
|
625
|
+
const id = this.getViewerIdentifier(newViewer);
|
|
626
|
+
return `Added viewer with ID: ${id}`;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async findViewersByType(viewerType: string): Promise<string> {
|
|
630
|
+
const foundViewer = Array.from(this.tableView.viewers).filter((v) => v.type === viewerType);
|
|
631
|
+
if (foundViewer.length === 0)
|
|
632
|
+
return `No viewers of type ${viewerType} found.`;
|
|
633
|
+
const resultLines = foundViewer.map((v) => {
|
|
634
|
+
const id = this.getViewerIdentifier(v);
|
|
635
|
+
const props = v.getOptions().look;
|
|
636
|
+
return `- ID: ${id} \n Configured Properties: \n\`\`\`json\n${JSON.stringify(props, null, 2)}\n\`\`\``;
|
|
637
|
+
});
|
|
638
|
+
return `Found viewers of type ${viewerType}: \n\n ${resultLines.join('\n\n')}`;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
async adjustViewer(viewerId: string, properties: ViewerProps): Promise<string> {
|
|
642
|
+
const foundViewer = Array.from(this.tableView.viewers).find((v) => this.getViewerIdentifier(v) === viewerId);
|
|
643
|
+
if (!foundViewer)
|
|
644
|
+
return `Viewer with ID ${viewerId} not found. Please add a new viewer instead.`;
|
|
645
|
+
foundViewer.setOptions(properties as Record<string, string | number | boolean | null | object>);
|
|
646
|
+
return `Adjusted viewer ${viewerId}`;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
async listCurrentViewers(): Promise<string> {
|
|
650
|
+
const allViewers = Array.from(this.tableView.viewers);
|
|
651
|
+
if (allViewers.length === 0)
|
|
652
|
+
return `No viewers currently added.`;
|
|
653
|
+
const lines = allViewers.map((v) => {
|
|
654
|
+
const id = this.getViewerIdentifier(v);
|
|
655
|
+
const type = v.type;
|
|
656
|
+
const props = v.getOptions().look;
|
|
657
|
+
return `- ID: ${id}, Type: ${type}\n Configured Properties:\n\`\`\`json\n${JSON.stringify(props, null, 2)}\n\`\`\``;
|
|
658
|
+
});
|
|
659
|
+
return `Currently added viewers:\n\n${lines.join('\n\n')}`;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
private highlightableElements = [
|
|
663
|
+
{id: 'Toggle filters button', description: 'Button to toggle the filter panel visibility', selector: 'div.d4-ribbon .grok-icon.grok-icon-filter'},
|
|
664
|
+
{id: 'Add viewer button', description: 'Button that lets you add a new viewer to the table and has a list of all viewers', selector: 'div.d4-ribbon .grok-icon.svg-icon.svg-add-viewer'},
|
|
665
|
+
{id: 'Download button', description: 'Button to download the current table in various formats (csv, excel, json, parquet, sdf, etc.)', selector: 'div.d4-ribbon .grok-icon.fal.fa-arrow-to-bottom'},
|
|
666
|
+
{id: 'Add new column button', description: 'Button to add a new column to the current table using various methods (from formula, from mapping, constant etc.)', selector: 'div.d4-ribbon .grok-icon.svg-icon.svg-add-new-column'},
|
|
667
|
+
];
|
|
668
|
+
|
|
669
|
+
private getUiElements() {
|
|
670
|
+
const uiElements: {id: string, description: string, element: HTMLElement}[] = this.highlightableElements
|
|
671
|
+
.map((el) => ({element: document.querySelector(el.selector) as HTMLElement, id: el.id, description: el.description}))
|
|
672
|
+
.filter((el) => el.element != null);
|
|
673
|
+
// also add top menu items
|
|
674
|
+
['Select', 'Edit', 'View', 'Data', 'ML', 'Bio', 'Chem'].forEach((menuText) => {
|
|
675
|
+
const menuItem = Array.from(this.tableView.ribbonMenu.root.querySelectorAll(`div.d4-menu-item.d4-menu-group.d4-menu-item-horz`))
|
|
676
|
+
.find((el) => (el as HTMLDivElement).innerText === menuText);
|
|
677
|
+
if (menuItem)
|
|
678
|
+
uiElements.push({id: `${menuText} top menu`, description: `Top menu item: "${menuText}" containing relevant functions `, element: menuItem as HTMLElement});
|
|
679
|
+
});
|
|
680
|
+
return uiElements;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
async listUIElements(): Promise<string> {
|
|
684
|
+
// TODO: Populate with actual UI elements from the table view
|
|
685
|
+
const elements = this.getUiElements();
|
|
686
|
+
|
|
687
|
+
let result = 'Available UI elements:\n\n';
|
|
688
|
+
for (const elem of elements)
|
|
689
|
+
result += `- **${elem.id}**: ${elem.description}\n`;
|
|
690
|
+
|
|
691
|
+
return result;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
async highlightElement(elementId: string, _description: string): Promise<string | null> {
|
|
695
|
+
const element = this.getUiElements().find((el) => el.id.toLowerCase() === elementId.toLowerCase());
|
|
696
|
+
if (!element)
|
|
697
|
+
return `Element with ID ${elementId} not found or cannot be highlighted.`;
|
|
698
|
+
const domElement = element.element;
|
|
699
|
+
if (!domElement || !document.body.contains(domElement))
|
|
700
|
+
return `Element with ID ${elementId} not found in the current UI.`;
|
|
701
|
+
ui.hints.addHintIndicator(domElement, true, 15000);
|
|
702
|
+
return null;
|
|
703
|
+
}
|
|
704
|
+
}
|