@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,170 @@
1
+ import {JSONSchema7} from 'ai';
2
+ import * as DG from 'datagrok-api/dg';
3
+
4
+ export interface FuncParam {
5
+ type: string;
6
+ description: string;
7
+ default?: any;
8
+ optional?: boolean;
9
+ }
10
+
11
+ export type ChatGptFuncParams = Record<string, FuncParam>;
12
+
13
+ export interface FunctionInput {
14
+ type: string;
15
+ properties: ChatGptFuncParams;
16
+ }
17
+
18
+ export interface FunctionOutput {
19
+ name: string;
20
+ type: string;
21
+ }
22
+
23
+ export interface FunctionMeta {
24
+ name: string;
25
+ description: string;
26
+ inputs: FunctionInput;
27
+ outputs: FunctionOutput[];
28
+ }
29
+
30
+ export interface Step {
31
+ action: 'call_function';
32
+ function: string;
33
+ inputs: Record<string, any>;
34
+ outputs: string[];
35
+ }
36
+
37
+ export interface Plan {
38
+ goal: string;
39
+ analysis: string[];
40
+ steps: Step[];
41
+ }
42
+
43
+ export interface PackageInfo {
44
+ name: string;
45
+ description: string;
46
+ }
47
+
48
+ export interface StepExecutionOutput<T = any> {
49
+ value: T;
50
+ meta?: DG.Property;
51
+ }
52
+
53
+ export type ExecutionContext = Record<string, StepExecutionOutput>;
54
+
55
+ export interface ExecutePlanResult {
56
+ context: ExecutionContext;
57
+ finalResult: StepExecutionOutput | null;
58
+ }
59
+
60
+ export interface PackageSelection {
61
+ selected_packages: {
62
+ name: string;
63
+ reason: string;
64
+ }[];
65
+ }
66
+
67
+ export type JsonSchema = JSONSchema7;
68
+
69
+ /* Schemas defined to enable structured output handling */
70
+ export const PackageSelectionSchema: JsonSchema = {
71
+ type: 'object',
72
+ properties: {
73
+ selected_packages: {
74
+ type: 'array',
75
+ items: {
76
+ type: 'object',
77
+ properties: {
78
+ name: {
79
+ type: 'string',
80
+ description: 'The name of the package to use.',
81
+ },
82
+ reason: {
83
+ type: 'string',
84
+ description: 'The reason why this package is relevant to the user\'s goal.',
85
+ }
86
+ },
87
+ required: ['name', 'reason'],
88
+ additionalProperties: false,
89
+ }
90
+ }
91
+ },
92
+ required: ['selected_packages'],
93
+ additionalProperties: false,
94
+ };
95
+
96
+ export const PlanSchema: JsonSchema = {
97
+ type: 'object',
98
+ properties: {
99
+ goal: {
100
+ type: 'string',
101
+ description: 'The user goal restated clearly in your own words.'
102
+ },
103
+ analysis: {
104
+ type: 'array',
105
+ description: 'Reasoning explaining why the selected steps will achieve the goal.',
106
+ items: {
107
+ type: 'string',
108
+ }
109
+ },
110
+ steps: {
111
+ type: 'array',
112
+ description: 'An ordered list of steps to perform, using available functions.',
113
+ items: {
114
+ type: 'object',
115
+ properties: {
116
+ action: {
117
+ type: 'string',
118
+ description: 'The type of action to perform in this step. Currently only "call_function" is supported.',
119
+ enum: ['call_function']
120
+ },
121
+ function: {
122
+ type: 'string',
123
+ description: 'The exact name of the function to call in this step.'
124
+ },
125
+ inputs: {
126
+ type: 'object',
127
+ description: 'Function inputs as a dictionary of key-value pairs.',
128
+ properties: {},
129
+ required: [],
130
+ patternProperties: {
131
+ '.*': {},
132
+ },
133
+ additionalProperties: false,
134
+ },
135
+ outputs: {
136
+ type: 'array',
137
+ description: 'List of names for the outputs this step will produce.',
138
+ items: {
139
+ type: 'string',
140
+ }
141
+ }
142
+ },
143
+ additionalProperties: false,
144
+ required: ['action', 'function', 'inputs', 'outputs']
145
+ }
146
+ }
147
+ },
148
+ additionalProperties: false,
149
+ required: ['goal', 'analysis', 'steps'],
150
+ };
151
+
152
+ export enum LLMApiNames {
153
+ OpenAIChatCompletions = 'OpenAI Chat Completions',
154
+ OpenAIResponses = 'OpenAI Responses',
155
+ AntropicMessages = 'Antropic Messages',
156
+ AmazonBedrock = 'Amazon Bedrock',
157
+ }
158
+
159
+ export type LLMApiName = `${LLMApiNames}`;
160
+ // export type LLMApiName = 'OpenAI Chat Completions' | 'OpenAI Responses' | 'Antropic Messages'
161
+
162
+ export type PackageSettings = {
163
+ vectorStoreId?: string;
164
+ defaultFastModel?: string;
165
+ defaultDeepResearchModel?: string;
166
+ defaultCodingModel?: string;
167
+ APIName: LLMApiName;
168
+ region?: string;
169
+ apiVersion?: string;
170
+ }
@@ -0,0 +1,52 @@
1
+ import {ModelType, LLMClient} from '../llm-utils/LLM-client';
2
+ import {JsonSchema} from './interfaces';
3
+ export interface PromptEngine {
4
+ generate(prompt: string, system: string, schema?: JsonSchema): Promise<string>;
5
+ }
6
+
7
+ export class ChatGPTPromptEngine implements PromptEngine {
8
+ private static instance: ChatGPTPromptEngine | null = null;
9
+
10
+ private constructor(
11
+ private model = ModelType['Deep Research'],
12
+ private temperature = 0.0
13
+ ) {}
14
+
15
+ public static getInstance(model?: string, temperature?: number): ChatGPTPromptEngine {
16
+ return ChatGPTPromptEngine.instance ??= new ChatGPTPromptEngine(model, temperature);
17
+ }
18
+
19
+ async generate(prompt: string, system: string, schema?: JsonSchema): Promise<string> {
20
+ const res = LLMClient.getInstance();
21
+ return await res.generalPromptCached(this.model, system, prompt, schema);
22
+ }
23
+ }
24
+
25
+ export class GeminiPromptEngine implements PromptEngine {
26
+ private static instance: GeminiPromptEngine | null = null;
27
+ private session: LanguageModel | null = null;
28
+
29
+ private constructor(
30
+ private readonly monitor?: CreateMonitorCallback,
31
+ ) {}
32
+
33
+ public static getInstance(monitor?: CreateMonitorCallback): GeminiPromptEngine {
34
+ return GeminiPromptEngine.instance ??= new GeminiPromptEngine(monitor);
35
+ }
36
+
37
+ private async initSession(system: string) {
38
+ if (!this.session) {
39
+ this.session = await LanguageModel.create({
40
+ monitor: this.monitor,
41
+ initialPrompts: [{role: 'system', content: system}],
42
+ });
43
+ }
44
+ }
45
+
46
+ async generate(prompt: string, system: string, schema?: JsonSchema): Promise<string> {
47
+ await this.initSession(system);
48
+ return this.session!.prompt(prompt, {
49
+ responseConstraint: (schema as Record<string, unknown>) ?? undefined,
50
+ });
51
+ }
52
+ }
@@ -0,0 +1,103 @@
1
+ import * as ui from 'datagrok-api/ui';
2
+ import * as DG from 'datagrok-api/dg';
3
+ import * as grok from 'datagrok-api/grok';
4
+
5
+ //@ts-ignore
6
+ import '../../css/ai.css';
7
+ import {Plan, Step} from './interfaces';
8
+
9
+ function renderHelm(value: string): HTMLElement {
10
+ return ui.wait(async () => {
11
+ //@ts-ignore
12
+ const helmInput = await ui.input.helmAsync('helm', {
13
+ editable: false,
14
+ });
15
+ helmInput.setStringValue(value);
16
+ await DG.delay(200); // wait for proper sizing
17
+ helmInput.getInput().addEventListener('click', () => {
18
+ grok.shell.o = helmInput.getValue();
19
+ });
20
+ helmInput.getInput().addEventListener('dblclick', () => {
21
+ helmInput.showEditorDialog();
22
+ });
23
+
24
+ helmInput.getInput().style.width = '100%';
25
+ helmInput.getInput().style.setProperty('height', '300px', 'important');
26
+ return helmInput.getInput();
27
+ });
28
+ }
29
+
30
+
31
+ export class AssistantRenderer {
32
+ static renderPlan(plan: Plan): HTMLElement {
33
+ const container = ui.divV([], 'ai-execute-plan');
34
+ if (!plan?.steps?.length) {
35
+ container.append(ui.divText('No steps generated.'));
36
+ return container;
37
+ }
38
+
39
+ const analysis = ui.divV(
40
+ (plan.analysis ?? []).map((line: string) => ui.divText(line))
41
+ );
42
+
43
+ const stepsAccordion = ui.accordion();
44
+ plan.steps.map((s: Step, i: number) =>
45
+ stepsAccordion.addPane(
46
+ `Step ${i + 1}: ${s.function}`,
47
+ () => {
48
+ return ui.divV([
49
+ ui.divText(`Action: ${s.action}`),
50
+ ui.divText(`Inputs: ${JSON.stringify(s.inputs, null, 2)}`),
51
+ ui.divText(`Outputs: ${JSON.stringify(s.outputs)}`),
52
+ ]);
53
+ },
54
+ false
55
+ )
56
+ );
57
+
58
+ container.append(ui.h2('Plan'), analysis, stepsAccordion.root);
59
+ return container;
60
+ }
61
+
62
+ static renderResult(result: any): HTMLElement {
63
+ const val = result?.finalResult?.value ?? result?.finalResult ?? result;
64
+ const meta = result?.finalResult?.meta;
65
+ const container = ui.div([ui.h2('Result')], 'ai-execute-result');
66
+
67
+ if (meta?.propertyType === 'graphics')
68
+ container.append(renderGraphics(val));
69
+ else if (meta?.propertyType === 'widget')
70
+ container.append(val.root);
71
+ else if (typeof val === 'string' && meta?.semType === DG.SEMTYPE.MOLECULE)
72
+ container.append(grok.chem.drawMolecule(val, 200, 300));
73
+ else if (typeof val === 'string' && meta?.semType === DG.SEMTYPE.MACROMOLECULE &&
74
+ (meta?.units?.toLowerCase() === 'helm' || meta?.options?.units?.toLowerCase() === 'helm')
75
+ )
76
+ container.append(renderHelm(val));
77
+ else if (meta?.propertyType === 'dataframe') {
78
+ container.append(ui.button('Add to Workspace', () => grok.shell.addTableView(val),
79
+ 'Add resulting data frame to workspace'));
80
+ const grid = val.plot.grid().root;
81
+ grid.style.width = '100%';
82
+ container.append(grid);
83
+ } else
84
+ container.append(ui.divText(String(val)));
85
+
86
+ return container;
87
+ }
88
+ }
89
+
90
+ function renderGraphics(intermediateResult: HTMLElement): HTMLElement {
91
+ if (!intermediateResult?.style?.backgroundImage)
92
+ return ui.divText('No graphics available.');
93
+
94
+ try {
95
+ const backgroundImageUrl = intermediateResult.style.backgroundImage;
96
+ let base64Data = backgroundImageUrl.split('data:image/png;base64,')[1];
97
+ base64Data = base64Data.slice(0, -2);
98
+ return ui.image(`data:image/png;base64,${base64Data}`, 200, 300);
99
+ } catch (err) {
100
+ console.error('Failed to render graphics output:', err);
101
+ return ui.divText('Failed to render graphics.');
102
+ }
103
+ }
@@ -0,0 +1,26 @@
1
+ import {geminiDownloadMonitor} from '../llm-utils/query-matching';
2
+
3
+ export async function isHelpRequest(post: string): Promise<boolean> {
4
+ const schema = {
5
+ 'type': 'boolean'
6
+ };
7
+
8
+ const systemPrompt = `You are a helpful LLM that inspects user input and returns true
9
+ when the input is likely a question concerning the functionality of the data analytics application.
10
+ Return false for anything else (random strings, identifiers, numbers, commands, requests)`;
11
+
12
+ const session = await LanguageModel.create({
13
+ monitor: geminiDownloadMonitor,
14
+ initialPrompts: [
15
+ {role: 'system', content: systemPrompt}
16
+ ]
17
+ });
18
+
19
+ const result = await session.prompt(post,
20
+ {
21
+ responseConstraint: schema,
22
+ }
23
+ );
24
+
25
+ return JSON.parse(result);
26
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,174 @@
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 * as rxjs from 'rxjs';
6
+
7
+ const AI_SQL_QUERY_ABORT_EVENT = 'd4-ai-generation-abort';
8
+ const AI_PANEL_TOGGLE_EVENT = 'd4-ai-panel-toggle';
9
+
10
+ const dummy = grok.data.testData('demog');
11
+ let viewerDescriptions: string = '';
12
+
13
+ type IProp = {
14
+ type: string;
15
+ description?: string;
16
+ }
17
+
18
+ type IViewerDescription = {
19
+ viewerType: string;
20
+ properties: { [propName: string]: IProp };
21
+ }
22
+
23
+ type IDataFrameDescription = {
24
+ name: string;
25
+ columns: { [columnName: string]: IProp };
26
+ }
27
+
28
+ export function getViewerDescription(viewerType: DG.ViewerType): IViewerDescription {
29
+ const viewer = DG.Viewer.fromType(viewerType, dummy);
30
+ const properties: { [propName: string]: IProp } = {};
31
+
32
+ viewer.getProperties().forEach((prop) => {
33
+ properties[prop.name] = {
34
+ type: prop.type,
35
+ description: prop.description
36
+ };
37
+ });
38
+
39
+ return {
40
+ viewerType,
41
+ properties
42
+ };
43
+ }
44
+
45
+ export function getDataFrameDescription(dataFrame: DG.DataFrame): IDataFrameDescription {
46
+ const columns: { [columnName: string]: IProp } = {};
47
+
48
+ for (const column of dataFrame.columns.all) {
49
+ columns[column.name] = {type: column.type};
50
+
51
+ if (column.meta.description)
52
+ columns[column.name].description = column.meta.description;
53
+ }
54
+
55
+ return {
56
+ name: dataFrame.name,
57
+ columns
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Returns a list of viewer types, along with the detailed descriptions of their properties.
63
+ * This is used to generate the AI assistant's context.
64
+ */
65
+ export function getViewerDescriptions(): {[viewerType: string]: { [propName: string]: IProp }} {
66
+ grok.shell.info('gvd');
67
+ const descriptions: {[viewerType: string]: { [propName: string]: IProp }} = {};
68
+
69
+ for (const viewerType of DG.Viewer.CORE_VIEWER_TYPES) {
70
+ const viewer = DG.Viewer.fromType(viewerType, dummy);
71
+ const properties: { [propName: string]: IProp } = {};
72
+
73
+ viewer.getProperties().forEach((prop) => {
74
+ properties[prop.name] = {
75
+ type: prop.type,
76
+ description: prop.description
77
+ };
78
+ });
79
+
80
+ descriptions[viewerType] = properties;
81
+ }
82
+
83
+ return descriptions;
84
+ }
85
+
86
+ const commonProps = ['rowSource', 'filter', 'table'];
87
+ /**
88
+ * Returns a list of viewer types, along with the detailed descriptions of their properties.
89
+ * This is used to generate the AI assistant's context.
90
+ */
91
+ export function getViewerDescriptionsString(): string {
92
+ if (viewerDescriptions !== '')
93
+ return viewerDescriptions;
94
+
95
+
96
+ let result = `Properties common for all viewers:
97
+ rowSource: string // choices: "All", "Selected", "Filtered"
98
+ filter: string // Formulas like "\${AGE} < 40"
99
+
100
+ `;
101
+
102
+ for (const viewerType of DG.Viewer.CORE_VIEWER_TYPES) {
103
+ try {
104
+ const viewer = DG.Viewer.fromType(viewerType, dummy);
105
+
106
+ result += `${viewerType}\n`;
107
+ for (const prop of viewer.getProperties()) {
108
+ if (!commonProps.includes(prop.name) && (prop.category == 'Data' || prop.name.endsWith('ColumnName')))
109
+ result += `${prop.name} ${prop.type}` + '\n';
110
+ }
111
+ } catch (e) {
112
+ grok.shell.error('Error getting viewer descriptions: ' + e);
113
+ }
114
+
115
+ result += '\n';
116
+ }
117
+
118
+ viewerDescriptions = result;
119
+ return result;
120
+ }
121
+
122
+ export function getCurrentViewersString(view: DG.TableView): string {
123
+ let result = `Current viewers in the view:\n`;
124
+ for (const viewer of view.viewers) {
125
+ result += `${viewer.type} with properties: \n`;
126
+ for (const prop of viewer.getProperties()) {
127
+ if (!commonProps.includes(prop.name) && (prop.category == 'Data' ||
128
+ prop.name.endsWith('ColumnName')) && viewer.props[prop.name]
129
+ )
130
+ result += `${prop.name}: ${viewer.props[prop.name]?.toString()}` + '\n';
131
+ }
132
+ result += '\n\n';
133
+ }
134
+ return result;
135
+ }
136
+
137
+ export type AbortPointer = {
138
+ aborted: boolean;
139
+ }
140
+
141
+ export function dartLike<T extends any>(obj: T) {
142
+ return {
143
+ set: function<K extends keyof T>(key: K, value: T[K]) {
144
+ (obj as any)[key] = value;
145
+ return this;
146
+ },
147
+ value: obj as T,
148
+ };
149
+ }
150
+
151
+ export function getAIAbortSubscription() {
152
+ return rxjs.merge(grok.events.onEvent(AI_SQL_QUERY_ABORT_EVENT), grok.events.onCustomEvent(AI_SQL_QUERY_ABORT_EVENT));
153
+ }
154
+
155
+ export function getAIPanelToggleSubscription() {
156
+ return rxjs.merge(grok.events.onEvent(AI_PANEL_TOGGLE_EVENT), grok.events.onCustomEvent(AI_PANEL_TOGGLE_EVENT));
157
+ }
158
+
159
+ export function fireAIAbortEvent() {
160
+ grok.events.fireCustomEvent(AI_SQL_QUERY_ABORT_EVENT, null);
161
+ }
162
+
163
+ export function fireAIPanelToggleEvent(v: DG.View | DG.ViewBase) {
164
+ grok.events.fireCustomEvent(AI_PANEL_TOGGLE_EVENT, v);
165
+ }
166
+
167
+ export function findLast<T, K extends T>(array: T[], predicate: (value: T, index: number, obj: T[]) => value is K): K | undefined {
168
+ for (let i = array.length - 1; i >= 0; i--) {
169
+ const value = array[i];
170
+ if (predicate(value, i, array))
171
+ return value;
172
+ }
173
+ return undefined;
174
+ }
@@ -0,0 +1,67 @@
1
+ import * as grok from 'datagrok-api/grok';
2
+ import * as ui from 'datagrok-api/ui';
3
+ import * as DG from 'datagrok-api/dg';
4
+ import {getCurrentViewersString, getDataFrameDescription, getViewerDescriptionsString} from './utils';
5
+ import {ModelType, LLMClient} from './llm-utils/LLM-client';
6
+
7
+ type IViewerResponse = {
8
+ viewerType: string;
9
+ properties: {[index: string]: any};
10
+ }
11
+
12
+ /**
13
+ * Examples of queries:
14
+ * - plot width by height
15
+ * - show me age distribution
16
+ * - age distribution by disease
17
+ * - plot age, height, and weight on the 3d scatter plot
18
+ * - Plot width by height in a trellis plot split by race
19
+ * - Plot weight by height for selected rows only
20
+ * - form with all columns starting with "s"
21
+ * */
22
+ export async function askAiTableView(view: DG.TableView, question: string) {
23
+ const prompt = getPrompt(view, question);
24
+ //console.log(prompt);
25
+ // TODO: substitute with the OpenAI client call
26
+ const res = LLMClient.getInstance();
27
+ const answer = await res.generalPromptCached(ModelType.Fast, '', prompt);
28
+ //console.log(answer);
29
+ //grok.shell.info(answer);
30
+
31
+ const response: IViewerResponse = JSON.parse(answer);
32
+ if (DG.Viewer.CORE_VIEWER_TYPES.includes(response.viewerType))
33
+ view.addViewer(response.viewerType, response.properties);
34
+ }
35
+
36
+ export function askAiTableViewDialog(view: DG.TableView) {
37
+ const input = ui.input.textArea('Question', {value: 'Plot width by height'});
38
+
39
+ ui.dialog('Ask AI')
40
+ .addInput('Question', input)
41
+ .onOK(async () => {
42
+ askAiTableView(view, input.value);
43
+ })
44
+ .show();
45
+ }
46
+
47
+ const getPrompt = (view: DG.TableView, question: string) => {
48
+ return `
49
+ Below is the structure of the dataframe a user is working with, and the interfaces for Datagrok visualizations.
50
+ Your task is to identify which visualization to use, and which properties to set for what the user asks.
51
+ For column name properties, you can only use names from the dataframe.
52
+ Give the answer in the JSON format that can be directly parsed (no annotations or anything like that)
53
+ with the "viewerType" identifying viewer type, and
54
+ "properties" containing properties, like in this example:
55
+ {"viewerType": "Histogram", "properties": {"valueColumnName": "Age", "markerSize": 15}}
56
+
57
+ ${getCurrentViewersString(view)}
58
+
59
+ User question: ${question}
60
+
61
+ DataFrame structure:
62
+ ${JSON.stringify(getDataFrameDescription(view.dataFrame))}
63
+
64
+ Viewers:
65
+ ${getViewerDescriptionsString()}`;
66
+ };
67
+
package/tsconfig.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
5
+ /* Basic Options */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
8
+ "module": "es2020", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
9
+ "lib": ["ES2022", "dom"], /* Specify library files to be included in the compilation. */
10
+ // "allowJs": true, /* Allow javascript files to be compiled. */
11
+ // "checkJs": true, /* Report errors in .js files. */
12
+ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
13
+ // "declaration": true, /* Generates corresponding '.d.ts' file. */
14
+ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15
+ "sourceMap": true, /* Generates corresponding '.map' file. */
16
+ // "outFile": "./", /* Concatenate and emit output to single file. */
17
+ // "outDir": "./", /* Redirect output structure to the directory. */
18
+ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
19
+ // "composite": true, /* Enable project compilation */
20
+ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
21
+ // "removeComments": true, /* Do not emit comments to output. */
22
+ // "noEmit": true, /* Do not emit outputs. */
23
+ // "importHelpers": true, /* Import emit helpers from 'tslib'. */
24
+ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
25
+ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
26
+
27
+ /* Strict Type-Checking Options */
28
+ "strict": true, /* Enable all strict type-checking options. */
29
+ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
30
+ // "strictNullChecks": true, /* Enable strict null checks. */
31
+ // "strictFunctionTypes": true, /* Enable strict checking of function types. */
32
+ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
33
+ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34
+ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35
+ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
36
+
37
+ /* Additional Checks */
38
+ // "noUnusedLocals": true, /* Report errors on unused locals. */
39
+ // "noUnusedParameters": true, /* Report errors on unused parameters. */
40
+ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41
+ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42
+ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
43
+ // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
44
+
45
+ /* Module Resolution Options */
46
+ "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
47
+ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
48
+ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
49
+ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
50
+ // "typeRoots": [], /* List of folders to include type definitions from. */
51
+ // "types": [], /* Type declaration files to be included in compilation. */
52
+ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
53
+ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
54
+ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
55
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
56
+
57
+ /* Source Map Options */
58
+ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
59
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60
+ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
61
+ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
62
+
63
+ /* Experimental Options */
64
+ "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
65
+ "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
66
+
67
+ /* Advanced Options */
68
+ "skipLibCheck": true, /* Skip type checking of declaration files. */
69
+ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
70
+ },
71
+ "exclude": ["dockerfiles"]
72
+ }