A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: variables in completion (#4416)
Myles Scolnick1f616a4c37cb
diff --git a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts b/frontend/src/components/editor/ai/__tests__/completion-utils.test.tsindex ba2f580325..779beeaa78 100644--- a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts+++ b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts@@ -9,6 +9,8 @@ import {dataSourceConnectionsAtom,DUCKDB_ENGINE,} from "@/core/datasets/data-source-connections";+import { variablesAtom } from "@/core/variables/state";+import type { Variable, VariableName } from "@/core/variables/types";// Mock getCodes functionvi.mock("@/core/codemirror/copilot/getCodes", () => ({@@ -25,6 +27,7 @@ describe("getAICompletionBody", () => {latestEngineSelected: DUCKDB_ENGINE,connectionsMap: new Map(),});+ store.set(variablesAtom, {});(getCodes as Mock).mockReturnValue("// Some other code");});@@ -210,4 +213,166 @@ describe("getAICompletionBody", () => {},});});++ it("should return the correct completion body with mentioned variables", () => {+ // Set up test data in the Jotai store+ const testVariables: Record<VariableName, Variable> = {+ ["var1" as VariableName]: {+ name: "var1" as VariableName,+ value: "string value",+ dataType: "string",+ declaredBy: [],+ usedBy: [],+ },+ ["var2" as VariableName]: {+ name: "var2" as VariableName,+ value: "42",+ dataType: "number",+ declaredBy: [],+ usedBy: [],+ },+ };+ store.set(variablesAtom, testVariables);++ const input = "Use @var1 and @var2 for analysis";+ const result = getAICompletionBody({ input });++ expect(result).toEqual({+ includeOtherCode: "// Some other code",+ context: {+ schema: [],+ variables: [+ {+ name: "var1",+ valueType: "string",+ previewValue: "string value",+ },+ {+ name: "var2",+ valueType: "number",+ previewValue: "42",+ },+ ],+ },+ });+ });++ it("should handle input with both datasets and variables", () => {+ // Set up test data in the Jotai store+ const testDatasets = [+ {+ name: "dataset1",+ columns: [+ { name: "col1", type: "number" },+ { name: "col2", type: "string" },+ ],+ },+ ];+ store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);++ const testVariables: Record<VariableName, Variable> = {+ ["var1" as VariableName]: {+ name: "var1" as VariableName,+ value: "string value",+ dataType: "string",+ declaredBy: [],+ usedBy: [],+ },+ };+ store.set(variablesAtom, testVariables);++ const input = "Use @dataset1 and @var1 for analysis";+ const result = getAICompletionBody({ input });++ expect(result).toEqual({+ includeOtherCode: "// Some other code",+ context: {+ schema: [+ {+ name: "dataset1",+ columns: [+ { name: "col1", type: "number" },+ { name: "col2", type: "string" },+ ],+ },+ ],+ variables: [+ {+ name: "var1",+ valueType: "string",+ previewValue: "string value",+ },+ ],+ },+ });+ });++ it("should handle non-existent variables", () => {+ // Set up test data in the Jotai store+ const testVariables: Record<VariableName, Variable> = {+ ["existingVar" as VariableName]: {+ name: "existingVar" as VariableName,+ value: "string value",+ dataType: "string",+ declaredBy: [],+ usedBy: [],+ },+ };+ store.set(variablesAtom, testVariables);++ const input = "Use @existingVar and @nonExistentVar for analysis";+ const result = getAICompletionBody({ input });++ expect(result).toEqual({+ includeOtherCode: "// Some other code",+ context: {+ schema: [],+ variables: [+ {+ name: "existingVar",+ valueType: "string",+ previewValue: "string value",+ },+ ],+ },+ });+ });++ it("should prioritize datasets over variables when there's a name conflict", () => {+ // Set up test data in the Jotai store with a name conflict+ const testDatasets = [+ {+ name: "conflict",+ columns: [{ name: "col1", type: "number" }],+ },+ ];+ store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);++ const testVariables: Record<VariableName, Variable> = {+ ["conflict" as VariableName]: {+ name: "conflict" as VariableName,+ value: "string value",+ dataType: "string",+ declaredBy: [],+ usedBy: [],+ },+ };+ store.set(variablesAtom, testVariables);++ const input = "Use @conflict for analysis";+ const result = getAICompletionBody({ input });++ expect(result).toEqual({+ includeOtherCode: "// Some other code",+ context: {+ schema: [+ {+ name: "conflict",+ columns: [{ name: "col1", type: "number" }],+ },+ ],+ variables: [],+ },+ });+ });});diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsxindex 550d36da80..91921f83bc 100644--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx@@ -31,7 +31,8 @@ import { atomWithStorage } from "jotai/utils";import { type ResolvedTheme, useTheme } from "@/theme/useTheme";import { getAICompletionBody, mentions } from "./completion-utils";import { allTablesAtom } from "@/core/datasets/data-source-connections";-import type { DataTable } from "@/core/kernel/messages";+import { variablesAtom } from "@/core/variables/state";+import { getTableCompletions, getVariableCompletions } from "./completions";const pythonExtensions = [customPythonLanguageSupport(),@@ -235,82 +236,23 @@ export const PromptInput = ({const handleSubmit = onSubmit;const handleEscape = onClose;const tablesMap = useAtomValue(allTablesAtom);+ const variables = useAtomValue(variablesAtom);const extensions = useMemo(() => {- const completions = [...tablesMap.entries()].map(- ([tableName, table]): Completion => ({- label: `@${tableName}`,- detail: table.source,- boost: table.source_type === "local" ? 5 : 0,- info: () => {- const shape = [- table.num_rows == null ? undefined : `${table.num_rows} rows`,- table.num_columns == null- ? undefined- : `${table.num_columns} columns`,- ]- .filter(Boolean)- .join(", ");-- const infoContainer = document.createElement("div");- infoContainer.classList.add("prose", "prose-sm", "dark:prose-invert");-- if (shape) {- const shapeElement = document.createElement("div");- shapeElement.textContent = shape;- shapeElement.style.fontWeight = "bold";- infoContainer.append(shapeElement);- }-- if (table.source) {- const sourceElement = document.createElement("figcaption");- sourceElement.textContent = `Source: ${table.source}`;- infoContainer.append(sourceElement);- }-- if (table.columns) {- const columnsTable = document.createElement("table");- const headerRow = columnsTable.insertRow();- const nameHeader = headerRow.insertCell();- nameHeader.textContent = "Column";- nameHeader.style.fontWeight = "bold";- const typeHeader = headerRow.insertCell();- typeHeader.textContent = "Type";- typeHeader.style.fontWeight = "bold";-- table.columns.forEach((column) => {- const row = columnsTable.insertRow();- const nameCell = row.insertCell();-- nameCell.textContent = column.name;- const itemMetadata = getItemMetadata(table, column);- if (itemMetadata) {- nameCell.append(itemMetadata);- }-- const typeCell = row.insertCell();- typeCell.textContent = column.type;- });-- infoContainer.append(columnsTable);- }-- return infoContainer;- },- }),- );+ const completions = [+ ...getTableCompletions(tablesMap),+ ...getVariableCompletions(variables, new Set(tablesMap.keys())),+ ];// Trigger autocompletion for text that begins with @, can contain dotsconst matchBeforeRegexes = [/@([\w.]+)?/];if (additionalCompletions) {matchBeforeRegexes.push(additionalCompletions.triggerCompletionRegex);+ completions.push(...additionalCompletions.completions);}- const allCompletions = additionalCompletions- ? [...completions, ...additionalCompletions.completions]- : completions;return [- mentions(matchBeforeRegexes, allCompletions),+ mentions(matchBeforeRegexes, completions),EditorView.lineWrapping,minimalSetup(),Prec.highest(@@ -381,7 +323,7 @@ export const PromptInput = ({},]),];- }, [tablesMap, additionalCompletions, handleSubmit, handleEscape]);+ }, [tablesMap, variables, additionalCompletions, handleSubmit, handleEscape]);return (<ReactCodeMirror@@ -399,25 +341,3 @@ export const PromptInput = ({/>);};--function getItemMetadata(- table: DataTable,- column: DataTable["columns"][0],-): HTMLSpanElement | undefined {- const isPrimaryKey = table.primary_keys?.includes(column.name);- const isIndexed = table.indexes?.includes(column.name);- if (isPrimaryKey || isIndexed) {- const subtext = document.createElement("span");- subtext.textContent = isPrimaryKey ? "PK" : "IDX";- subtext.classList.add(- "text-xs",- "text-black",- "bg-gray-100",- "dark:invert",- "rounded",- "px-1",- "ml-1",- );- return subtext;- }-}diff --git a/frontend/src/components/editor/ai/completion-utils.ts b/frontend/src/components/editor/ai/completion-utils.tsindex 7ac95c5ca7..9b31076e6f 100644--- a/frontend/src/components/editor/ai/completion-utils.ts+++ b/frontend/src/components/editor/ai/completion-utils.ts@@ -4,6 +4,8 @@ import { allTablesAtom } from "@/core/datasets/data-source-connections";import type { DataTable } from "@/core/kernel/messages";import type { AiCompletionRequest } from "@/core/network/types";import { store } from "@/core/state/jotai";+import { variablesAtom } from "@/core/variables/state";+import type { Variable, VariableName } from "@/core/variables/types";import { Logger } from "@/utils/Logger";import {autocompletion,@@ -21,8 +23,9 @@ export function getAICompletionBody({AiCompletionRequest,"language" | "prompt" | "code"> {- const datasets = extractDatasets(input);+ const { datasets, variables } = extractDatasetsAndVariables(input);Logger.debug("Included datasets", datasets);+ Logger.debug("Included variables", variables);return {includeOtherCode: getCodes(""),@@ -35,26 +38,50 @@ export function getAICompletionBody({sampleValues: column.sample_values,})),})),- variables: [],+ variables: variables.map((variable) => ({+ name: variable.name,+ valueType: variable.dataType ?? "",+ previewValue: variable.value,+ })),},};}/**- * Extracts datasets from the input.- * Datasets are referenced with @<dataset_name> in the input.+ * Extracts datasets and variables from the input.+ * References are with @<name> in the input.+ * Prioritizes datasets over variables if there's a name conflict.*/-function extractDatasets(input: string): DataTable[] {+function extractDatasetsAndVariables(input: string): {+ datasets: DataTable[];+ variables: Variable[];+} {const allTables = store.get(allTablesAtom);+ const allVariables = store.get(variablesAtom);++ // Extract mentions from the input+ const mentions = input.match(/@([\w.]+)/g) || [];+ const mentionedNames = mentions.map((mention) => mention.slice(1));++ const datasets: DataTable[] = [];+ const variables: Variable[] = [];++ for (const name of mentionedNames) {+ // First process datasets (higher priority)+ const dataset = allTables.get(name);+ if (dataset) {+ datasets.push(dataset);+ continue;+ }- // Extract dataset mentions from the input- const mentionedDatasets = input.match(/@([\w.]+)/g) || [];+ // Then process variables if not already processed as datasets+ const variable = allVariables[name as VariableName];+ if (variable) {+ variables.push(variable);+ }+ }- // Filter to only include datasets that exist- return mentionedDatasets- .map((mention) => mention.slice(1))- .map((name) => allTables.get(name))- .filter(Boolean);+ return { datasets, variables };}/**diff --git a/frontend/src/components/editor/ai/completions.ts b/frontend/src/components/editor/ai/completions.tsnew file mode 100644index 0000000000..32d3cd9e53--- /dev/null+++ b/frontend/src/components/editor/ai/completions.ts@@ -0,0 +1,264 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { DatasetTablesMap } from "@/core/datasets/data-source-connections";+import type { DataTable } from "@/core/kernel/messages";+import type { Completion } from "@codemirror/autocomplete";+import type { Variable, Variables } from "@/core/variables/types";++const Boosts = {+ LOCAL_TABLE: 5,+ REMOTE_TABLE: 4,+ VARIABLE: 3,+} as const;++export function getTableCompletions(tablesMap: DatasetTablesMap) {+ return [...tablesMap.entries()].map(+ ([tableName, table]): Completion => ({+ label: `@${tableName}`,+ displayLabel: tableName,+ detail: table.source === "memory" ? "in-memory" : table.source,+ boost:+ table.source_type === "local"+ ? Boosts.LOCAL_TABLE+ : Boosts.REMOTE_TABLE,+ type: table.variable_name ? "dataframe" : "table",+ apply: `@${tableName}`,+ // This may break in future, but if if it has a variable name,+ // then it is a dataframe, otherwise it is a table.+ section: table.variable_name ? "Dataframe" : "Table",+ info: () => {+ const infoContainer = document.createElement("div");+ infoContainer.classList.add(+ "mo-cm-tooltip",+ "docs-documentation",+ "min-w-[200px]",+ );+ infoContainer.style.display = "flex";+ infoContainer.style.flexDirection = "column";+ infoContainer.style.gap = ".8rem";+ infoContainer.style.padding = "0.5rem";++ // Table header with name and source+ const headerDiv = document.createElement("div");+ headerDiv.classList.add("flex", "flex-col", "gap-1");++ const nameDiv = document.createElement("div");+ nameDiv.classList.add("font-bold", "text-base");+ nameDiv.textContent = tableName;+ headerDiv.append(nameDiv);++ if (table.source) {+ const sourceDiv = document.createElement("div");+ sourceDiv.classList.add("text-xs", "text-muted-foreground");+ sourceDiv.textContent = `Source: ${table.source}`;+ headerDiv.append(sourceDiv);+ }++ infoContainer.append(headerDiv);++ // Table shape info+ const shape = [+ table.num_rows == null ? undefined : `${table.num_rows} rows`,+ table.num_columns == null+ ? undefined+ : `${table.num_columns} columns`,+ ]+ .filter(Boolean)+ .join(", ");++ if (shape) {+ const shapeDiv = document.createElement("div");+ shapeDiv.classList.add(+ "text-xs",+ "bg-muted",+ "px-2",+ "py-1",+ "rounded",+ );+ shapeDiv.textContent = shape;+ infoContainer.append(shapeDiv);+ }++ // Columns table+ if (table.columns && table.columns.length > 0) {+ const columnsDiv = document.createElement("div");+ columnsDiv.classList.add("overflow-auto", "max-h-60");++ const columnsTable = document.createElement("table");+ columnsTable.classList.add("w-full", "text-xs", "border-collapse");++ // Table header+ const headerRow = columnsTable.insertRow();+ headerRow.classList.add("bg-muted");++ const nameHeader = headerRow.insertCell();+ nameHeader.classList.add("p-2", "font-medium", "text-left");+ nameHeader.textContent = "Column";++ const typeHeader = headerRow.insertCell();+ typeHeader.classList.add("p-2", "font-medium", "text-left");+ typeHeader.textContent = "Type";+ // Check if any column has metadata before adding the header+ const hasAnyMetadata = table.columns.some(+ (column) => getItemMetadata(table, column) !== undefined,+ );++ let metadataHeader: HTMLTableCellElement | undefined;+ if (hasAnyMetadata) {+ metadataHeader = headerRow.insertCell();+ metadataHeader.classList.add("p-2", "font-medium", "text-left");+ metadataHeader.textContent = "Metadata";+ }++ // Table rows+ table.columns.forEach((column, index) => {+ const row = columnsTable.insertRow();+ row.classList.add(+ index % 2 === 0 ? "bg-background" : "bg-muted/30",+ );++ const nameCell = row.insertCell();+ nameCell.classList.add("p-2", "font-mono");+ nameCell.textContent = column.name;++ const typeCell = row.insertCell();+ typeCell.classList.add("p-2", "text-muted-foreground");+ typeCell.textContent = column.type;++ if (hasAnyMetadata) {+ const metadataCell = row.insertCell();+ metadataCell.classList.add("p-2");++ const itemMetadata = getItemMetadata(table, column);+ if (itemMetadata) {+ metadataCell.append(itemMetadata);+ }+ }+ });++ columnsDiv.append(columnsTable);+ infoContainer.append(columnsDiv);+ }++ return infoContainer;+ },+ }),+ );+}++function getItemMetadata(+ table: DataTable,+ column: DataTable["columns"][0],+): HTMLSpanElement | undefined {+ const isPrimaryKey = table.primary_keys?.includes(column.name);+ const isIndexed = table.indexes?.includes(column.name);+ if (isPrimaryKey || isIndexed) {+ const badge = document.createElement("span");+ badge.textContent = isPrimaryKey ? "PK" : "IDX";+ badge.classList.add(+ "text-xs",+ "px-1.5",+ "py-0.5",+ "rounded-full",+ "font-medium",+ isPrimaryKey+ ? "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"+ : "bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200",+ );+ return badge;+ }+}++/**+ * Gets completions for variables defined in the notebook.+ */+export function getVariableCompletions(+ variables: Variables,+ skipVariables: Set<string>,+): Completion[] {+ return Object.values(variables).flatMap<Completion>((variable) => {+ if (skipVariables.has(variable.name)) {+ return [];+ }+ return {+ label: `@${variable.name}`,+ displayLabel: variable.name,+ detail: variable.dataType ?? "",+ boost: Boosts.VARIABLE,+ type: "variable",+ apply: `@${variable.name}`,+ section: "Variable",+ info: () => {+ return createVariableInfoElement(variable);+ },+ };+ });+}++function createVariableInfoElement(variable: Variable): HTMLElement {+ const infoContainer = document.createElement("div");+ infoContainer.classList.add(+ "mo-cm-tooltip",+ "docs-documentation",+ "min-w-[200px]",+ );+ infoContainer.style.display = "flex";+ infoContainer.style.flexDirection = "column";+ infoContainer.style.gap = ".8rem";+ infoContainer.style.padding = "0.5rem";++ // Variable header+ const header = document.createElement("div");+ header.classList.add("flex", "items-center", "gap-2");++ const nameBadge = document.createElement("span");+ nameBadge.classList.add("font-bold", "text-base");+ nameBadge.textContent = variable.name;+ header.append(nameBadge);++ if (variable.dataType) {+ const typeBadge = document.createElement("span");+ typeBadge.classList.add(+ "text-xs",+ "px-1.5",+ "py-0.5",+ "rounded-full",+ "bg-purple-100",+ "text-purple-800",+ "dark:bg-purple-900",+ "dark:text-purple-200",+ );+ typeBadge.textContent = variable.dataType;+ header.append(typeBadge);+ }++ infoContainer.append(header);++ // Variable value+ if (variable.value) {+ const valueContainer = document.createElement("div");+ valueContainer.classList.add("flex", "flex-col", "gap-1");++ const valueLabel = document.createElement("div");+ valueLabel.classList.add("text-xs", "text-muted-foreground");+ valueLabel.textContent = "Value:";+ valueContainer.append(valueLabel);++ const valueContent = document.createElement("div");+ valueContent.classList.add(+ "text-xs",+ "font-mono",+ "bg-muted",+ "p-2",+ "rounded",+ "overflow-auto",+ "max-h-40",+ );+ valueContent.textContent = variable.value;+ valueContainer.append(valueContent);++ infoContainer.append(valueContainer);+ }++ return infoContainer;+}diff --git a/frontend/src/core/datasets/data-source-connections.ts b/frontend/src/core/datasets/data-source-connections.tsindex 1c1a8e3558..9eff20cb0a 100644--- a/frontend/src/core/datasets/data-source-connections.ts+++ b/frontend/src/core/datasets/data-source-connections.ts@@ -330,3 +330,5 @@ export const allTablesAtom = atom((get) => {return tableNames;});++export type DatasetTablesMap = ReturnType<(typeof allTablesAtom)["read"]>;diff --git a/frontend/src/css/app/codemirror-completions.css b/frontend/src/css/app/codemirror-completions.cssindex ca542cc24a..4e0539dbcc 100644--- a/frontend/src/css/app/codemirror-completions.css+++ b/frontend/src/css/app/codemirror-completions.css@@ -4,7 +4,7 @@/* Base styling for autocomplete container */.cm-tooltip-autocomplete {/* CodeMirror's default is too wide. */- max-width: 200px;+ max-width: 250px;@apply bg-popover shadow-md border border-border;}@@ -25,10 +25,21 @@}.cm-completionLabel {- padding: 1px 0;+ padding-top: 1px;+ padding-bottom: 1px;+ padding-right: 12px;@apply text-xs;}+ .cm-completionDetail {+ flex-grow: 1;+ text-align: right;+ }++ .cm-tooltip-autocomplete > ul > completion-section {+ @apply text-xs bg-muted-foreground/10 border-y border-border;+ }+/* Hover state for list items */.cm-tooltip-autocomplete > ul > li:hover {background-color: var(--blue-3);@@ -151,11 +162,34 @@}}+ .cm-completionIcon-table {+ color: var(--gray-11);+ background-color: var(--gray-3);++ &::after {+ content: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiM2NjY2NjYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBjbGFzcz0ibHVjaWRlIGx1Y2lkZS1kYXRhYmFzZS1pY29uIGx1Y2lkZS1kYXRhYmFzZSI+PGVsbGlwc2UgY3g9IjEyIiBjeT0iNSIgcng9IjkiIHJ5PSIzIi8+PHBhdGggZD0iTTMgNVYxOUE5IDMgMCAwIDAgMjEgMTlWNSIvPjxwYXRoIGQ9Ik0zIDEyQTkgMyAwIDAgMCAyMSAxMiIvPjwvc3ZnPg=="); /* Database icon for tables */+ }+ }++ .cm-completionIcon-dataframe {+ color: var(--gray-11);+ background-color: var(--gray-3);++ &::after {+ content: "𝌆"; /* Dataframe icon for tables */+ }+ }+/* Completion info tooltip */.cm-completionInfo {@apply max-w-md border-l border-border;}+ .cm-completionDetail {+ font-style: normal;+ @apply text-xs text-muted-foreground;+ }+/* Completion matching text highlight */.cm-completionMatchedText {@apply font-semibold text-primary underline underline-offset-2;