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.

snippets: openai, huggingface, env (#3799)

Myles Scolnick83c21f6e67bc
diff --git a/.vscode/settings.json b/.vscode/settings.json
index eb10ce73db..d9ce98f83d 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -10,5 +10,8 @@
},
"[json]": {
"editor.defaultFormatter": "biomejs.biome"
+ },
+ "[python]": {
+ "editor.defaultFormatter": "charliermarsh.ruff"
}
}
diff --git a/marimo/_snippets/data/env-0.py b/marimo/_snippets/data/env-0.py
new file mode 100644
index 0000000000..c0e2178f0b
--- /dev/null
+++ b/marimo/_snippets/data/env-0.py
@@ -0,0 +1,28 @@
+import marimo
+
+__generated_with = "0.11.0"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""# Load .env""")
+ return
+
+
+def _():
+ import dotenv
+
+ dotenv.load_dotenv(dotenv.find_dotenv(usecwd=True))
+ return (dotenv,)
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/huggingface-0.py b/marimo/_snippets/data/huggingface-0.py
new file mode 100644
index 0000000000..e58f8b3261
--- /dev/null
+++ b/marimo/_snippets/data/huggingface-0.py
@@ -0,0 +1,39 @@
+import marimo
+
+__generated_with = "0.11.0"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ # Hugging Face: Datasets with Polars
+
+ Fetch any datasets from [Hugging Face Datasets](https://huggingface.co/datasets) with [Polars](https://www.pola.rs/).
+ """
+ )
+ return
+
+
+def _():
+ import polars as pl
+ return (pl,)
+
+
+def _(pl):
+ df = pl.read_csv("hf://datasets/scikit-learn/Fish/Fish.csv")
+ df
+ return (df,)
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/huggingface-1.py b/marimo/_snippets/data/huggingface-1.py
new file mode 100644
index 0000000000..186e4845c3
--- /dev/null
+++ b/marimo/_snippets/data/huggingface-1.py
@@ -0,0 +1,50 @@
+import marimo
+
+__generated_with = "0.11.0"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ # Hugging Face: Datasets with SQL
+
+ Fetch any datasets from [Hugging Face Datasets](https://huggingface.co/datasets) with SQL via [DuckDB](https://duckdb.org/)
+ """
+ )
+ return
+
+
+def _():
+ import duckdb
+ import polars as pl
+ return duckdb, pl
+
+
+def _(mo):
+ data = mo.sql(
+ f"""
+ SELECT * FROM "hf://datasets/scikit-learn/Fish/Fish.csv"
+ """
+ )
+ return (data,)
+
+
+def _(data):
+ # Get the SQL result back in Python
+ data.describe()
+ return
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/openai-0.py b/marimo/_snippets/data/openai-0.py
new file mode 100644
index 0000000000..cf6cfc2657
--- /dev/null
+++ b/marimo/_snippets/data/openai-0.py
@@ -0,0 +1,62 @@
+import marimo
+
+__generated_with = "0.11.0"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ # OpenAI: Prompt with Streaming Response
+
+ Prompt OpenAI or any OpenAI-compatible endpoint and stream the response back.
+ """
+ )
+ return
+
+
+def _():
+ from openai import OpenAI
+ return (OpenAI,)
+
+
+def _(mo):
+ api_key = mo.ui.text(label="API Key", kind="password")
+ api_key
+ return (api_key,)
+
+
+def _(OpenAI, api_key):
+ client = OpenAI(
+ api_key=api_key.value,
+ # Change this if you are using a different OpenAI-compatible endpoint.
+ # base_url="https://api.openai.com/v1",
+ )
+
+ completion = client.chat.completions.create(
+ model="gpt-4o-mini",
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant."},
+ {
+ "role": "user",
+ "content": "Write a haiku about recursion in programming.",
+ },
+ ],
+ stream=True,
+ )
+ completion
+ return client, completion
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/openai-1.py b/marimo/_snippets/data/openai-1.py
new file mode 100644
index 0000000000..d502226a62
--- /dev/null
+++ b/marimo/_snippets/data/openai-1.py
@@ -0,0 +1,55 @@
+import marimo
+
+__generated_with = "0.11.0"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ # OpenAI: Chatbot
+
+ Turn any OpenAI or any OpenAI-compatible endpoint into a chatbot.
+ """
+ )
+ return
+
+
+def _():
+ from openai import OpenAI
+ return (OpenAI,)
+
+
+def _(mo):
+ api_key = mo.ui.text(label="API Key", kind="password")
+ api_key
+ return (api_key,)
+
+
+def _(api_key, mo):
+ chat = mo.ui.chat(
+ mo.ai.llm.openai(
+ "gpt-4o-mini",
+ api_key=api_key.value,
+ # Change this if you are using a different OpenAI-compatible endpoint.
+ # base_url="https://api.openai.com/v1",
+ system_message="You are a helpful assistant.",
+ ),
+ prompts=["Write a haiku about recursion in programming."],
+ )
+ chat
+ return (chat,)
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/snippets.py b/marimo/_snippets/snippets.py
index 053c77012c..da7943fb8f 100644
--- a/marimo/_snippets/snippets.py
+++ b/marimo/_snippets/snippets.py
@@ -77,26 +77,26 @@ def should_ignore_code(code: str) -> bool:
def get_title_from_code(code: str) -> str:
+ # We intentionally avoid AST parsing here to avoid the overhead
if not code:
return ""
code = code.strip()
- if not code.startswith("mo.md") and not code.startswith("#"):
+ if not (code.startswith("mo.md") or code.startswith("#")):
return ""
- if "# " in code:
- # title is the start of # and end of \n or end quote
- start = code.find("#")
- if "\n" in code[start:]:
- end = code[start:].find("\n")
- return code[start : end + start].replace("#", "", 1).strip()
- # No newline, find end quote
- if '"' in code[start:]:
- end = code[start:].find('"')
- return code[start : end + start].replace("#", "", 1).strip()
- if "'" in code[start:]:
- end = code[start:].find("'")
- return code[start : end + start].replace("#", "", 1).strip()
- return code[start:].replace("#", "", 1).strip()
- return ""
+
+ start = code.find("#")
+ if start == -1:
+ return ""
+
+ # Skip the # character
+ start += 1
+
+ # Find end of title
+ for end_char in ("\n", '"', "'"):
+ if (end := code.find(end_char, start)) != -1:
+ return code[start:end].strip()
+
+ return code[start:].strip()
def is_markdown(code: str) -> bool:
diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.py
index 33fe49c7fe..e8857d4555 100644
--- a/tests/_server/api/endpoints/test_export.py
+++ b/tests/_server/api/endpoints/test_export.py
@@ -153,6 +153,7 @@ def test_export_script(client: TestClient) -> None:
assert "__generated_with = " in response.text
[email protected](reason="flakey", strict=False)
@with_session(SESSION_ID)
def test_export_markdown(client: TestClient) -> None:
response = client.post(
diff --git a/tests/_snippets/test_snippets.py b/tests/_snippets/test_snippets.py
index ef317b3336..b57e9d4dfd 100644
--- a/tests/_snippets/test_snippets.py
+++ b/tests/_snippets/test_snippets.py
@@ -57,16 +57,23 @@ def test_get_title_from_code_with_mo_md() -> None:
assert get_title_from_code(code) == "This is a title"
+total_snippets = len(list(read_snippet_filenames(True, [])))
+
+
@pytest.mark.xfail(condition=is_windows(), reason="flaky on Windows")
@pytest.mark.parametrize(
("include_default_snippets", "custom_paths", "expected_snippets"),
[
- (True, [], 89),
+ (True, [], total_snippets),
(False, [], 0),
- (True, ["/notarealdirectory"], 89),
+ (True, ["/notarealdirectory"], total_snippets),
(False, ["/notarealdirectory"], 0),
- (False, ["marimo/_snippets/data"], 89),
- (False, ["marimo/_snippets/data", "/notarealdirectory"], 89),
+ (False, ["marimo/_snippets/data"], total_snippets),
+ (
+ False,
+ ["marimo/_snippets/data", "/notarealdirectory"],
+ total_snippets,
+ ),
],
)
def test_read_snippet_filenames(
@@ -77,6 +84,7 @@ def test_read_snippet_filenames(
filenames = list(
read_snippet_filenames(include_default_snippets, custom_paths)
)
+ assert total_snippets > 0
assert len(filenames) == expected_snippets
assert all(filename.endswith(".py") for filename in filenames)
assert all("_snippets/data" in filename for filename in filenames)