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
feat: marimo new 'prompt to generate notebook' (#4364)
Myles Scolnicka57d1246fd46
diff --git a/marimo/_ai/text_to_notebook.py b/marimo/_ai/text_to_notebook.pynew file mode 100644index 0000000000..04e5b2a930--- /dev/null+++ b/marimo/_ai/text_to_notebook.py@@ -0,0 +1,108 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import datetime+import urllib.error+import urllib.parse+import urllib.request+from typing import Optional, cast++from marimo import __version__+from marimo._cli.print import bold, green, muted+from marimo._config.cli_state import (+ get_cli_state,+ write_cli_state,+)+from marimo._server.utils import print_++TERMS = """+Before using marimo's Text-To-Notebook AI feature, you should know:++1. Your prompt will be sent to marimo's API at `https://ai.marimo.app/`+2. The API uses OpenAI/Anthropic's models to convert your prompt into a notebook+3. Your prompt is securely stored for caching purposes (fast response times)+4. No personal data beyond the prompt itself is collected+5. You can revoke consent at any time by modifying ~/.marimo/state.toml+"""++TERMS_LAST_UPDATED = datetime.datetime(2025, 4, 1)+++def text_to_notebook(prompt: str) -> str:+ """+ Generate a notebook from a text prompt.++ Args:+ prompt: The text prompt to generate a notebook from.++ Returns:+ The generated notebook as a string.++ Raises:+ ValueError: If the user has not accepted the terms.+ RuntimeError: If the API request fails.+ """+ # Check if the user has accepted the terms+ state = get_cli_state()+ if not state:+ raise RuntimeError(+ "Failed to get CLI configuration at ~/.marimo/state.toml"+ )++ if _should_show_terms(state.accepted_text_to_notebook_terms_at):+ # User hasn't accepted terms+ print_(bold(TERMS))+ print_(bold("Do you accept these terms? (y/n)"))++ response = input().strip().lower()+ if response != "y":+ raise ValueError("Terms not accepted.")++ # Update state with acceptance+ today = datetime.datetime.now().date().strftime("%Y-%m-%d")+ state.accepted_text_to_notebook_terms_at = today++ write_cli_state(state)++ # Call the API+ try:+ url = f"https://ai.marimo.app/api/notebook.py?prompt={urllib.parse.quote(prompt)}"+ print_(muted("Generating notebook this may take a few seconds..."))++ # Create a request with a proper User-Agent header+ headers = {"User-Agent": f"marimo-cli/{__version__}"}+ req = urllib.request.Request(url, headers=headers)++ with urllib.request.urlopen(req) as response:+ result = response.read().decode("utf-8") # type: ignore[attr-defined]++ print_(green("Notebook generated successfully."))++ # Check if the response is valid+ if "marimo.App" not in result:+ raise RuntimeError(+ "Invalid response from API: missing 'marimo.App' key"+ )++ return cast(str, result)++ except Exception as e:+ raise RuntimeError(f"Failed to generate notebook: {str(e)}") from e+++def _should_show_terms(last_accepted_at: Optional[str]) -> bool:+ """+ Determine if the terms should be shown to the user.++ Args:+ last_accepted_at (Optional[str]): The date the user last accepted the terms.++ Returns:+ bool: Whether the terms should be shown to the user.+ """+ if not last_accepted_at:+ return True+ last_accepted_date = datetime.datetime.strptime(+ last_accepted_at, "%Y-%m-%d"+ )+ return last_accepted_date < TERMS_LAST_UPDATEDdiff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex d3b42391ff..97831100aa 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -503,6 +503,7 @@ def edit(type=bool,help=sandbox_message,)[email protected]("prompt", required=False)def new(port: Optional[int],host: str,@@ -512,6 +513,7 @@ def new(token_password: Optional[str],base_url: str,sandbox: Optional[bool],+ prompt: Optional[str],) -> None:if sandbox:from marimo._cli.sandbox import run_in_sandbox@@ -520,8 +522,27 @@ def new(run_in_sandbox(sys.argv[1:], None, additional_features=["lsp"])return+ file_router: Optional[AppFileRouter] = None+ if prompt:+ import tempfile++ from marimo._ai.text_to_notebook import text_to_notebook++ try:+ notebook_content = text_to_notebook(prompt)+ temp_file = tempfile.NamedTemporaryFile(suffix=".py")+ Path(temp_file.name).write_text(notebook_content, encoding="utf-8")+ file_router = AppFileRouter.infer(temp_file.name)+ except Exception as e:+ raise click.ClickException(+ f"Failed to generate notebook: {str(e)}"+ ) from e++ if file_router is None:+ file_router = AppFileRouter.new_file()+start(- file_router=AppFileRouter.new_file(),+ file_router=file_router,development_mode=GLOBAL_SETTINGS.DEVELOPMENT_MODE,quiet=GLOBAL_SETTINGS.QUIET,host=host,diff --git a/marimo/_cli/upgrade.py b/marimo/_cli/upgrade.pyindex ce737db816..57df82e179 100644--- a/marimo/_cli/upgrade.py+++ b/marimo/_cli/upgrade.py@@ -5,27 +5,24 @@ import jsonimport osimport urllib.errorimport urllib.request-from dataclasses import dataclassfrom datetime import datetime-from typing import Any, Callable, Optional+from typing import Any, Callablefrom marimo import __version__ as current_version, _loggersfrom marimo._cli.print import echo, green, orange+from marimo._config.cli_state import (+ MarimoCLIState,+ get_cli_state,+ write_cli_state,+)from marimo._server.api.status import HTTPExceptionfrom marimo._tracer import server_tracer-from marimo._utils.config.config import ConfigReaderFETCH_TIMEOUT = 3LOGGER = _loggers.marimo_logger()-@dataclass-class MarimoCLIState:- latest_version: Optional[str] = None- last_checked_at: Optional[str] = None--def print_latest_version(current_version: str, latest_version: str) -> None:message = f"Update available {current_version} → {latest_version}"echo(orange(message))@@ -46,16 +43,10 @@ def check_for_updates(on_update: Callable[[str, str], None]) -> None:def _check_for_updates_internal(on_update: Callable[[str, str], None]) -> None:from packaging import version- config_reader = ConfigReader.for_filename("state.toml")- if not config_reader:- # Couldn't find home directory, so do nothing+ state = get_cli_state()+ if not state:return- # Load the state file or create a default state if it doesn't exist- state: MarimoCLIState = config_reader.read_toml(- MarimoCLIState, fallback=MarimoCLIState()- )-# Maybe update the state with the latest versionstate = _update_with_latest_version(state)@@ -70,7 +61,7 @@ def _check_for_updates_internal(on_update: Callable[[str, str], None]) -> None:on_update(current_version, state.latest_version)# Save the state, create directories if necessary- config_reader.write_toml(state)+ write_cli_state(state)DATE_FORMAT = "%Y-%m-%d"diff --git a/marimo/_config/cli_state.py b/marimo/_config/cli_state.pynew file mode 100644index 0000000000..61501eeb1a--- /dev/null+++ b/marimo/_config/cli_state.py@@ -0,0 +1,36 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from dataclasses import dataclass+from typing import Optional++from marimo._utils.config.config import ConfigReader+++@dataclass+class MarimoCLIState:+ latest_version: Optional[str] = None+ last_checked_at: Optional[str] = None+ accepted_text_to_notebook_terms_at: Optional[str] = None+++FILE_NAME = "state.toml"+++def get_cli_state() -> Optional[MarimoCLIState]:+ config_reader = ConfigReader.for_filename(FILE_NAME)+ if not config_reader:+ # Couldn't find home directory, so do nothing+ return None++ # Load the state file or create a default state if it doesn't exist+ state = config_reader.read_toml(MarimoCLIState, fallback=MarimoCLIState())+ return state+++def write_cli_state(state: MarimoCLIState) -> None:+ config_reader = ConfigReader.for_filename(FILE_NAME)+ if not config_reader:+ # Couldn't find home directory, so do nothing+ return+ config_reader.write_toml(state)diff --git a/tests/_cli/test_upgrade.py b/tests/_cli/test_upgrade.pyindex 989fae5bd6..3db246f404 100644--- a/tests/_cli/test_upgrade.py+++ b/tests/_cli/test_upgrade.py@@ -8,11 +8,11 @@ from typing import Anyfrom unittest.mock import mock_open, patchfrom marimo._cli.upgrade import (- MarimoCLIState,_update_with_latest_version,check_for_updates,print_latest_version,)+from marimo._config.cli_state import MarimoCLIState@patch("marimo._cli.upgrade.current_version", "0.1.0")