@datagrok/grokky 1.0.4 → 1.1.0
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/.claude/skills/deploy-grokky/SKILL.md +193 -0
- package/.grokignore +2 -0
- package/.turbo/turbo-build.log +24 -0
- package/.vscode/settings.json +16 -0
- package/CHANGELOG.md +151 -8
- package/CLAUDE.md +284 -0
- package/CREDITS.md +173 -0
- package/LICENSE.md +16 -0
- package/README.md +24 -0
- package/bdd/bdd.config.json +1 -0
- package/bdd/bindings/elements.ts +9 -0
- package/bdd/bindings/steps.ts +787 -0
- package/bdd/features/ai-panel/platform-work.feature +63 -0
- package/bdd/features/ai-panel/session.feature +69 -0
- package/bdd/features/ai-panel/table-work.feature +99 -0
- package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
- package/bdd/generated/ai-panel/session.test.ts +100 -0
- package/bdd/generated/ai-panel/table-work.test.ts +150 -0
- package/bdd/package.json +1 -0
- package/bdd/tsconfig.json +13 -0
- package/css/ai.css +637 -49
- package/dist/package-test.js +4 -1707
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +742 -92317
- package/dist/package.js.map +1 -1
- package/dockerfiles/claude-runtime/.dockerignore +1 -0
- package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
- package/dockerfiles/claude-runtime/Dockerfile +73 -13
- package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
- package/dockerfiles/claude-runtime/container.json +2 -2
- package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
- package/dockerfiles/claude-runtime/package-lock.json +1721 -306
- package/dockerfiles/claude-runtime/package.json +20 -5
- package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
- package/dockerfiles/claude-runtime/pyproject.toml +18 -0
- package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
- package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
- package/dockerfiles/claude-runtime/src/constants.ts +20 -0
- package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
- package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
- package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
- package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
- package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
- package/dockerfiles/claude-runtime/src/server.ts +134 -234
- package/dockerfiles/claude-runtime/src/session.ts +328 -0
- package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
- package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
- package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
- package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
- package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
- package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
- package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
- package/dockerfiles/claude-runtime/src/types.ts +142 -23
- package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
- package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
- package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
- package/dockerfiles/claude-runtime/src/verify.ts +136 -0
- package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
- package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
- package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
- package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
- package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
- package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
- package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
- package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
- package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
- package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
- package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
- package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
- package/dockerfiles/mcp-server/.eslintrc.json +39 -0
- package/dockerfiles/mcp-server/Dockerfile +10 -2
- package/dockerfiles/mcp-server/package-lock.json +1743 -98
- package/dockerfiles/mcp-server/package.json +27 -5
- package/dockerfiles/mcp-server/src/api-client.ts +123 -66
- package/dockerfiles/mcp-server/src/format.ts +51 -0
- package/dockerfiles/mcp-server/src/index.ts +44 -113
- package/dockerfiles/mcp-server/src/ops.ts +325 -0
- package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
- package/dockerfiles/mcp-server/test/format.test.js +62 -0
- package/dockerfiles/mcp-server/test/ops.test.js +84 -0
- package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
- package/dockerfiles/queue/Dockerfile +2 -0
- package/dockerfiles/queue/container.json +7 -0
- package/docs/AUDIT-2026-08-03.md +1064 -0
- package/docs/BENCHMARK.md +292 -0
- package/docs/CLAUDE_CODE_FLOW.md +746 -0
- package/docs/EXAMPLES.md +82 -0
- package/docs/FEATURES.md +71 -0
- package/docs/IMPLEMENTATION.md +128 -0
- package/docs/LATENCY.md +170 -0
- package/docs/VISION.md +36 -0
- package/files/benchmark/suite.yaml +404 -0
- package/files/scripts/process-cro-results.md +14 -0
- package/files/suggestions.yaml +344 -0
- package/package.json +39 -97
- package/src/ai/ai-window.ts +157 -0
- package/src/ai/benchmark/benchmark.ts +737 -0
- package/src/ai/db-view-functions.ts +56 -0
- package/src/ai/engine.ts +98 -0
- package/src/ai/gemma-engine.ts +81 -0
- package/src/ai/panel.ts +1385 -0
- package/src/ai/prompt-suggestions.ts +209 -0
- package/src/ai/search/combined-search.ts +244 -0
- package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
- package/src/{llm-utils → ai}/storage.ts +0 -1
- package/src/ai/table-tools.ts +145 -0
- package/src/ai/ui.ts +720 -0
- package/src/ai/usage-limiter.ts +105 -0
- package/src/ai/view-tools.ts +352 -0
- package/src/claude/ai-feature.ts +16 -0
- package/src/claude/exec-blocks.ts +176 -0
- package/src/claude/queue-task.ts +84 -0
- package/src/claude/runtime-client.ts +310 -0
- package/src/claude/turn-log.ts +114 -0
- package/src/claude/undoable.ts +105 -0
- package/src/{llm-utils → db}/db-index-tools.ts +24 -32
- package/src/db/sql-tools.ts +336 -0
- package/src/depr/LLM-client.ts +251 -0
- package/src/depr/ai-panel.ts +174 -0
- package/src/depr/chatgpt-assistant.ts +257 -0
- package/src/depr/creds.ts +30 -0
- package/src/depr/deepwikiclient.ts +118 -0
- package/src/depr/indexes/dg-repository-index.ts +266 -0
- package/src/depr/interfaces.ts +170 -0
- package/src/depr/is-help-request.ts +39 -0
- package/src/depr/prompt-engine.ts +52 -0
- package/src/depr/rendering-tools.ts +103 -0
- package/src/depr/script-tools.ts +785 -0
- package/src/depr/tableview-tools.ts +746 -0
- package/src/depr/viewers-ai.ts +67 -0
- package/src/package-api.ts +87 -28
- package/src/package-test.ts +1 -0
- package/src/package.g.ts +98 -48
- package/src/package.ts +211 -157
- package/src/polyfills.ts +12 -0
- package/src/utils.ts +128 -0
- package/tsconfig.json +8 -70
- package/webpack.config.js +3 -49
- package/.eslintignore +0 -2
- package/src/ai-panel.ts +0 -174
- package/src/claude-code/claude-panel.ts +0 -34
- package/src/claude-code/claude-runtime-client.ts +0 -148
- package/src/llm-utils/LLM-client.ts +0 -251
- package/src/llm-utils/combined-search.ts +0 -162
- package/src/llm-utils/creds.ts +0 -30
- package/src/llm-utils/deepwikiclient.ts +0 -118
- package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
- package/src/llm-utils/panel.ts +0 -866
- package/src/llm-utils/script-tools.ts +0 -784
- package/src/llm-utils/sql-tools.ts +0 -840
- package/src/llm-utils/tableview-tools.ts +0 -704
- package/src/llm-utils/ui.ts +0 -315
- package/src/prompt-engine/chatgpt-assistant.ts +0 -257
- package/src/prompt-engine/interfaces.ts +0 -170
- package/src/prompt-engine/prompt-engine.ts +0 -52
- package/src/prompt-engine/rendering-tools.ts +0 -103
- package/src/prompts/is-help-request.ts +0 -26
- package/src/viewers-ai.ts +0 -67
- /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
- /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
- /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
- /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
- /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
- /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import * as grok from 'datagrok-api/grok';
|
|
2
|
+
import * as DG from 'datagrok-api/dg';
|
|
3
|
+
import * as jsyaml from 'js-yaml';
|
|
4
|
+
|
|
5
|
+
import {_package} from '../package';
|
|
6
|
+
|
|
7
|
+
type Scope = 'column' | 'view' | 'global';
|
|
8
|
+
type Context = 'powerSearch' | 'panel';
|
|
9
|
+
export type SearchProvider = 'Help' | 'Execute' | 'Query';
|
|
10
|
+
|
|
11
|
+
export interface Suggestion {
|
|
12
|
+
label?: string;
|
|
13
|
+
/** The prompt sent to the assistant. Omitted for `action` suggestions handled client-side. */
|
|
14
|
+
prompt?: string;
|
|
15
|
+
/** A client-side action key (see [SUGGESTION_ACTIONS]) — runs immediately instead of prompting the AI. */
|
|
16
|
+
action?: string;
|
|
17
|
+
prefer?: Record<string, string>;
|
|
18
|
+
/** Packages whose functions must be registered for this prompt to work (e.g. [Chem]). */
|
|
19
|
+
requires?: string[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Block {
|
|
23
|
+
context: Context;
|
|
24
|
+
scope: Scope;
|
|
25
|
+
key: string;
|
|
26
|
+
match?: {semType?: string; type?: string};
|
|
27
|
+
label: string;
|
|
28
|
+
icon?: string;
|
|
29
|
+
color?: string;
|
|
30
|
+
requires?: string[];
|
|
31
|
+
provider?: SearchProvider;
|
|
32
|
+
suggestions: Suggestion[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// TODO: LLM-curated suggestions vs current human + view-agnostic heuristics?
|
|
36
|
+
const SLOT = /\{(\w+)\.(\w+)}/g;
|
|
37
|
+
let _cache: Block[] | null = null;
|
|
38
|
+
const MAX_GROUPING_CATEGORIES = 50;
|
|
39
|
+
|
|
40
|
+
enum SlotFilter {
|
|
41
|
+
Numerical = 'isNumerical',
|
|
42
|
+
Categorical = 'isCategorical',
|
|
43
|
+
DateTime = 'isDateTime',
|
|
44
|
+
SemType = 'semType',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type SlotColumns = (filter: SlotFilter, semType?: string) => DG.Column[];
|
|
48
|
+
|
|
49
|
+
const SLOT_COLUMNS: Record<SlotFilter, (cols: DG.ColumnList, semType?: string) => Iterable<DG.Column>> = {
|
|
50
|
+
[SlotFilter.Numerical]: (cols) => cols.numericalNoDateTime,
|
|
51
|
+
[SlotFilter.Categorical]: (cols) => cols.categorical,
|
|
52
|
+
[SlotFilter.DateTime]: (cols) => cols.dateTime,
|
|
53
|
+
[SlotFilter.SemType]: (cols, semType) => semType ? cols.bySemTypeAll(semType) : [],
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const isSlotFilter = (filter: string): filter is SlotFilter => filter in SLOT_COLUMNS;
|
|
57
|
+
|
|
58
|
+
function isGrouping(c: DG.Column): boolean {
|
|
59
|
+
const n = c.categories.length;
|
|
60
|
+
return n > 1 && n <= MAX_GROUPING_CATEGORIES;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function slotColumns(df: DG.DataFrame): SlotColumns {
|
|
64
|
+
const lists = new Map<string, DG.Column[]>();
|
|
65
|
+
return (filter, semType) => {
|
|
66
|
+
const key = filter === SlotFilter.SemType ? `${filter}:${semType}` : filter;
|
|
67
|
+
let list = lists.get(key);
|
|
68
|
+
if (!list) {
|
|
69
|
+
const first: DG.Column[] = [];
|
|
70
|
+
const rest: DG.Column[] = [];
|
|
71
|
+
for (const c of SLOT_COLUMNS[filter](df.columns, semType))
|
|
72
|
+
(filter === SlotFilter.Categorical && !isGrouping(c) ? rest : first).push(c);
|
|
73
|
+
lists.set(key, list = first.concat(rest));
|
|
74
|
+
}
|
|
75
|
+
return list;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const _pkgAvailable = new Set<string>();
|
|
80
|
+
|
|
81
|
+
function requiresMet(req?: string[]): boolean {
|
|
82
|
+
return !req || req.every((p) => {
|
|
83
|
+
if (!_pkgAvailable.has(p) && DG.Func.find({package: p}).length > 0)
|
|
84
|
+
_pkgAvailable.add(p);
|
|
85
|
+
return _pkgAvailable.has(p);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function load(): Promise<Block[]> {
|
|
90
|
+
if (!_cache)
|
|
91
|
+
_cache = jsyaml.load(await _package.files.readAsText('suggestions.yaml')) as Block[];
|
|
92
|
+
return _cache;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function resolveSuggestion(s: Suggestion, columns: SlotColumns | null, semType?: string): Suggestion | null {
|
|
96
|
+
const pickedCols: Record<string, DG.Column> = {};
|
|
97
|
+
const taken = new Set<DG.Column>();
|
|
98
|
+
|
|
99
|
+
const slotSource = `${s.label ?? ''}\n${s.prompt ?? ''}`;
|
|
100
|
+
for (const [, name, filter] of slotSource.matchAll(SLOT)) {
|
|
101
|
+
if (name in pickedCols) continue;
|
|
102
|
+
if (!columns || !isSlotFilter(filter)) return null;
|
|
103
|
+
const candidates = columns(filter, semType).filter((c) => !taken.has(c));
|
|
104
|
+
if (!candidates.length) return null;
|
|
105
|
+
|
|
106
|
+
const prefer = s.prefer?.[name];
|
|
107
|
+
const re = prefer ? new RegExp(prefer.match(/name~="([^"]+)"/)?.[1] ?? prefer, 'i') : null;
|
|
108
|
+
const pick = (re && candidates.find((c) => re.test(c.name))) || candidates[0];
|
|
109
|
+
pickedCols[name] = pick;
|
|
110
|
+
taken.add(pick);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const fill = (t: string): string => t
|
|
114
|
+
.replace(/\{(\w+)((?:\.\w+)+)}/g, (_, n, path) => {
|
|
115
|
+
if (!path.includes('.', 1))
|
|
116
|
+
return pickedCols[n]?.name ?? '';
|
|
117
|
+
let val: unknown = pickedCols[n];
|
|
118
|
+
for (const key of path.slice(1).split('.'))
|
|
119
|
+
val = (val as Record<string, unknown> | undefined)?.[key];
|
|
120
|
+
return `${val ?? ''}`;
|
|
121
|
+
});
|
|
122
|
+
return {
|
|
123
|
+
label: s.label ? fill(s.label) : undefined,
|
|
124
|
+
prompt: s.prompt ? fill(s.prompt) : undefined,
|
|
125
|
+
action: s.action,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function resolveScopes(context: Context, view: DG.ViewBase | null = null): Promise<Block[]> {
|
|
130
|
+
const df = view instanceof DG.TableView ? view.dataFrame ?? null : null;
|
|
131
|
+
const columns = df ? slotColumns(df) : null;
|
|
132
|
+
const out: Block[] = [];
|
|
133
|
+
for (const b of await load()) {
|
|
134
|
+
if (b.context !== context) continue;
|
|
135
|
+
const applies = b.scope === 'global' ||
|
|
136
|
+
(b.scope === 'view' && view?.type === b.match?.type) ||
|
|
137
|
+
(b.scope === 'column' && !!df?.columns.bySemType(b.match?.semType ?? ''));
|
|
138
|
+
if (!applies || !requiresMet(b.requires)) continue;
|
|
139
|
+
|
|
140
|
+
const suggestions = b.suggestions
|
|
141
|
+
.map((s) => requiresMet(s.requires) ? resolveSuggestion(s, columns, b.match?.semType) : null)
|
|
142
|
+
.filter((s): s is Suggestion => !!s);
|
|
143
|
+
if (suggestions.length)
|
|
144
|
+
out.push({...b, suggestions});
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function showSuggestionsMenu(
|
|
150
|
+
scopes: Block[],
|
|
151
|
+
onSelect: (s: Suggestion, provider?: SearchProvider) => void,
|
|
152
|
+
causedBy?: MouseEvent,
|
|
153
|
+
): void {
|
|
154
|
+
const menu = DG.Menu.popup();
|
|
155
|
+
for (const s of scopes) {
|
|
156
|
+
const group = menu.group(s.label);
|
|
157
|
+
for (const sg of s.suggestions)
|
|
158
|
+
group.item(sg.label ?? sg.prompt ?? '', () => onSelect(sg, s.provider));
|
|
159
|
+
}
|
|
160
|
+
menu.show(causedBy ? {causedBy} : undefined);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ---- Client-side actions -------------------------------------------------------------
|
|
164
|
+
// Some suggestions are ambiguous for the AI (e.g. "open a demo dataset"): resolving them
|
|
165
|
+
// with a quick in-panel choice is faster and more predictable than a round-trip to the assistant.
|
|
166
|
+
|
|
167
|
+
/** One selectable option in an in-panel choice block. */
|
|
168
|
+
export interface ChoiceOption {
|
|
169
|
+
label: string;
|
|
170
|
+
onSelect: () => void;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The panel surface an action renders into — it draws the choices as an assistant-style response. */
|
|
174
|
+
export interface SuggestionActionHost {
|
|
175
|
+
addChoice(prompt: string | null, options: ChoiceOption[]): void;
|
|
176
|
+
addNote(markdown: string): void;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const DEMO_DATASETS: {label: string; open: () => Promise<DG.DataFrame>}[] = [
|
|
180
|
+
{label: 'Demographics (clinical)', open: () => grok.dapi.files.readCsv('System:DemoFiles/demog.csv')},
|
|
181
|
+
{label: 'SPGI (small molecules)', open: () => grok.dapi.files.readCsv('System:DemoFiles/chem/SPGI.csv')},
|
|
182
|
+
{label: 'Dose-response curves', open: () => grok.dapi.files.readCsv('System:DemoFiles/curves.csv')},
|
|
183
|
+
{label: 'Beer reviews', open: () => grok.dapi.files.readCsv('System:DemoFiles/beer.csv')},
|
|
184
|
+
{label: 'Random walk', open: async () => grok.data.demo.randomWalk()},
|
|
185
|
+
];
|
|
186
|
+
|
|
187
|
+
function openDemoDataset(d: {label: string; open: () => Promise<DG.DataFrame>}, host: SuggestionActionHost): void {
|
|
188
|
+
d.open()
|
|
189
|
+
.then((df) => {
|
|
190
|
+
grok.shell.addTableView(df);
|
|
191
|
+
host.addNote(`Opened the **${d.label}** table.`);
|
|
192
|
+
})
|
|
193
|
+
.catch((e) => grok.shell.error(`Couldn't open ${d.label}: ${e}`));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const SUGGESTION_ACTIONS: Record<string, (host: SuggestionActionHost) => void> = {
|
|
197
|
+
openDemoDataset: (host) => host.addChoice(
|
|
198
|
+
'Which demo dataset would you like to open?',
|
|
199
|
+
DEMO_DATASETS.map((d) => ({label: d.label, onSelect: () => openDemoDataset(d, host)})),
|
|
200
|
+
),
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/** Runs a suggestion's client-side action into the given panel host, if it has one. Returns whether it was handled. */
|
|
204
|
+
export function runSuggestionAction(action: string | undefined, host: SuggestionActionHost): boolean {
|
|
205
|
+
const handler = action ? SUGGESTION_ACTIONS[action] : undefined;
|
|
206
|
+
if (handler)
|
|
207
|
+
handler(host);
|
|
208
|
+
return !!handler;
|
|
209
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/* eslint-disable max-len */
|
|
2
|
+
|
|
3
|
+
import * as grok from 'datagrok-api/grok';
|
|
4
|
+
import * as DG from 'datagrok-api/dg';
|
|
5
|
+
import * as ui from 'datagrok-api/ui';
|
|
6
|
+
import * as rxjs from 'rxjs';
|
|
7
|
+
import {ClaudeRuntimeClient} from '../../claude/runtime-client';
|
|
8
|
+
import {UsageLimiter} from '../usage-limiter';
|
|
9
|
+
import {AIPanel} from '../panel';
|
|
10
|
+
import {runPromptWithLifecycle, RENDERED_EVENT} from '../ui';
|
|
11
|
+
import {AiFeature} from '../../claude/ai-feature';
|
|
12
|
+
import {SearchProvider} from '../prompt-suggestions';
|
|
13
|
+
|
|
14
|
+
interface AISearchFuncInfo {
|
|
15
|
+
func: DG.Func;
|
|
16
|
+
friendlyName: string;
|
|
17
|
+
inputName: string;
|
|
18
|
+
order: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The idea is to provide single AI search provider which will decide which LLM to use based on user prompt.
|
|
23
|
+
* This class will not care about individual LLM implementations, nor the presence of api keys and other needed things.
|
|
24
|
+
*/
|
|
25
|
+
const SEARCH_FEATURES: {[func: string]: AiFeature} = {Help: AiFeature.Help, Execute: AiFeature.Execute};
|
|
26
|
+
|
|
27
|
+
export class CombinedAISearchAssistant {
|
|
28
|
+
private collectFunctions(): {[name: string]: AISearchFuncInfo} {
|
|
29
|
+
// these function should have descriptions, one input of a string prompt and an output of a widget. meta.useWhen must be defined as well
|
|
30
|
+
const functions = DG.Func.find({meta: {role: 'aiSearchProvider'}}).filter((f) => f.inputs.length >= 1 && f.inputs[0].type === 'string' &&
|
|
31
|
+
f.description && f.outputs.length === 1 && (f.outputs[0].type as string) === 'widget' && f.options.useWhen);
|
|
32
|
+
|
|
33
|
+
const functionMap: {[name: string]: AISearchFuncInfo} = {};
|
|
34
|
+
for (const f of functions) {
|
|
35
|
+
functionMap[f.name] = {
|
|
36
|
+
func: f,
|
|
37
|
+
friendlyName: f.friendlyName ?? f.name,
|
|
38
|
+
inputName: f.inputs[0].name,
|
|
39
|
+
order: Number.parseInt(f.options.order ?? '0') ?? 0,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return functionMap;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private functions: {[name: string]: AISearchFuncInfo};
|
|
46
|
+
private constructor() {
|
|
47
|
+
this.functions = this.collectFunctions();
|
|
48
|
+
}
|
|
49
|
+
private static _instance: CombinedAISearchAssistant | null = null;
|
|
50
|
+
public static get instance(): CombinedAISearchAssistant {
|
|
51
|
+
if (this._instance === null)
|
|
52
|
+
this._instance = new CombinedAISearchAssistant();
|
|
53
|
+
return this._instance;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
public async getResultWidget(prompt: string, provider?: SearchProvider): Promise<DG.Widget | null> {
|
|
57
|
+
// a provider is the tab's friendly name; the order holds function names, as the ranking returns
|
|
58
|
+
const direct = provider ? Object.values(this.functions).find((f) => f.friendlyName === provider)?.func.name : undefined;
|
|
59
|
+
const functionOrder = direct ? [direct] : await this.getRelevantFunctionOrder(prompt);
|
|
60
|
+
console.log(`Function order for execution: ${functionOrder.join(', ')}`);
|
|
61
|
+
const remainingFunctions = Object.keys(this.functions).filter((fn) => !functionOrder.includes(fn));
|
|
62
|
+
let moreBtn: HTMLButtonElement | null = null;
|
|
63
|
+
// create a lazy tabcontrol with all functions, but the chosen one first
|
|
64
|
+
const tabcontrol = ui.tabControl();
|
|
65
|
+
|
|
66
|
+
const addFunctionTab = (functionName: string, setAsCurrentPane: boolean = false) => {
|
|
67
|
+
const funcInfo = this.functions[functionName];
|
|
68
|
+
let cachedHost: HTMLElement | null = null;
|
|
69
|
+
const pane = tabcontrol.addPane(funcInfo.friendlyName, () => {
|
|
70
|
+
if (!cachedHost)
|
|
71
|
+
cachedHost = this.buildFunctionTabContent(funcInfo, prompt);
|
|
72
|
+
return cachedHost;
|
|
73
|
+
});
|
|
74
|
+
if (setAsCurrentPane) tabcontrol.currentPane = pane;
|
|
75
|
+
ui.tooltip.bind(pane.header, funcInfo.func.description);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const handleBtnClick = () => {
|
|
79
|
+
const menu = ui.popupMenu();
|
|
80
|
+
for (const functionName of remainingFunctions) {
|
|
81
|
+
const funcFn = this.functions[functionName].friendlyName;
|
|
82
|
+
menu.item(funcFn, () => {
|
|
83
|
+
// Remove selected function from remaining list
|
|
84
|
+
const index = remainingFunctions.indexOf(functionName);
|
|
85
|
+
if (index !== -1) remainingFunctions.splice(index, 1);
|
|
86
|
+
|
|
87
|
+
if (moreBtn && tabcontrol.header.contains(moreBtn))
|
|
88
|
+
tabcontrol.header.removeChild(moreBtn);
|
|
89
|
+
|
|
90
|
+
addFunctionTab(functionName, true);
|
|
91
|
+
|
|
92
|
+
if (moreBtn && remainingFunctions.length > 0)
|
|
93
|
+
tabcontrol.header.appendChild(moreBtn);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
menu.show();
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
for (const functionName of functionOrder)
|
|
100
|
+
addFunctionTab(functionName);
|
|
101
|
+
|
|
102
|
+
if (remainingFunctions.length) {
|
|
103
|
+
moreBtn = ui.button('...', () => handleBtnClick(), 'Click to see other options');
|
|
104
|
+
tabcontrol.header.appendChild(moreBtn);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
tabcontrol.root.style.width = '100%';
|
|
108
|
+
tabcontrol.root.style.height = 'unset';
|
|
109
|
+
tabcontrol.root.style.minHeight = '300px';
|
|
110
|
+
// d4 TabControl auto-hides the header stripe when only one pane is added; force it visible so tabs always show
|
|
111
|
+
tabcontrol.header.style.display = 'flex';
|
|
112
|
+
return DG.Widget.fromRoot(tabcontrol.root);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private buildFunctionTabContent(funcInfo: AISearchFuncInfo, prompt: string): HTMLElement {
|
|
116
|
+
const host = ui.divV([], 'grokky-ai-search-tab-host');
|
|
117
|
+
const chat = new AIPanel(`search-${funcInfo.func.name}`, grok.shell.v, {inline: true, feature: SEARCH_FEATURES[funcInfo.friendlyName]});
|
|
118
|
+
chat.onRunRequest.subscribe((a) => runPromptWithLifecycle(chat, a.currentPrompt.prompt, grok.shell.v, 'search', undefined, a.currentPrompt.isAnswer));
|
|
119
|
+
|
|
120
|
+
host.appendChild(ui.wait(async () => {
|
|
121
|
+
const client = ClaudeRuntimeClient.getInstance();
|
|
122
|
+
const firstStreamingEvent = new Promise<void>((resolve) => {
|
|
123
|
+
const sub = rxjs.merge(client.onChunk, client.onToolActivity).subscribe((evt) => {
|
|
124
|
+
if (evt.sessionId !== chat.sessionId)
|
|
125
|
+
return;
|
|
126
|
+
sub.unsubscribe();
|
|
127
|
+
resolve();
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
const rendered = new Promise<void>((resolve) => {
|
|
131
|
+
const sub = grok.events.onCustomEvent(RENDERED_EVENT).subscribe((s) => {
|
|
132
|
+
if (s !== chat.sessionId)
|
|
133
|
+
return;
|
|
134
|
+
sub.unsubscribe();
|
|
135
|
+
resolve();
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
const inputParam: {[key: string]: any} = {[funcInfo.inputName]: prompt};
|
|
140
|
+
if (funcInfo.func.inputs.some((i) => i.name === 'sessionId'))
|
|
141
|
+
inputParam['sessionId'] = chat.sessionId;
|
|
142
|
+
const widget = await funcInfo.func.apply(inputParam) as DG.Widget | null;
|
|
143
|
+
|
|
144
|
+
const mount = ui.div();
|
|
145
|
+
if (widget == null) {
|
|
146
|
+
chat.mountInto(mount);
|
|
147
|
+
chat.appendArtifact(ui.divText('No result generated.'));
|
|
148
|
+
return mount;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
await Promise.race([firstStreamingEvent, rendered]);
|
|
152
|
+
chat.mountInto(mount);
|
|
153
|
+
widget.root.style.width = '100%';
|
|
154
|
+
chat.appendArtifact(widget.root);
|
|
155
|
+
return mount;
|
|
156
|
+
}));
|
|
157
|
+
|
|
158
|
+
return host;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private lastUiprompt: string = '';
|
|
162
|
+
public resetSearchUI() {
|
|
163
|
+
this.lastUiprompt = '';
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
public async searchUI(prompt: string, provider?: SearchProvider) {
|
|
167
|
+
if (this.lastUiprompt === prompt)
|
|
168
|
+
return;
|
|
169
|
+
this.lastUiprompt = prompt;
|
|
170
|
+
if (!await UsageLimiter.getInstance().tryCheckAndIncrement('search', 'Fast'))
|
|
171
|
+
return;
|
|
172
|
+
// add components to right places in ui
|
|
173
|
+
const searchResultHost = document.getElementsByClassName('power-pack-search-host')[0];
|
|
174
|
+
if (!searchResultHost) {
|
|
175
|
+
console.warn('No search result host found for combined AI search.');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const spinner = ui.icons.spinner();
|
|
179
|
+
spinner.style.color = 'var(--blue-1)';
|
|
180
|
+
const searchingText = ui.divText('Grokking your question...', {style: {marginLeft: '8px'}});
|
|
181
|
+
const loader = ui.divH([spinner, searchingText], {style: {alignItems: 'center', marginTop: '8px'}});
|
|
182
|
+
const widgetDiv = ui.divV([loader], {style: {marginTop: '8px', marginBottom: '8px', alignItems: 'center', justifyContent: 'center', height: '100px'}});
|
|
183
|
+
searchResultHost.prepend(widgetDiv);
|
|
184
|
+
try {
|
|
185
|
+
const widgetResult = await this.getResultWidget(prompt, provider);
|
|
186
|
+
if (!widgetResult)
|
|
187
|
+
throw new Error('No result widget generated.');
|
|
188
|
+
loader.remove();
|
|
189
|
+
widgetDiv.style.removeProperty('align-items');
|
|
190
|
+
widgetDiv.style.removeProperty('justify-content');
|
|
191
|
+
widgetDiv.style.removeProperty('height');
|
|
192
|
+
widgetDiv.appendChild(widgetResult.root);
|
|
193
|
+
} catch (error: any) {
|
|
194
|
+
console.error('Error during Combined AI search:', error);
|
|
195
|
+
widgetDiv.appendChild(ui.divText(`Error during Combined AI search: ${error.message}`));
|
|
196
|
+
} finally {
|
|
197
|
+
loader.remove();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private async getRelevantFunctionOrder(prompt: string) {
|
|
202
|
+
const functionNames = Object.keys(this.functions);
|
|
203
|
+
const fullPrompt = `You are an intelligent assistant that helps to choose the best AI tool for a user's search query.
|
|
204
|
+
Given the following available functions and their descriptions along with descriptions of when to use them, rank only relevant functions in correct order (first being the best choice).
|
|
205
|
+
Leave out the functions only if they are super irrelevant, otherwise include them but make sure the best function is first in the list.
|
|
206
|
+
Available functions:
|
|
207
|
+
${Object.values(this.functions).map((f) => `Function name: ${f.func.name}
|
|
208
|
+
Description: ${f.func.description}
|
|
209
|
+
Use when: ${f.func.options.useWhen}`).join('\n\n')}
|
|
210
|
+
|
|
211
|
+
User query: ${prompt}`;
|
|
212
|
+
|
|
213
|
+
const orderSchema = {
|
|
214
|
+
type: 'object',
|
|
215
|
+
properties: {
|
|
216
|
+
order: {
|
|
217
|
+
type: 'array',
|
|
218
|
+
items: {type: 'string', enum: functionNames},
|
|
219
|
+
description: 'Function names ranked by relevance, best first. Omit only clearly irrelevant functions.',
|
|
220
|
+
},
|
|
221
|
+
},
|
|
222
|
+
required: ['order'],
|
|
223
|
+
additionalProperties: false,
|
|
224
|
+
} as const;
|
|
225
|
+
|
|
226
|
+
let order = functionNames;
|
|
227
|
+
try {
|
|
228
|
+
const res = await ClaudeRuntimeClient.getInstance().query(fullPrompt, {
|
|
229
|
+
systemPromptMode: 'none',
|
|
230
|
+
outputSchema: orderSchema,
|
|
231
|
+
feature: AiFeature.Search,
|
|
232
|
+
logPrompt: prompt,
|
|
233
|
+
});
|
|
234
|
+
const parsed = (res as {order?: unknown})?.order;
|
|
235
|
+
if (Array.isArray(parsed) && parsed.every((s) => typeof s === 'string' && this.functions[s]) && parsed.length > 0)
|
|
236
|
+
order = parsed as string[];
|
|
237
|
+
else
|
|
238
|
+
console.error('Invalid function order response:', res);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
console.error('Error getting function order from Claude:', error);
|
|
241
|
+
}
|
|
242
|
+
return order;
|
|
243
|
+
}
|
|
244
|
+
}
|