@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,56 @@
|
|
|
1
|
+
import * as grok from 'datagrok-api/grok';
|
|
2
|
+
import * as DG from 'datagrok-api/dg';
|
|
3
|
+
import {SQLGenerationContext} from '../db/sql-tools';
|
|
4
|
+
|
|
5
|
+
// Implementations of the `meta.viewType: DataQueryView` package functions (package.ts).
|
|
6
|
+
// They complement the Dart-native functions the query view returns from getFunctions()
|
|
7
|
+
// (getQueryInfo / setQueryAndRun) with SQL schema exploration and test execution.
|
|
8
|
+
// Each takes the generic `view` (the current DataQueryView) as its first argument.
|
|
9
|
+
|
|
10
|
+
const sqlContexts = new Map<string, Promise<SQLGenerationContext>>();
|
|
11
|
+
|
|
12
|
+
async function getSqlContext(connectionId: string): Promise<SQLGenerationContext> {
|
|
13
|
+
if (!sqlContexts.has(connectionId)) {
|
|
14
|
+
sqlContexts.set(connectionId, (async () => {
|
|
15
|
+
const connection = await grok.dapi.connections.find(connectionId);
|
|
16
|
+
const catalog = connection?.parameters?.['catalog'] ?? connection?.parameters?.['db'] ?? '';
|
|
17
|
+
return SQLGenerationContext.create(connectionId, catalog);
|
|
18
|
+
})());
|
|
19
|
+
}
|
|
20
|
+
return sqlContexts.get(connectionId)!;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The connection is discovered through the view's own Dart-native getQueryInfo function. */
|
|
24
|
+
async function queryViewContext(view: any): Promise<SQLGenerationContext> {
|
|
25
|
+
const info = (view?.getFunctions?.() as DG.Func[] | undefined)?.find((f) => f.name === 'getQueryInfo');
|
|
26
|
+
const connectionId = info ? ((await info.apply({})) ?? {})['connectionId'] : null;
|
|
27
|
+
if (!connectionId)
|
|
28
|
+
throw new Error('This view has no database connection');
|
|
29
|
+
return getSqlContext(connectionId);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const splitTables = (tables: string) => (tables ?? '').split(',').map((t) => t.trim()).filter((t) => t.length > 0);
|
|
33
|
+
|
|
34
|
+
export async function listDbCatalogs(view: any): Promise<string> {
|
|
35
|
+
return (await (await queryViewContext(view)).listCatalogs()).join(', ');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function listDbSchemas(view: any, catalogName?: string): Promise<string> {
|
|
39
|
+
return (await (await queryViewContext(view)).listAllSchemas(catalogName)).join(', ');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function listDbTables(view: any, schemaName: string, catalogName?: string): Promise<string> {
|
|
43
|
+
return (await (await queryViewContext(view)).listTables(false, schemaName, catalogName)).description;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function getDbTableDetails(view: any, tables: string): Promise<string> {
|
|
47
|
+
return (await queryViewContext(view)).describeTables(splitTables(tables));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function listDbJoins(view: any, tables: string): Promise<string> {
|
|
51
|
+
return (await queryViewContext(view)).listJoins(splitTables(tables));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function getSqlTestResult(view: any, sql: string, description: string): Promise<string> {
|
|
55
|
+
return (await queryViewContext(view)).trySql(sql, description ?? '');
|
|
56
|
+
}
|
package/src/ai/engine.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import * as DG from 'datagrok-api/dg';
|
|
2
|
+
import * as rxjs from 'rxjs';
|
|
3
|
+
import {ClaudeRuntimeClient, FinalEvent, ImageAttachment} from '../claude/runtime-client';
|
|
4
|
+
import {AiFeature} from '../claude/ai-feature';
|
|
5
|
+
|
|
6
|
+
export class ClaudeEngine extends DG.AIEngine {
|
|
7
|
+
id = 'claude';
|
|
8
|
+
name = 'Grokky';
|
|
9
|
+
|
|
10
|
+
private client = ClaudeRuntimeClient.getInstance();
|
|
11
|
+
|
|
12
|
+
available(): Promise<boolean> {
|
|
13
|
+
return this.client.discover();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async chat(options: DG.AIChatOptions = {}): Promise<DG.AIChat> {
|
|
17
|
+
return new ClaudeChat(this.client, options);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The runtime keeps the transcript under the session id; it has no system prompt field, so
|
|
22
|
+
* `systemPrompt` goes in front of the first message. */
|
|
23
|
+
class ClaudeChat extends DG.AIChat {
|
|
24
|
+
private sessionId = `${AiFeature.Engine}-${crypto.randomUUID()}`;
|
|
25
|
+
private started = false;
|
|
26
|
+
|
|
27
|
+
constructor(private client: ClaudeRuntimeClient, private options: DG.AIChatOptions) {
|
|
28
|
+
super();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
protected async* respond(prompt: string, options: DG.AIRunOptions = {}): DG.AIStream {
|
|
32
|
+
const {client, sessionId, options: {systemPrompt}} = this;
|
|
33
|
+
const images = await Promise.all((options.attachments ?? []).map(ClaudeChat.encode));
|
|
34
|
+
await client.ensureConnected();
|
|
35
|
+
const chunks: string[] = [];
|
|
36
|
+
let final = null as FinalEvent | null;
|
|
37
|
+
let failure: any = null;
|
|
38
|
+
let wake = () => {};
|
|
39
|
+
const fail = (e: any) => { failure = e; wake(); };
|
|
40
|
+
const onAbort = () => fail(options.signal!.reason);
|
|
41
|
+
const forSession = <T extends {sessionId: string}>(source: rxjs.Observable<T>, handler: (e: T) => void) =>
|
|
42
|
+
source.subscribe((e) => { if (e.sessionId === sessionId) handler(e); });
|
|
43
|
+
const subs = [
|
|
44
|
+
forSession(client.onChunk, (e) => { chunks.push(e.content); wake(); }),
|
|
45
|
+
forSession(client.onFinal, (e) => { final = e; wake(); }),
|
|
46
|
+
forSession(client.onError, (e) => fail(new Error(e.message))),
|
|
47
|
+
forSession(client.onSessionReset, () => fail(new Error('AI runtime: the session was lost'))),
|
|
48
|
+
client.onClose.subscribe(() => fail(new Error('AI runtime: connection lost'))),
|
|
49
|
+
];
|
|
50
|
+
options.signal?.addEventListener('abort', onAbort);
|
|
51
|
+
try {
|
|
52
|
+
if (options.signal?.aborted)
|
|
53
|
+
throw options.signal.reason;
|
|
54
|
+
client.send(sessionId, this.started || !systemPrompt ? prompt : `${systemPrompt}\n\n${prompt}`, {
|
|
55
|
+
systemPromptMode: 'none', outputSchema: options.schema, images,
|
|
56
|
+
});
|
|
57
|
+
while (!final || chunks.length) {
|
|
58
|
+
if (chunks.length)
|
|
59
|
+
yield chunks.shift()!;
|
|
60
|
+
else if (failure)
|
|
61
|
+
throw failure;
|
|
62
|
+
else
|
|
63
|
+
await new Promise<void>((resolve) => wake = resolve);
|
|
64
|
+
}
|
|
65
|
+
this.started = true;
|
|
66
|
+
const m = final.metrics;
|
|
67
|
+
return {
|
|
68
|
+
text: final.content,
|
|
69
|
+
structuredOutput: final.structured_output,
|
|
70
|
+
usage: {
|
|
71
|
+
inputTokens: m?.inputTokens ?? undefined,
|
|
72
|
+
outputTokens: m?.outputTokens ?? undefined,
|
|
73
|
+
costUsd: m?.costUsd ?? undefined,
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
} finally {
|
|
77
|
+
for (const s of subs)
|
|
78
|
+
s.unsubscribe();
|
|
79
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
80
|
+
if (!final)
|
|
81
|
+
client.abort(sessionId);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The runtime forwards images only. */
|
|
86
|
+
private static encode(a: DG.AIAttachment): Promise<ImageAttachment> {
|
|
87
|
+
if (a.type !== 'image')
|
|
88
|
+
throw new Error(`Grokky engine: ${a.type} attachments are not supported`);
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
const reader = new FileReader();
|
|
91
|
+
reader.onload = () => resolve({
|
|
92
|
+
mediaType: a.data.type as ImageAttachment['mediaType'], data: (reader.result as string).split(',')[1],
|
|
93
|
+
});
|
|
94
|
+
reader.onerror = () => reject(reader.error);
|
|
95
|
+
reader.readAsDataURL(a.data);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import * as DG from 'datagrok-api/dg';
|
|
2
|
+
|
|
3
|
+
// Chrome's Prompt API global (Chrome 138+); absent in other browsers and in the Node worker
|
|
4
|
+
declare const LanguageModel: any;
|
|
5
|
+
|
|
6
|
+
const INPUTS = [{type: 'text'}, {type: 'image'}];
|
|
7
|
+
|
|
8
|
+
export class GemmaEngine extends DG.AIEngine {
|
|
9
|
+
id = 'gemma';
|
|
10
|
+
name = 'Gemma (Chrome built-in)';
|
|
11
|
+
|
|
12
|
+
async available(): Promise<boolean> {
|
|
13
|
+
return typeof LanguageModel !== 'undefined' &&
|
|
14
|
+
await LanguageModel.availability({expectedInputs: INPUTS}) === 'available';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async chat(options: DG.AIChatOptions = {}): Promise<DG.AIChat> {
|
|
18
|
+
if (!(await this.available()))
|
|
19
|
+
throw new Error('Gemma engine: the built-in model is not downloaded; call download() first');
|
|
20
|
+
return new GemmaChat(await LanguageModel.create({
|
|
21
|
+
initialPrompts: options.systemPrompt ? [{role: 'system', content: options.systemPrompt}] : [],
|
|
22
|
+
expectedInputs: INPUTS,
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async download(): Promise<void> {
|
|
27
|
+
const state = typeof LanguageModel === 'undefined' ? 'unsupported browser' :
|
|
28
|
+
await LanguageModel.availability({expectedInputs: INPUTS});
|
|
29
|
+
if (state === 'available')
|
|
30
|
+
return;
|
|
31
|
+
if (state !== 'downloadable' && state !== 'downloading')
|
|
32
|
+
throw new Error(`Built-in model: ${state}`);
|
|
33
|
+
const pi = DG.TaskBarProgressIndicator.create('Downloading the built-in model');
|
|
34
|
+
try {
|
|
35
|
+
const session = await LanguageModel.create({
|
|
36
|
+
expectedInputs: INPUTS,
|
|
37
|
+
monitor: (m: any) => m.addEventListener('downloadprogress',
|
|
38
|
+
(e: any) => pi.update(e.loaded * 100, `${Math.round(e.loaded * 100)}%`)),
|
|
39
|
+
});
|
|
40
|
+
session.destroy();
|
|
41
|
+
} finally {
|
|
42
|
+
pi.close();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
class GemmaChat extends DG.AIChat {
|
|
48
|
+
constructor(private session: any) {
|
|
49
|
+
super();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
protected async* respond(prompt: string, options: DG.AIRunOptions = {}): DG.AIStream {
|
|
53
|
+
const parts = await Promise.all((options.attachments ?? []).map(GemmaChat.encode));
|
|
54
|
+
const stream = this.session.promptStreaming(
|
|
55
|
+
[{role: 'user', content: [{type: 'text', value: prompt}, ...parts]}],
|
|
56
|
+
{signal: options.signal, responseConstraint: options.schema});
|
|
57
|
+
const reader = stream.getReader();
|
|
58
|
+
let text = '';
|
|
59
|
+
try {
|
|
60
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
61
|
+
text += chunk.value;
|
|
62
|
+
yield chunk.value;
|
|
63
|
+
}
|
|
64
|
+
} finally {
|
|
65
|
+
reader.cancel().catch(() => {});
|
|
66
|
+
}
|
|
67
|
+
return {text, structuredOutput: options.schema ? JSON.parse(text) : undefined, usage: {}};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
close(): void {
|
|
71
|
+
this.session.destroy();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private static async encode(a: DG.AIAttachment): Promise<{type: string, value: any}> {
|
|
75
|
+
if (a.type === 'image')
|
|
76
|
+
return {type: 'image', value: a.data};
|
|
77
|
+
if (a.data.type.startsWith('text/'))
|
|
78
|
+
return {type: 'text', value: `${a.title ?? 'Document'}:\n${await a.data.text()}`};
|
|
79
|
+
throw new Error(`Gemma engine: ${a.data.type} documents are not supported`);
|
|
80
|
+
}
|
|
81
|
+
}
|