@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
package/src/package.ts ADDED
@@ -0,0 +1,275 @@
1
+ /* eslint-disable max-len */
2
+ /* Do not change these import lines to match external modules in webpack configuration */
3
+ import * as grok from 'datagrok-api/grok';
4
+ import * as ui from 'datagrok-api/ui';
5
+ import * as DG from 'datagrok-api/dg';
6
+ import {ChatGptAssistant} from './prompt-engine/chatgpt-assistant';
7
+ import {ChatGPTPromptEngine} from './prompt-engine/prompt-engine';
8
+ import {findBestMatchingQuery, tableQueriesFunctionsSearchLlm} from './llm-utils/query-matching';
9
+ import {askWiki, setupAIQueryEditorUI, setupScriptsAIPanelUI, setupSearchUI, setupTableViewAIPanelUI, smartExecution} from './llm-utils/ui';
10
+ import {PackageSettings, Plan} from './prompt-engine/interfaces';
11
+ import {initModelTypeNames, ModelType, LLMClient} from './llm-utils/LLM-client';
12
+ import {LLMCredsManager} from './llm-utils/creds';
13
+ import {CombinedAISearchAssistant} from './llm-utils/combined-search';
14
+ import {JsonSchema} from './prompt-engine/interfaces';
15
+ import {genDBConnectionMeta, moveDBMetaToStickyMetaOhCoolItEvenRhymes} from './llm-utils/db-index-tools';
16
+ import {biologicsIndex} from './llm-utils/indexes/biologics-index';
17
+ import {chemblIndex} from './llm-utils/indexes/chembl-index';
18
+ import {uploadFilesToVectorStroreOneByOne} from './llm-utils/indexes/dg-repository-index';
19
+ export * from './package.g';
20
+
21
+ export class ChatGPTPackage extends DG.Package {
22
+ get settings(): PackageSettings {
23
+ return super.settings as PackageSettings;
24
+ }
25
+ }
26
+
27
+ export const _package = new ChatGPTPackage();
28
+
29
+
30
+ export class PackageFunctions {
31
+ @grok.decorators.init({tags: ['init']})
32
+ static async init() {
33
+ initModelTypeNames();
34
+ LLMCredsManager.init(_package);
35
+ setupSearchUI();
36
+ setupTableViewAIPanelUI();
37
+ setupScriptsAIPanelUI();
38
+ // LLMClient.getInstance();
39
+ // // @ts-ignore
40
+ // window.openAI = OpenAIClient.getInstance().openai;
41
+
42
+ // AIProvider.setProvider(_package.settings.APIName === 'openai chat completions' ?
43
+ // new OpenAIChatCompletionsProvider(OpenAIClient.getInstance().openai) : new OpenAIResponsesProvider(OpenAIClient.getInstance().openai)
44
+ // );
45
+ }
46
+
47
+
48
+ @grok.decorators.autostart({tags: ['autostart']})
49
+ static autostart() {
50
+ // try {
51
+ // grok.events.onViewAdded.subscribe((view) => {
52
+ // if (view.type === DG.VIEW_TYPE.TABLE_VIEW) {
53
+ // const tableView = view as DG.TableView;
54
+ // const iconFse = ui.iconSvg('ai.svg', () => setAiPanelVisibility(true), 'Ask AI \n Ctrl+I');
55
+ // tableView.setRibbonPanels([...tableView.getRibbonPanels(), [iconFse]]);
56
+ // }
57
+ // });
58
+
59
+ // initAiPanel();
60
+ // // Add keyboard shortcut for toggling AI panel
61
+ // document.addEventListener('keydown', (event) => {
62
+ // // Check for Ctrl+I (Ctrl key + I key)
63
+ // if (event.ctrlKey && event.key === 'i') {
64
+ // event.preventDefault(); // Prevent default browser behavior
65
+ // const isVisible = getAiPanelVisibility();
66
+ // setAiPanelVisibility(!isVisible);
67
+ // }
68
+ // });
69
+ // } catch (e) {
70
+ // console.log('AI autostart failed.');
71
+ // console.log(e);
72
+ // }
73
+ }
74
+
75
+
76
+ @grok.decorators.func({
77
+ meta: {role: 'searchProvider'},
78
+ })
79
+ static combinedLLMSearchProvider(): DG.SearchProvider {
80
+ const isAiConfigured = grok.ai.config.configured;
81
+ return {
82
+ 'home': {
83
+ name: 'Ask AI Assistant',
84
+ search: async (_query: string) => {
85
+ CombinedAISearchAssistant.instance.resetSearchUI();
86
+ return null;
87
+ },
88
+ getSuggestions: (_query: string) => [],
89
+ isApplicable: (query: string) => isAiConfigured ? query?.trim().length >= 2 : false,
90
+ description: 'Get answers form AI assistant',
91
+ onValueEnter: async (query) => {
92
+ isAiConfigured && query?.trim().length >= 2 &&
93
+ await CombinedAISearchAssistant.instance.searchUI(query);
94
+ }
95
+ }
96
+ } satisfies DG.SearchProvider;
97
+ }
98
+
99
+ @grok.decorators.func({meta: {
100
+ role: 'aiSearchProvider',
101
+ useWhen: 'If the user is asking questions about how to do something, how to write the code on platform, how to execute tasks, or any other questions related to Datagrok platform functionalities and capabilities. The tone of the prompt should generally sound like "how do I do this" / "what is this". for example, "what sequence notations are supported?'
102
+ }, name: 'Help',
103
+ description: 'Get answers from DeepGROK AI assistant based on Datagrok documentation and public code.', result: {type: 'widget', name: 'result'}})
104
+ static async askHelpLLMProvider(@grok.decorators.param({type: 'string'})prompt: string): Promise<DG.Widget | null> {
105
+ return await askWiki(prompt);
106
+ }
107
+
108
+ @grok.decorators.func({meta: {
109
+ role: 'aiSearchProvider',
110
+ useWhen: 'If the prompt looks like a user has a goal to achieve something with concrete input(s), and wants the system to plan and execute a series of steps/functions to achieve that goal. This relates to functions that analyse or mutate data, not get it. for example, adme properties of CHEMBL1234, enumerate some peptide, etc... Also, if the tone of the prompt sounds like "Do something to something", use this function'
111
+ }, name: 'Execute',
112
+ description: 'Plans and executes function steps to achieve needed results', result: {type: 'widget', name: 'result'}})
113
+ static async smartChainExecutionProvider(@grok.decorators.param({type: 'string'})prompt: string): Promise<DG.Widget | null> {
114
+ return await smartExecution(prompt, ModelType.Fast);
115
+ }
116
+
117
+ @grok.decorators.func({meta: {
118
+ role: 'aiSearchProvider',
119
+ useWhen: 'if the prompt suggest that the user is looking for a data table result and the prompt resembles a query pattern. for example, "bioactivity data for shigella" or "compounds similar to aspirin" or first 100 chembl compounds. there should be some parts of user prompt that could match parameters in some query, like shigella, aspirin, first 100 etc. Always use this function when user wants to get the data without any further processing or calculating'
120
+ }, name: 'Query',
121
+ description: 'Tries to find a query which has the similar pattern as the prompt user entered and executes it', result: {type: 'widget', name: 'result'}})
122
+ static async llmSearchQueryProvider(@grok.decorators.param({type: 'string'})prompt: string): Promise<DG.Widget | null> {
123
+ return await tableQueriesFunctionsSearchLlm(prompt);
124
+ }
125
+
126
+ @grok.decorators.func({
127
+ 'meta': {
128
+ 'cache': 'all',
129
+ 'cache.invalidateOn': '0 0 1 * *'
130
+ }
131
+ })
132
+ static async askAIGeneralCached(
133
+ model: string,
134
+ systemPrompt: string,
135
+ prompt: string,
136
+ schema?: JsonSchema
137
+ ): Promise<string> {
138
+ const client = LLMClient.getInstance();
139
+ // this is used only here to provide caching
140
+ return await client.generalPrompt(model, systemPrompt, prompt, schema);
141
+ }
142
+
143
+ @grok.decorators.func({
144
+ 'meta': {
145
+ 'cache': 'all',
146
+ 'cache.invalidateOn': '0 0 1 * *'
147
+ }
148
+ })
149
+ static async ask(
150
+ question: string,
151
+ ): Promise<string> {
152
+ const client = LLMClient.getInstance();
153
+ // this is used only here to provide caching
154
+ return await client.generalPrompt(ModelType.Fast, 'You are a helpful assistant.', question);
155
+ }
156
+
157
+ @grok.decorators.func({
158
+ 'meta': {
159
+ 'cache': 'all',
160
+ 'cache.invalidateOn': '0 0 1 * *'
161
+ }
162
+ })
163
+ static async getExecutionPlan(userGoal: string): Promise<string> {
164
+ const gptEngine = ChatGPTPromptEngine.getInstance(ModelType['Deep Research']);
165
+ const gptAssistant = new ChatGptAssistant(gptEngine);
166
+ const plan: Plan = await gptAssistant.plan(userGoal);
167
+ // Cache only works with scalar values, so we serialize the plan to a string
168
+ return JSON.stringify(plan);
169
+ }
170
+
171
+ @grok.decorators.func({
172
+ 'meta': {
173
+ 'cache': 'all',
174
+ 'cache.invalidateOn': '0 0 1 * *'
175
+ }
176
+ })
177
+ static async findMatchingPatternQuery(prompt: string): Promise<string> {
178
+ const queryMatchResult = await findBestMatchingQuery(prompt);
179
+ return JSON.stringify(queryMatchResult);
180
+ }
181
+
182
+ @grok.decorators.func({
183
+ 'meta': {
184
+ 'cache': 'all',
185
+ 'cache.invalidateOn': '0 0 1 * *'
186
+ }
187
+ })
188
+ static async askDocumentationCached(prompt: string): Promise<string> {
189
+ const client = LLMClient.getInstance();
190
+ return await client.getHelpAnswer(prompt);
191
+ }
192
+
193
+ // @grok.decorators.func({
194
+ // 'meta': {
195
+ // 'cache': 'all',
196
+ // 'cache.invalidateOn': '0 0 1 * *'
197
+ // }
198
+ // })
199
+ // static async generateSqlQuery(prompt: string, connectionID: string, schemaName: string): Promise<string> {
200
+ // return await generateAISqlQuery(prompt, connectionID, schemaName);
201
+ // }
202
+ @grok.decorators.func({})
203
+ static async setupAIQueryEditor(view: DG.ViewBase, connectionID: string, queryEditorRoot: HTMLElement, @grok.decorators.param({type: 'dynamic'}) setAndRunFunc: Function): Promise<boolean> {
204
+ return setupAIQueryEditorUI(view, connectionID, queryEditorRoot, setAndRunFunc as (query: string) => void);
205
+ }
206
+
207
+ @grok.decorators.func({})
208
+ static async moveMetaToDB(@grok.decorators.param({type: 'string', options: {choices: ['biologics', 'chembl']}})dbName: string): Promise<void> {
209
+ const meta = dbName === 'biologics' ? biologicsIndex : chemblIndex;
210
+ await moveDBMetaToStickyMetaOhCoolItEvenRhymes(meta);
211
+ }
212
+
213
+ @grok.decorators.func({})
214
+ static async setupVectorStore() {
215
+ const keyWordInput = ui.input.string('PassKey', {tooltipText: 'Enter the passkey for this action', placeholder: 'Type passkey here'});
216
+ ui.dialog('Index DG Repository Files to Vector Store')
217
+ .add(ui.divText('This will upload all files from DG Repository to the vector store for AI search and assistance. This may take up to an hour depending on the number of files in the repository.'))
218
+ .add(ui.divText('This action will delete the previous files and update all files. make sure to LEAVE THE PLATFORM OPEN until the process is finished.'))
219
+ .add(ui.divText('Make sure that you have set up the OpenAI API key and vector store ID in the package settings before proceeding.'))
220
+ .add(keyWordInput)
221
+ .onOK(async () => {
222
+ if (keyWordInput.value !== 'DG-index-admin') {
223
+ grok.shell.error('Incorrect passkey. Operation aborted.');
224
+ return;
225
+ }
226
+ await
227
+ uploadFilesToVectorStroreOneByOne();
228
+ })
229
+ .show();
230
+ }
231
+
232
+ @grok.decorators.func({})
233
+ static async searchForSomething() {
234
+ const query = 'anything';
235
+ const openAIClient = LLMClient.getInstance().openai;
236
+ const f = await openAIClient.vectorStores.search('vs_696fbf9985f8819191dc6f71e04b6593', {query: query, max_num_results: 5, filters: {
237
+ key: 'firstParentFolder',
238
+ type: 'eq',
239
+ value: 'datagrok-celery-task'
240
+ }});
241
+ console.log(f.data);
242
+ }
243
+
244
+
245
+ @grok.decorators.func({})
246
+ static async indexDatabaseSchema() {
247
+ grok.shell.info('Do not touch this function if you are not a developer. :D :D :D');
248
+ return;
249
+ const connections = await grok.dapi.connections.list();
250
+ const connectionsInput = ui.input.choice('Connection', {items: connections.map((c) => c.nqName), value: connections[0].nqName, nullable: false});
251
+ const getConnectionByName = (): DG.DataConnection => {
252
+ return connections.find((c) => c.nqName === connectionsInput.value)!;
253
+ };
254
+ const schemaInputRoot = ui.div([]);
255
+ let schemaInput: DG.ChoiceInput<string>;
256
+ const createSchemaInput = async () => {
257
+ ui.empty(schemaInputRoot);
258
+ const connection = getConnectionByName();
259
+ const schemas = await grok.dapi.connections.getSchemas(connection);
260
+ schemaInput = ui.input.choice('Schema', {items: schemas, value: schemas[0], nullable: false}) as DG.ChoiceInput<string>;
261
+ schemaInputRoot.append(schemaInput.root);
262
+ };
263
+ connectionsInput.onChanged.subscribe(() => createSchemaInput());
264
+ await createSchemaInput();
265
+ ui.dialog('Index Database Schema')
266
+ .add(connectionsInput)
267
+ .add(schemaInputRoot)
268
+ .onOK(async () => {
269
+ const res = await genDBConnectionMeta(getConnectionByName(), [schemaInput.value]);
270
+ grok.shell.info('Database schema indexed successfully.');
271
+ console.log(res);
272
+ DG.Utils.download(`${connectionsInput.value}_${schemaInput.value}_db_index.json`, JSON.stringify(res, (_, v) => typeof v === 'bigint' ? Number(v) : v, 2));
273
+ }).show();
274
+ }
275
+ }
@@ -0,0 +1,257 @@
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 {PromptEngine} from './prompt-engine';
6
+ import {ChatGptFuncParams, ExecutePlanResult, ExecutionContext, FunctionMeta, JsonSchema, PackageInfo, PackageSelection, PackageSelectionSchema, Plan, PlanSchema} from './interfaces';
7
+
8
+ export class ChatGptAssistant {
9
+ private delimiter = '####';
10
+
11
+ constructor(private promptEngine: PromptEngine) {}
12
+
13
+ private async chat<T>(
14
+ prompt: string,
15
+ options: { system?: string; schema: JsonSchema }
16
+ ): Promise<T> {
17
+ const systemPrompt = options.system ?? `
18
+ You are an assistant that outputs only valid JSON.
19
+ Do NOT include explanations or extra text.
20
+ User input is delimited by ${this.delimiter}.
21
+ Always respond strictly in JSON format.
22
+ `;
23
+
24
+ const raw = await this.promptEngine.generate(
25
+ `${this.delimiter}${prompt}${this.delimiter}`,
26
+ systemPrompt,
27
+ options.schema
28
+ );
29
+
30
+ try {
31
+ return JSON.parse(raw) as T;
32
+ } catch (err) {
33
+ throw new Error(`Failed to parse JSON from LLM output: ${raw}\nError: ${err}`);
34
+ }
35
+ }
36
+
37
+ private getProperties(f: DG.Func): ChatGptFuncParams {
38
+ const props: ChatGptFuncParams = {};
39
+ for (const p of f.inputs) {
40
+ props[p.name] = {
41
+ type: p.propertyType,
42
+ description: p.description ?? '',
43
+ default: p.options['default'],
44
+ optional: p.options['optional'],
45
+ };
46
+ }
47
+ return props;
48
+ }
49
+
50
+ // TODO: Substitute with the list of available roles along with descriptions
51
+ private packagesInfo: PackageInfo[] = [
52
+ {
53
+ name: 'Admetica',
54
+ description: 'Assessment of ADMET Properties',
55
+ },
56
+ {
57
+ name: 'Bio',
58
+ description: 'Bioinformatics support (import/export of sequences, HELM and other format conversion, visualization, analysis). [See more](https://github.com/datagrok-ai/public/blob/master/packages/Bio/README.md) for details.',
59
+ },
60
+ {
61
+ name: 'Chem',
62
+ description:
63
+ 'Cheminformatics support: import, rendering, sketching, calculation of properties, predictive models, augmentations, multiple analyses. Includes multiple different calculators(descriptors, properties, solubility(LogS through properties) and many more). Can be used in conjunction to peptides, conversion tools to optimize/maximize/minimize different properties.',
64
+ },
65
+ {
66
+ name: 'Chembl',
67
+ description: 'Chembl integration, commonly used queries and browser',
68
+ },
69
+ {
70
+ name: 'ClinicalCase',
71
+ description: 'Analysis of the clinical data represented in the [SDTM](https://www.cdisc.org/standards/foundational/sdtm) and [SEND](https://www.cdisc.org/standards/foundational/send) formats.',
72
+ },
73
+ {
74
+ name: 'Retrosynthesis',
75
+ description: 'Creates retrosynthesis paths for the selected molecule',
76
+ },
77
+ {
78
+ name: 'Biologics',
79
+ description: 'Database with ADC, protein sequences, peptides, drugs and their assay data. contains tools and queries into the database. compounds identifiers for peptides, sequences, drugs, ADCs etc. like GROKPEP-######, GROKADC-###### etc.',
80
+ },
81
+ {
82
+ name: 'SequenceTranslator',
83
+ description: 'Contains tools for enumerating sequences at different positions and monomers. very useful when trying to maximize/minimize/optimize certain properties of peptides/proteins by sequence enumeration.',
84
+ },
85
+ {
86
+ name: 'MolTrack',
87
+ description: 'A lightweight, flexible, and extendable FastAPI server for managing chemical compounds, batches, and properties, powered by RDKit-enabled Postgres for chemical intelligence'
88
+ }
89
+ ];
90
+
91
+ private async selectPackages(userGoal: string): Promise<string[]> {
92
+ const prompt = `User goal: "${userGoal}"
93
+ Available packages:
94
+ ${JSON.stringify(this.packagesInfo, null, 2)}
95
+
96
+ Determine which packages are relevant for achieving this goal.
97
+ Respond ONLY in JSON with the folllowing structure, no Markdown or extra text.
98
+ {
99
+ "selected_packages": [
100
+ { "name": "<package_name>", "reason": "<why this helps>" }
101
+ ]
102
+ }
103
+
104
+ Rules:
105
+ - Include only packages that can meaningfully contribute.
106
+ - Rank them from most to least relevant.
107
+ - Do not include packages that clearly don't apply.`;
108
+
109
+ const res = await this.chat<PackageSelection>(prompt, {schema: PackageSelectionSchema});
110
+ console.log('Selected packages:', res);
111
+ return res.selected_packages.map((p: any) => p.name);
112
+ }
113
+
114
+ private readonly reasoningSystemPrompt = `
115
+ You are a reasoning assistant that plans how to achieve user goals using available functions.
116
+
117
+ General output rules:
118
+ - Output ONLY valid JSON.
119
+ - Produce the smallest possible sequence of steps.
120
+ - Each step should be:
121
+ { "action": "call_function", "function": "<name>", "inputs": {...}, "outputs": [...] }
122
+
123
+ STRICT INPUT RULES (applies to ALL models):
124
+ - You MUST include EVERY REQUIRED input parameter defined for the function.
125
+ - Optional inputs:
126
+ - If a value is provided, include it in the "inputs" object.
127
+ - If no value is provided, the field may be omitted.
128
+ - Inputs with default values are treated as required:
129
+ - You MUST include them in the "inputs", even if the value equals the default.
130
+ - Leaving out a required input or a defaulted input is considered an ERROR.
131
+ - Inputs should appear exactly as defined in the function metadata.
132
+ - Today's date is ${new Date().toISOString().split('T')[0]}. Always use this date when interpreting natural language like "last week", "this year", or "next month".
133
+
134
+ Referencing previous steps:
135
+ - If an input value comes from a previous step's output, prefix it with "$".
136
+
137
+ Planning rules:
138
+ - Produce the minimal number of steps needed to achieve the user’s goal.
139
+ - If one function can directly satisfy the goal, output only that step.
140
+ - Do not use helper or lookup functions unless required by the goal.
141
+ - Ensure all steps are valid according to the function metadata.
142
+ - Include a short "analysis" explaining your reasoning.
143
+ - When asked to optimize or maximize/minimize something, make sure that the calculation of the said property is also done.
144
+ `;
145
+
146
+ private async planFunctions(userGoal: string, functions: FunctionMeta[]): Promise<Plan> {
147
+ const prompt = `
148
+ User request: "${userGoal}"
149
+ Available functions:
150
+ ${JSON.stringify(functions, null, 2)}
151
+
152
+ Analyze what needs to be done and produce the minimal sequence of steps.
153
+ Respond strictly as JSON with this structure:
154
+ {
155
+ "goal": "<restated_goal>",
156
+ "analysis": ["...reasoning..."],
157
+ "steps": [ { "action": "call_function", "function": "...", "inputs": {...}, "outputs": [...] } ]
158
+ }`;
159
+ return await this.chat<Plan>(prompt, {
160
+ system: this.reasoningSystemPrompt,
161
+ schema: PlanSchema,
162
+ });
163
+ }
164
+
165
+ private async getFunctionsByPackage(pkg: string): Promise<FunctionMeta[]> {
166
+ const funcs = DG.Func.find({package: pkg});
167
+ return funcs.map((f) => {
168
+ return {
169
+ name: f.name,
170
+ description: (f.nqName || f.package.name) + ': ' + (f.description || f.options['description'] || f.friendlyName || f.name),
171
+ inputs: {type: 'object', properties: this.getProperties(f)},
172
+ outputs: f.outputs.map((o) => ({
173
+ name: o.name,
174
+ type: o.propertyType,
175
+ }))
176
+ };
177
+ });
178
+ }
179
+
180
+ public async executePlan(plan: Plan): Promise<ExecutePlanResult | null> {
181
+ if (!plan?.steps?.length) {
182
+ console.warn('No steps to execute in plan.');
183
+ return null;
184
+ }
185
+
186
+ const context: ExecutionContext = {};
187
+ for (const [index, step] of plan.steps.entries()) {
188
+ if (step.action !== 'call_function') continue;
189
+
190
+ const func = DG.Func.find({name: step.function})[0];
191
+ if (!func) {
192
+ console.warn(`Function not found: ${step.function}`);
193
+ continue;
194
+ }
195
+
196
+ const resolvedInputs: Record<string, any> = {};
197
+ for (const [key, val] of Object.entries(step.inputs ?? {})) {
198
+ if (typeof val === 'string' && val.startsWith('$')) {
199
+ const varName = val.slice(1);
200
+ resolvedInputs[key] = context[varName]['value'];
201
+ } else
202
+ resolvedInputs[key] = val;
203
+ }
204
+
205
+ let result;
206
+ try {
207
+ result = await func.apply(resolvedInputs);
208
+ } catch (err) {
209
+ console.error(`Error executing ${func.name}:`, err);
210
+ result = null;
211
+ }
212
+
213
+ if (Array.isArray(step.outputs)) {
214
+ const outputName = step.outputs[0] ?? func.name;
215
+ const funcOutputMeta = func.outputs.length === 1 ? func.outputs[0] : func.outputs.find((o) => o.name === outputName);
216
+ context[outputName] = {value: result, meta: funcOutputMeta};
217
+ }
218
+ }
219
+
220
+ const finalKey = plan.steps.at(-1)?.outputs?.[0];
221
+ const finalResult = finalKey ? context[finalKey] : null;
222
+ if (!finalKey) {
223
+ // some functions along the steps can be such that they just alter the dataFrame and do nothing, so search for the last dataFrame in the context
224
+ for (let i = plan.steps.length - 2; i >= 0; i--) {
225
+ const step = plan.steps[i];
226
+ const outputMeta = step.outputs?.length ? context[step.outputs[0]]?.meta : null;
227
+ if (outputMeta?.propertyType === 'dataframe')
228
+ return {context, finalResult: context[step.outputs[0]]};
229
+ else if (step.outputs?.length)
230
+ break;
231
+ }
232
+ }
233
+
234
+ return {context, finalResult};
235
+ }
236
+
237
+ public async plan(userGoal: string): Promise<Plan> {
238
+ const packages = await this.selectPackages(userGoal);
239
+ await setTimeout(() => {}, 25000);
240
+
241
+ const allFunctions: FunctionMeta[] = [];
242
+ for (const pkg of packages) {
243
+ const funcs = await this.getFunctionsByPackage(pkg);
244
+ allFunctions.push(...funcs);
245
+ await setTimeout(() => {}, 25000);
246
+ }
247
+
248
+ const plan = await this.planFunctions(userGoal, allFunctions);
249
+ await setTimeout(() => {}, 25000);
250
+
251
+ return plan;
252
+ }
253
+
254
+ public async execute(plan: Plan): Promise<ExecutePlanResult | null> {
255
+ return await this.executePlan(plan);
256
+ }
257
+ }