Skip to content

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.

feat: ai completion button (#1433)

Myles Scolnick304047037084
diff --git a/.gitignore b/.gitignore
index e6a9ae912e..22d9358cc7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -107,3 +107,5 @@ marimo/_static/
marimo/_lsp/
.vscode
+
+.marimo.toml
diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
new file mode 100644
index 0000000000..f848ac3bda
--- /dev/null
+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
@@ -0,0 +1,120 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { useCellActions } from "../../../core/cells/cells";
+import { cn } from "@/utils/cn";
+import { Button } from "@/components/ui/button";
+import { 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";
+import ReactCodeMirror, { EditorView } from "@uiw/react-codemirror";
+import { customPythonLanguageSupport } from "@/core/codemirror/language/python";
+
+const extensions = [customPythonLanguageSupport(), EditorView.lineWrapping];
+
+/**
+ * Add a cell with AI.
+ */
+export const AddCellWithAI: React.FC<{
+ onClose: () => void;
+}> = ({ onClose }) => {
+ const { createNewCell } = useCellActions();
+
+ const {
+ completion,
+ input,
+ stop,
+ isLoading,
+ setCompletion,
+ handleInputChange,
+ handleSubmit,
+ } = useCompletion({
+ api: "/api/ai/completion",
+ headers: API.headers(),
+ streamMode: "text",
+ body: {
+ includeOtherCode: getCodes(""),
+ code: "",
+ },
+ onError: (error) => {
+ toast({
+ title: "Generate with AI failed",
+ description: prettyError(error),
+ });
+ },
+ });
+
+ const inputComponent = (
+ <div className="flex items-center gap-3 px-3 py-2">
+ <SparklesIcon className="size-4 text-[var(--blue-11)]" />
+ <input
+ className="h-8 outline-none text-base focus-visible:shadow-none flex-1 rounded-none border-none focus:border-none"
+ autoFocus={true}
+ value={input}
+ onChange={handleInputChange}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleSubmit(e as unknown as React.FormEvent<HTMLFormElement>);
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ setCompletion("");
+ onClose();
+ }
+ }}
+ placeholder="Generate with AI"
+ />
+ {isLoading && (
+ <Button
+ data-testid="stop-completion-button"
+ variant="text"
+ size="sm"
+ className="mb-0"
+ onClick={stop}
+ >
+ <Loader2Icon className="animate-spin mr-1" size={14} />
+ Stop
+ </Button>
+ )}
+ {!isLoading && completion && (
+ <Button
+ data-testid="accept-completion-button"
+ variant="text"
+ size="sm"
+ className="mb-0"
+ disabled={isLoading}
+ onClick={() => {
+ createNewCell({
+ cellId: "__end__",
+ before: false,
+ code: completion,
+ });
+ setCompletion("");
+ onClose();
+ }}
+ >
+ <span className="text-[var(--grass-11)] opacity-100">Accept</span>
+ </Button>
+ )}
+ <Button variant="text" size="sm" className="mb-0" onClick={onClose}>
+ <XIcon className="size-4" />
+ </Button>
+ </div>
+ );
+
+ return (
+ <div className={cn("flex flex-col w-full")}>
+ {inputComponent}
+ {completion && (
+ <ReactCodeMirror
+ value={completion}
+ className="cm border-t"
+ onChange={setCompletion}
+ extensions={extensions}
+ />
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
index b946e1af42..52f30a6003 100644
--- a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
+++ b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
@@ -34,6 +34,8 @@ interface Props {
children: React.ReactNode;
}
+const baseExtensions = [customPythonLanguageSupport(), EditorView.lineWrapping];
+
export const AiCompletionEditor: React.FC<Props> = ({
onChange,
currentCode,
@@ -79,11 +81,6 @@ export const AiCompletionEditor: React.FC<Props> = ({
}
}, [enabled]);
- const baseExtensions = [
- customPythonLanguageSupport(),
- EditorView.lineWrapping,
- ];
-
return (
<div className="flex flex-col w-full rounded-[inherit] overflow-hidden">
<div
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index ef59f92b2c..a90e91622d 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -24,10 +24,12 @@ import { PackageAlert } from "@/components/editor/package-alert";
import { useDeleteCellCallback } from "../cell/useDeleteCell";
import { cn } from "@/utils/cn";
import { Button } from "@/components/ui/button";
-import { SquareCodeIcon, SquareMIcon } from "lucide-react";
+import { SparklesIcon, SquareCodeIcon, SquareMIcon } from "lucide-react";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import { autoInstantiateAtom } from "@/core/config/config";
+import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";
import { useAtomValue } from "jotai";
+import { useBoolean } from "@/hooks/useBoolean";
+import { AddCellWithAI } from "../ai/add-cell-with-ai";
interface CellArrayProps {
notebook: NotebookState;
@@ -150,15 +152,21 @@ export const CellArray: React.FC<CellArrayProps> = ({
const AddCellButtons: React.FC = () => {
const { createNewCell } = useCellActions();
const autoInstantiate = useAtomValue(autoInstantiateAtom);
+ const [isAiButtonOpen, isAiButtonOpenActions] = useBoolean(false);
+ const aiEnabled = useAtomValue(aiEnabledAtom);
const buttonClass = cn(
"px-16 mb-0 rounded-none",
"hover:bg-accent hover:text-accent-foreground font-semibold uppercase text-xs",
);
- return (
- <div className="flex justify-center mt-4 pt-6 pb-32 group gap-4">
- <div className="shadow-smSolid border border-border rounded opacity-0 transition-all duration-200 group-hover:opacity-100 overflow-hidden divide-x divide-border">
+ const renderBody = () => {
+ if (isAiButtonOpen) {
+ return <AddCellWithAI onClose={isAiButtonOpenActions.toggle} />;
+ }
+
+ return (
+ <>
<Button
className={buttonClass}
variant="text"
@@ -185,6 +193,31 @@ const AddCellButtons: React.FC = () => {
<SquareMIcon className="mr-2 size-4" />
Markdown
</Button>
+ {aiEnabled && (
+ <Button
+ className={buttonClass}
+ variant="text"
+ size="sm"
+ onClick={isAiButtonOpenActions.toggle}
+ >
+ <SparklesIcon className="mr-2 size-4" />
+ Generate with AI
+ </Button>
+ )}
+ </>
+ );
+ };
+
+ return (
+ <div className="flex justify-center mt-4 pt-6 pb-32 group gap-4 w-full">
+ <div
+ className={cn(
+ "shadow-sm border border-border rounded transition-all duration-200 overflow-hidden divide-x divide-border",
+ !isAiButtonOpen && "opacity-0 group-hover:opacity-100 w-fit",
+ isAiButtonOpen && "opacity-100 w-full max-w-4xl shadow-lg",
+ )}
+ >
+ {renderBody()}
</div>
</div>
);
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index 7f4cfa9493..5e0a07e46a 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -8,13 +8,20 @@ from starlette.exceptions import HTTPException
from starlette.responses import StreamingResponse
from marimo import _loggers
+from marimo._config.config import MarimoConfig
from marimo._server.api.deps import AppState
from marimo._server.api.status import HTTPStatus
from marimo._server.api.utils import parse_request
-from marimo._server.models.completion import AiCompletionRequest
+from marimo._server.models.completion import (
+ AiCompletionRequest,
+)
from marimo._server.router import APIRouter
if TYPE_CHECKING:
+ from openai import OpenAI, Stream # type: ignore[import-not-found]
+ from openai.types.chat import ( # type: ignore[import-not-found]
+ ChatCompletionChunk,
+ )
from starlette.requests import Request
LOGGER = _loggers.marimo_logger()
@@ -23,12 +30,7 @@ LOGGER = _loggers.marimo_logger()
router = APIRouter()
[email protected]("/completion")
-@requires("edit")
-async def ai_completion(
- *,
- request: Request,
-) -> StreamingResponse:
+def get_openai_client(config: MarimoConfig) -> "OpenAI":
try:
from openai import OpenAI # type: ignore[import-not-found]
except ImportError:
@@ -36,11 +38,6 @@ async def ai_completion(
status_code=HTTPStatus.BAD_REQUEST, detail="OpenAI not installed"
) from None
- app_state = AppState(request)
- app_state.require_current_session()
- config = app_state.config_manager.get_config(hide_secrets=False)
- body = await parse_request(request, cls=AiCompletionRequest)
-
if "ai" not in config:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="OpenAI not configured"
@@ -66,20 +63,58 @@ async def ai_completion(
)
if not base_url:
base_url = None
+
+ return OpenAI(api_key=key, base_url=base_url)
+
+
+def get_model(config: MarimoConfig) -> str:
model: str = (
config.get("ai", {}).get("open_ai", {}).get("model", "gpt-3.5-turbo")
)
if not model:
model = "gpt-3.5-turbo"
+ return model
- client = OpenAI(api_key=key, base_url=base_url)
+
+def make_stream_response(
+ response: Stream[ChatCompletionChunk],
+) -> Generator[str, None, None]:
+ # If it starts or ends with markdown, remove it
+ for chunk in response:
+ content = chunk.choices[0].delta.content
+ if content:
+ if content.startswith("```python"):
+ yield content[9:]
+ if content.startswith("```"):
+ yield content[4:]
+ elif content.endswith("```"):
+ yield content[:-3]
+ else:
+ yield content or ""
+
+
[email protected]("/completion")
+@requires("edit")
+async def ai_completion(
+ *,
+ request: Request,
+) -> StreamingResponse:
+ app_state = AppState(request)
+ app_state.require_current_session()
+ config = app_state.config_manager.get_config(hide_secrets=False)
+ body = await parse_request(request, cls=AiCompletionRequest)
+ client = get_openai_client(config)
system_prompt = (
"You are a helpful assistant that can answer questions "
"about python code. You can only output python code. "
- "Do not describe the code, just write the code."
- "Do not output markdown or backticks. When using matplotlib "
- "to show plots, use plt.gca() instead of plt.show()."
+ "1. Do not describe the code, just write the code."
+ "2. Do not output markdown or backticks."
+ "3. When using matplotlib to show plots,"
+ "use plt.gca() instead of plt.show()."
+ "4. If an import already exists, do not import it again."
+ "5. If a variable is already defined, use another name, or"
+ "make it private by adding an underscore at the beginning."
)
prompt = body.prompt
@@ -91,7 +126,7 @@ async def ai_completion(
prompt = f"{prompt}\n\nCurrent code:\n{body.code}"
response = client.chat.completions.create(
- model=model,
+ model=get_model(config),
messages=[
{
"role": "system",
@@ -106,21 +141,7 @@ async def ai_completion(
stream=True,
)
- # If it starts or ends with markdown, remove it
- def stream_response() -> Generator[str, None, None]:
- for chunk in response:
- content = chunk.choices[0].delta.content
- if content:
- if content.startswith("```python"):
- yield content[9:]
- if content.startswith("```"):
- yield content[4:]
- elif content.endswith("```"):
- yield content[:-3]
- else:
- yield content or ""
-
return StreamingResponse(
- content=stream_response(),
+ content=make_stream_response(response),
media_type="application/json",
)