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: support multi-line AI prompts, add @dataframe context to cell prompts (#2577)
Myles Scolnick50b8199315c6
diff --git a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts b/frontend/src/components/editor/ai/__tests__/completion-utils.test.tsnew file mode 100644index 0000000000..1a43605fa0--- /dev/null+++ b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts@@ -0,0 +1,115 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, beforeEach, it, expect, vi, type Mock } from "vitest";+import { getAICompletionBody } from "../completion-utils";+import { getCodes } from "@/core/codemirror/copilot/getCodes";+import { datasetsAtom } from "@/core/datasets/state";+import { store } from "@/core/state/jotai";+import type { DatasetsState } from "@/core/datasets/types";++// Mock getCodes function+vi.mock("@/core/codemirror/copilot/getCodes", () => ({+ getCodes: vi.fn(),+}));++describe("getAICompletionBody", () => {+ beforeEach(() => {+ // Reset the Jotai store before each test+ store.set(datasetsAtom, {+ tables: [],+ } as unknown as DatasetsState);+ (getCodes as Mock).mockReturnValue("// Some other code");+ });++ it("should return the correct completion body with mentioned datasets", () => {+ // Set up test data in the Jotai store+ const testDatasets = [+ {+ name: "dataset1",+ columns: [+ { name: "col1", type: "number" },+ { name: "col2", type: "string" },+ ],+ },+ {+ name: "dataset2",+ columns: [+ { name: "col3", type: "boolean" },+ { name: "col4", type: "date" },+ ],+ },+ ];+ store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);++ const input = "Use @dataset1 and @dataset2 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" },+ ],+ },+ {+ name: "dataset2",+ columns: [+ { name: "col3", type: "boolean" },+ { name: "col4", type: "date" },+ ],+ },+ ],+ },+ code: "",+ });+ });++ it("should handle input with no mentioned datasets", () => {+ const input = "Perform some analysis without mentioning datasets";+ const result = getAICompletionBody(input);++ expect(result).toEqual({+ includeOtherCode: "// Some other code",+ context: {+ schema: [],+ },+ code: "",+ });+ });++ it("should handle input with non-existent datasets", () => {+ // Set up test data in the Jotai store+ const testDatasets = [+ {+ name: "existingDataset",+ columns: [+ { name: "col1", type: "number" },+ { name: "col2", type: "string" },+ ],+ },+ ];+ store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);++ const input = "Use @existingDataset and @nonExistentDataset for analysis";+ const result = getAICompletionBody(input);++ expect(result).toEqual({+ includeOtherCode: "// Some other code",+ context: {+ schema: [+ {+ name: "existingDataset",+ columns: [+ { name: "col1", type: "number" },+ { name: "col2", type: "string" },+ ],+ },+ ],+ },+ code: "",+ });+ });+});diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsxindex a69a42df88..b081439219 100644--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx@@ -4,7 +4,6 @@ import { cn } from "@/utils/cn";import { Button } from "@/components/ui/button";import { ChevronsUpDown, Loader2Icon, SparklesIcon, XIcon } from "lucide-react";import { toast } from "@/components/ui/use-toast";-import { getCodes } from "@/core/codemirror/copilot/getCodes";import { API } from "@/core/network/api";import { prettyError } from "@/utils/errors";import { useCompletion } from "ai/react";@@ -12,17 +11,14 @@ import ReactCodeMirror, {EditorView,keymap,minimalSetup,+ type ReactCodeMirrorRef,} from "@uiw/react-codemirror";import { Prec } from "@codemirror/state";import { customPythonLanguageSupport } from "@/core/codemirror/language/python";import { asURL } from "@/utils/url";import { mentions } from "@uiw/codemirror-extensions-mentions";import { useMemo, useState } from "react";-import { store } from "@/core/state/jotai";import { datasetTablesAtom } from "@/core/datasets/state";-import { Logger } from "@/utils/Logger";-import { Maps } from "@/utils/maps";-import type { DataTable } from "@/core/kernel/messages";import { useAtom, useAtomValue } from "jotai";import type { Completion } from "@codemirror/autocomplete";import {@@ -35,6 +31,7 @@ import { sql } from "@codemirror/lang-sql";import { SQLLanguageAdapter } from "@/core/codemirror/language/sql";import { atomWithStorage } from "jotai/utils";import { type ResolvedTheme, useTheme } from "@/theme/useTheme";+import { getAICompletionBody } from "./completion-utils";const pythonExtensions = [customPythonLanguageSupport(),@@ -42,39 +39,6 @@ const pythonExtensions = [];const sqlExtensions = [sql(), EditorView.lineWrapping];-function getCompletionBody(input: string): object {- const datasets = extractDatasets(input);- Logger.debug("Included datasets", datasets);-- return {- includeOtherCode: getCodes(""),- context: {- schema: datasets.map((dataset) => ({- name: dataset.name,- columns: dataset.columns.map((column) => ({- name: column.name,- type: column.type,- })),- })),- },- code: "",- };-}--function extractDatasets(input: string): DataTable[] {- const datasets = store.get(datasetTablesAtom);- const existingDatasets = Maps.keyBy(datasets, (dataset) => dataset.name);-- // Extract dataset mentions from the input- const mentionedDatasets = input.match(/@(\w+)/g) || [];-- // Filter to only include datasets that exist- return mentionedDatasets- .map((mention) => mention.slice(1))- .map((name) => existingDatasets.get(name))- .filter(Boolean);-}-// Persist across sessionsconst languageAtom = atomWithStorage<"python" | "sql">("marimo:ai-language",@@ -149,9 +113,13 @@ export const AddCellWithAI: React.FC<{value={input}onChange={(newValue) => {setInput(newValue);- setCompletionBody(getCompletionBody(newValue));+ setCompletionBody(getAICompletionBody(newValue));+ }}+ onSubmit={() => {+ if (!isLoading) {+ handleSubmit();+ }}}- onSubmit={handleSubmit}/>{isLoading && (<Button@@ -198,11 +166,14 @@ export const AddCellWithAI: React.FC<{<div className={cn("flex flex-col w-full gap-2 py-2")}>{inputComponent}{!completion && (- <span className="text-xs text-muted-foreground px-3">- You can mention{" "}- <span className="text-[var(--cyan-11)]">@dataframe</span> or{" "}- <span className="text-[var(--cyan-11)]">@sql_table</span> to pull- additional context such as column names.+ <span className="text-xs text-muted-foreground px-3 flex flex-col gap-1">+ <span>+ You can mention{" "}+ <span className="text-[var(--cyan-11)]">@dataframe</span> or{" "}+ <span className="text-[var(--cyan-11)]">@sql_table</span> to pull+ additional context such as column names.+ </span>+ <span>Code from other cells is automatically included.</span></span>)}{completion && (@@ -219,6 +190,7 @@ export const AddCellWithAI: React.FC<{};interface PromptInputProps {+ inputRef?: React.RefObject<ReactCodeMirrorRef>;value: string;onClose: () => void;onChange: (value: string) => void;@@ -226,8 +198,15 @@ interface PromptInputProps {theme: ResolvedTheme;}-const PromptInput = ({+/**+ * CodeMirror-based input for the AI prompt.+ *+ * This is just text (no language support), but we use codemirror to get autocomplete+ * for @dataframe and @sql_table.+ */+export const PromptInput = ({value,+ inputRef,onChange,onSubmit,onClose,@@ -300,12 +279,40 @@ const PromptInput = ({Prec.highest(keymap.of([{- key: "Enter",preventDefault: true,stopPropagation: true,- run: () => {- handleSubmit();- return true;+ any: (view, event) => {+ const pressedModOrShift =+ event.metaKey || event.ctrlKey || event.shiftKey;+ // If no mod key is pressed, submit+ if (event.key === "Enter" && !pressedModOrShift) {+ handleSubmit();+ event.preventDefault();+ event.stopPropagation();+ return true;+ }+ // Mod+Enter does add a new line already by codemirror+ // But Shift+Enter does not, so we need to handle it manually+ if (event.key === "Enter" && event.shiftKey) {+ const cursorPosition = view.state.selection.main.from;+ // Insert a new line+ view.dispatch({+ changes: {+ from: cursorPosition,+ to: cursorPosition,+ insert: "\n",+ },+ selection: {+ anchor: cursorPosition + 1,+ head: cursorPosition + 1,+ },+ });+ event.preventDefault();+ event.stopPropagation();+ return true;+ }++ return false;},},]),@@ -326,6 +333,7 @@ const PromptInput = ({return (<ReactCodeMirror+ ref={inputRef}className="flex-1 font-sans"autoFocus={true}width="100%"diff --git a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsxsimilarity index 83%rename from frontend/src/components/editor/cell/code/ai-completion-editor.tsxrename to frontend/src/components/editor/ai/ai-completion-editor.tsxindex 27e7a62756..5477061009 100644--- a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx+++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import React, { useEffect } from "react";+import React, { useEffect, useState } from "react";import CodeMirrorMerge from "react-codemirror-merge";import { useCompletion } from "ai/react";import { API } from "@/core/network/api";@@ -21,6 +21,10 @@ import { getCodes } from "@/core/codemirror/copilot/getCodes";import { useTheme } from "@/theme/useTheme";import { asURL } from "@/utils/url";import type { LanguageAdapterType } from "@/core/codemirror/language/types";+import { PromptInput } from "./add-cell-with-ai";+import { getAICompletionBody } from "./completion-utils";+import type { ReactCodeMirrorRef } from "@uiw/react-codemirror";+import { selectAllText } from "@/core/codemirror/utils";const Original = CodeMirrorMerge.Original;const Modified = CodeMirrorMerge.Modified;@@ -41,6 +45,11 @@ interface Props {const baseExtensions = [customPythonLanguageSupport(), EditorView.lineWrapping];+/**+ * Editor for AI completions that goes above a cell to modify it.+ *+ * This shows a left/right split with the original and modified code.+ */export const AiCompletionEditor: React.FC<Props> = ({onChange,initialPrompt,@@ -51,6 +60,8 @@ export const AiCompletionEditor: React.FC<Props> = ({enabled,children,}) => {+ const [completionBody, setCompletionBody] = useState<object>({});+const [includeOtherCells, setIncludeOtherCells] = useAtom(includeOtherCellsAtom,);@@ -62,7 +73,6 @@ export const AiCompletionEditor: React.FC<Props> = ({isLoading,setCompletion,setInput,- handleInputChange,handleSubmit,} = useCompletion({api: asURL("api/ai/completion").toString(),@@ -70,6 +80,7 @@ export const AiCompletionEditor: React.FC<Props> = ({initialInput: initialPrompt,streamMode: "text",body: {+ ...completionBody,includeOtherCode: includeOtherCells ? getCodes(currentCode) : "",code: currentCode,language: currentLanguageAdapter,@@ -82,13 +93,13 @@ export const AiCompletionEditor: React.FC<Props> = ({},});- const inputRef = React.useRef<HTMLInputElement>(null);+ const inputRef = React.useRef<ReactCodeMirrorRef>(null);// Focus the inputuseEffect(() => {if (enabled && inputRef.current) {- inputRef.current.focus();- inputRef.current.select();+ inputRef.current.view?.focus();+ selectAllText(inputRef.current.view);}}, [enabled]);@@ -106,7 +117,7 @@ export const AiCompletionEditor: React.FC<Props> = ({<divclassName={cn("flex items-center gap-2 border-b px-3 transition-[height] rounded-[inherit] rounded-b-none duration-300 overflow-hidden",- enabled && "h-10 visible",+ enabled && "min-h-10 visible",!enabled && "h-0 invisible",)}>@@ -116,23 +127,21 @@ export const AiCompletionEditor: React.FC<Props> = ({className="text-[var(--blue-10)] flex-shrink-0"size={16}/>- <input- className="h-8 outline-none px-2 focus-visible:shadow-none flex-1 rounded-none border-none focus:border-none"+ <PromptInput+ inputRef={inputRef}+ theme={theme}+ onClose={() => {+ declineChange();+ setCompletion("");+ }}value={input}- ref={inputRef}- onChange={handleInputChange}- placeholder="Type for completion"- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- handleSubmit(- e as unknown as React.FormEvent<HTMLFormElement>,- );- }- if (e.key === "Escape") {- e.preventDefault();- declineChange();- setCompletion("");+ onChange={(newValue) => {+ setInput(newValue);+ setCompletionBody(getAICompletionBody(newValue));+ }}+ onSubmit={() => {+ if (!isLoading) {+ handleSubmit();}}}/>diff --git a/frontend/src/components/editor/ai/completion-utils.ts b/frontend/src/components/editor/ai/completion-utils.tsnew file mode 100644index 0000000000..47630ee696--- /dev/null+++ b/frontend/src/components/editor/ai/completion-utils.ts@@ -0,0 +1,50 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { getCodes } from "@/core/codemirror/copilot/getCodes";+import { datasetTablesAtom } from "@/core/datasets/state";+import type { DataTable } from "@/core/kernel/messages";+import type { AiCompletionRequest } from "@/core/network/types";+import { store } from "@/core/state/jotai";+import { Logger } from "@/utils/Logger";+import { Maps } from "@/utils/maps";++/**+ * Gets the request body for the AI completion API.+ */+export function getAICompletionBody(+ input: string,+): Omit<AiCompletionRequest, "language" | "prompt"> {+ const datasets = extractDatasets(input);+ Logger.debug("Included datasets", datasets);++ return {+ includeOtherCode: getCodes(""),+ context: {+ schema: datasets.map((dataset) => ({+ name: dataset.name,+ columns: dataset.columns.map((column) => ({+ name: column.name,+ type: column.type,+ })),+ })),+ },+ code: "",+ };+}++/**+ * Extracts datasets from the input.+ * Datasets are referenced with @<dataset_name> in the input.+ */+function extractDatasets(input: string): DataTable[] {+ const datasets = store.get(datasetTablesAtom);+ const existingDatasets = Maps.keyBy(datasets, (dataset) => dataset.name);++ // Extract dataset mentions from the input+ const mentionedDatasets = input.match(/@(\w+)/g) || [];++ // Filter to only include datasets that exist+ return mentionedDatasets+ .map((mention) => mention.slice(1))+ .map((name) => existingDatasets.get(name))+ .filter(Boolean);+}diff --git a/frontend/src/components/editor/cell/code/merge-editor.css b/frontend/src/components/editor/ai/merge-editor.csssimilarity index 100%rename from frontend/src/components/editor/cell/code/merge-editor.cssrename to frontend/src/components/editor/ai/merge-editor.cssdiff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex dc1dd1a8e1..3f65054648 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -27,7 +27,7 @@ import { LanguageToggles } from "./language-toggle";import { cn } from "@/utils/cn";import { saveCellConfig } from "@/core/network/requests";import { HideCodeButton } from "../../code/readonly-python-code";-import { AiCompletionEditor } from "./ai-completion-editor";+import { AiCompletionEditor } from "../../ai/ai-completion-editor";import { useAtom, useAtomValue } from "jotai";import { aiCompletionCellAtom } from "@/core/ai/state";import { mergeRefs } from "@/utils/mergeRefs";diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsxindex 316c54d59b..64e93503e3 100644--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx@@ -45,7 +45,7 @@ export const MarimoTracebackOutput = ({const handleRefactorWithAI = () => {onRefactorWithAI?.({- prompt: `My code gives the following error: ${lastTracebackLine}`,+ prompt: `My code gives the following error:\n\n${lastTracebackLine}`,});};diff --git a/frontend/src/core/codemirror/utils.ts b/frontend/src/core/codemirror/utils.tsindex 4c7ec1c562..f4c05efe22 100644--- a/frontend/src/core/codemirror/utils.ts+++ b/frontend/src/core/codemirror/utils.ts@@ -36,3 +36,15 @@ export function isInVimNormalMode(ev: EditorView): boolean {}return vimState.mode === "normal";}++export function selectAllText(ev: EditorView | undefined) {+ if (!ev) {+ return;+ }+ ev.dispatch({+ selection: {+ anchor: 0,+ head: ev.state.doc.length,+ },+ });+}diff --git a/frontend/src/css/app/codemirror.css b/frontend/src/css/app/codemirror.cssindex 6dfcd2a74c..fe5bd8ce89 100644--- a/frontend/src/css/app/codemirror.css+++ b/frontend/src/css/app/codemirror.css@@ -31,6 +31,7 @@#root .cm-tooltip {border-radius: 4px;+ z-index: 1000;@apply bg-popover shadow-sm shadow-shade border-border;}diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex c2631ce657..dfe7bc9227 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -334,6 +334,7 @@ async def ai_completion(],temperature=0,stream=True,+ timeout=15,)return StreamingResponse(