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.

improvement: Better prompts for chat, new cell, and inline edits (#4399)

Myles Scolnickf4fe6942e9d0
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index 95573e7cf8..1014daee7d 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -270,9 +270,9 @@ const ChatPanelBody = () => {
experimental_prepareRequestBody: (options) => {
return {
...options,
- ...getAICompletionBody(
- options.messages.map((m) => m.content).join("\n"),
- ),
+ ...getAICompletionBody({
+ input: options.messages.map((m) => m.content).join("\n"),
+ }),
includeOtherCode: getCodes(""),
};
},
diff --git a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
index e2bdcb6ac4..ba2f580325 100644
--- a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
+++ b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
@@ -49,7 +49,7 @@ describe("getAICompletionBody", () => {
store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
const input = "Use @dataset1 and @dataset2 for analysis";
- const result = getAICompletionBody(input);
+ const result = getAICompletionBody({ input });
expect(result).toEqual({
includeOtherCode: "// Some other code",
@@ -70,18 +70,20 @@ describe("getAICompletionBody", () => {
],
},
],
+ variables: [],
},
});
});
it("should handle input with no mentioned datasets", () => {
const input = "Perform some analysis without mentioning datasets";
- const result = getAICompletionBody(input);
+ const result = getAICompletionBody({ input });
expect(result).toEqual({
includeOtherCode: "// Some other code",
context: {
schema: [],
+ variables: [],
},
});
});
@@ -100,7 +102,7 @@ describe("getAICompletionBody", () => {
store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
const input = "Use @existingDataset and @nonExistentDataset for analysis";
- const result = getAICompletionBody(input);
+ const result = getAICompletionBody({ input });
expect(result).toEqual({
includeOtherCode: "// Some other code",
@@ -114,6 +116,7 @@ describe("getAICompletionBody", () => {
],
},
],
+ variables: [],
},
});
});
@@ -136,7 +139,7 @@ describe("getAICompletionBody", () => {
store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
const input = "Use @dataset.with.dots and @regular_dataset for analysis";
- const result = getAICompletionBody(input);
+ const result = getAICompletionBody({ input });
expect(result).toEqual({
includeOtherCode: "// Some other code",
@@ -154,6 +157,7 @@ describe("getAICompletionBody", () => {
columns: [{ name: "col3", type: "boolean" }],
},
],
+ variables: [],
},
});
});
@@ -191,7 +195,7 @@ describe("getAICompletionBody", () => {
});
const input = "Use @table1 for analysis";
- const result = getAICompletionBody(input);
+ const result = getAICompletionBody({ input });
expect(result).toEqual({
includeOtherCode: "// Some other code",
@@ -202,6 +206,7 @@ describe("getAICompletionBody", () => {
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.tsx
index 8c2fc83ede..033d6a3808 100644
--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx
+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
@@ -116,7 +116,7 @@ export const AddCellWithAI: React.FC<{
value={input}
onChange={(newValue) => {
setInput(newValue);
- setCompletionBody(getAICompletionBody(newValue));
+ setCompletionBody(getAICompletionBody({ input: newValue }));
}}
onSubmit={() => {
if (!isLoading) {
diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsx
index 9157aca5b2..fb140de181 100644
--- a/frontend/src/components/editor/ai/ai-completion-editor.tsx
+++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx
@@ -149,7 +149,7 @@ export const AiCompletionEditor: React.FC<Props> = ({
value={input}
onChange={(newValue) => {
setInput(newValue);
- setCompletionBody(getAICompletionBody(newValue));
+ setCompletionBody(getAICompletionBody({ input: newValue }));
}}
onSubmit={() => {
if (!isLoading) {
diff --git a/frontend/src/components/editor/ai/completion-utils.ts b/frontend/src/components/editor/ai/completion-utils.ts
index cc7cf1b730..7ac95c5ca7 100644
--- a/frontend/src/components/editor/ai/completion-utils.ts
+++ b/frontend/src/components/editor/ai/completion-utils.ts
@@ -15,9 +15,12 @@ import type { Extension } from "@codemirror/state";
/**
* Gets the request body for the AI completion API.
*/
-export function getAICompletionBody(
- input: string,
-): Omit<AiCompletionRequest, "language" | "prompt" | "code"> {
+export function getAICompletionBody({
+ input,
+}: { input: string }): Omit<
+ AiCompletionRequest,
+ "language" | "prompt" | "code"
+> {
const datasets = extractDatasets(input);
Logger.debug("Included datasets", datasets);
@@ -32,6 +35,7 @@ export function getAICompletionBody(
sampleValues: column.sample_values,
})),
})),
+ variables: [],
},
};
}
diff --git a/frontend/src/core/codemirror/ai/request.ts b/frontend/src/core/codemirror/ai/request.ts
index 44fc7d5fe9..a41c2f24dc 100644
--- a/frontend/src/core/codemirror/ai/request.ts
+++ b/frontend/src/core/codemirror/ai/request.ts
@@ -3,6 +3,7 @@
import { API } from "@/core/network/api";
import { asURL } from "@/utils/url";
import type { LanguageAdapterType } from "../language/types";
+import type { AiCompletionRequest } from "@/core/network/types";
/**
* Request to edit code with AI
@@ -17,36 +18,24 @@ export async function requestEditCompletion(opts: {
// TODO: maybe include other code
// const otherCodes = getCodes(currentCode);
- const finalPrompt = `
-Given the following code context, ${opts.prompt}
-
-SELECTED CODE:
-${opts.selection}
-
-CODE BEFORE SELECTION:
+ const codeWithReplacement = `
${opts.codeBefore}
-
-CODE AFTER SELECTION:
+<rewrite_this>
+${opts.selection}
+</rewrite_this>
${opts.codeAfter}
-
-Instructions:
-1. Modify ONLY the selected code
-2. Keep the same indentation selected code
-3. Maintain consistent style with surrounding code
-4. Ensure the edit is complete and can be inserted directly
-5. Return ONLY the replacement code, no explanations, no code fences.
-
-Your task: ${opts.prompt}`;
+`.trim();
const response = await fetch(asURL("api/ai/completion").toString(), {
method: "POST",
headers: API.headers(),
body: JSON.stringify({
- prompt: finalPrompt,
- code: "",
+ prompt: opts.prompt,
+ code: codeWithReplacement,
+ selectedText: opts.selection,
includeOtherCode: "",
language: opts.language,
- }),
+ } satisfies AiCompletionRequest),
});
const firstLineIndent = opts.selection.match(/^\s*/)?.[0] || "";
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 67b14705c3..59662344bc 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -131,6 +131,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
snippets.Snippets,
requests.SetUIElementValueRequest,
# Requests/responses
+ completion.VariableContext,
completion.SchemaColumn,
completion.SchemaTable,
completion.AiCompletionContext,
diff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.py
index 13ef2d7938..c884a1e72a 100644
--- a/marimo/_server/ai/prompts.py
+++ b/marimo/_server/ai/prompts.py
@@ -1,16 +1,24 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Optional
+from typing import Optional, Union
from marimo._server.models.completion import (
AiCompletionContext,
Language,
+ SchemaTable,
+ VariableContext,
)
+FILL_ME_TAG = "<FILL_ME>"
+
language_rules = {
"python": [
- "When using matplotlib to show plots, use plt.gca() instead of plt.show().",
+ "For matplotlib: use plt.gca() as the last expression instead of plt.show().",
+ "For plotly: return the figure object directly.",
+ "For altair: return the chart object directly. Add tooltips where appropriate.",
+ "Include proper labels, titles, and color schemes.",
+ "Make visualizations interactive where appropriate.",
"If an import already exists, do not import it again.",
"If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.",
],
@@ -21,13 +29,13 @@ language_rules = {
}
-def _format_schema_info(context: Optional[AiCompletionContext]) -> str:
+def _format_schema_info(tables: Optional[list[SchemaTable]]) -> str:
"""Helper to format schema information from context"""
- if not context or not context.schema:
+ if not tables:
return ""
- schema_info = "\n\nAvailable schema:\n"
- for schema in context.schema:
+ schema_info = "\n\n## Available schema:\n"
+ for schema in tables:
schema_info += f"- Table: {schema.name}\n"
for col in schema.columns:
schema_info += f" - Column: {col.name}\n"
@@ -38,103 +46,252 @@ def _format_schema_info(context: Optional[AiCompletionContext]) -> str:
return schema_info
-class Prompter:
- def __init__(self, code: str):
- self.code = code
-
- @staticmethod
- def get_system_prompt(
- *,
- language: Language,
- custom_rules: Optional[str] = None,
- context: Optional[AiCompletionContext] = None,
- ) -> str:
- if language in language_rules:
- all_rules = [
- "Do not describe the code, just write the code.",
- "Do not output markdown or backticks.",
- ] + language_rules[language]
- rules = "\n".join(
- f"{i + 1}. {rule}" for i, rule in enumerate(all_rules)
- )
- system_prompt = (
- f"You are a helpful assistant that can answer questions about {language}."
- f" Here are your rules: \n{rules}"
- )
+def _format_variables(
+ variables: Optional[list[Union[VariableContext, str]]],
+) -> str:
+ if not variables:
+ return ""
- if custom_rules and custom_rules.strip():
- system_prompt += f"\n\nAdditional rules:\n{custom_rules}"
+ variable_info = "\n\n## Available variables from other cells:\n"
+ for variable in variables:
+ if isinstance(variable, VariableContext):
+ if _is_private_variable := variable.name.startswith("_"):
+ continue
+ variable_info += f"- variable: `{variable.name}`\n"
+ variable_info += f" - value_type: {variable.value_type}\n"
+ variable_info += f" - value_preview: {variable.preview_value}\n"
else:
- system_prompt = (
- "You are a helpful assistant that can answer questions."
- )
+ if _is_private_variable := variable.startswith("_"):
+ continue
+ variable_info += f"- variable: `{variable}`"
- system_prompt += _format_schema_info(context)
+ return variable_info
- return system_prompt
- @staticmethod
- def get_inline_system_prompt(*, language: Language) -> str:
- return (
- f"You are a {language} programmer that replaces <FILL_ME> part with the right code. "
- "Only output the code that replaces <FILL_ME> part. Do not add any explanation or markdown."
- )
+def _rules(rules: list[str]) -> str:
+ """Format a list of rules into a numbered string."""
+ return "\n".join(f"{i + 1}. {rule}" for i, rule in enumerate(rules))
- def get_prompt(self, *, user_prompt: str, include_other_code: str) -> str:
- prompt = user_prompt
- if include_other_code:
- prompt += f"\n\n<code-from-other-cells>\n{include_other_code.strip()}\n</code-from-other-cells>"
- if self.code.strip():
- prompt += (
- f"\n\n<current-code>\n{self.code.strip()}\n</current-code>"
- )
- return prompt
-
- @staticmethod
- def get_chat_system_prompt(
- *,
- custom_rules: Optional[str] = None,
- variables: Optional[list[str]] = None,
- context: Optional[AiCompletionContext] = None,
- include_other_code: str = "",
- ) -> str:
+
+def get_refactor_or_insert_notebook_cell_system_prompt(
+ *,
+ language: Language,
+ is_insert: bool,
+ custom_rules: Optional[str],
+ cell_code: Optional[str],
+ selected_text: Optional[str],
+ other_cell_codes: Optional[str],
+ context: Optional[AiCompletionContext],
+) -> str:
+ if cell_code:
+ system_prompt = f"Here's a {language} document from a Python notebook that I'm going to ask you to make an edit to.\n\n"
+ else:
system_prompt = (
- "You are a helpful assistant working in a marimo notebook. "
- "You can answer questions and help with tasks. "
- "You may respond with markdown, code, or a combination of both. "
- "If you respond in code, you must use the appropriate language block. "
- "And you only work with two languages: Python and SQL. "
- "When responding in code, think of each block of code as a separate cell in the notebook. "
- "The notebook has 2 hard rules: \n"
- "1. Do not import the same library twice. \n"
- "2. Do not define a variable if it already exists. You may reference variables from previous cells, "
- "but you may not define a variable if it already exists. \n"
+ "You are an AI assistant integrated into the marimo notebook code editor.\n"
+ "You goal is to create a new cell in the notebook.\n"
+ f"Your output must be valid {language} code.\n"
+ "You can use the provided context to help you write the new cell.\n"
+ "You can reference variables from other cells, but you cannot redefine a variable if it already exists.\n"
+ "Immediately start with the following format with no remarks. \n\n"
+ "```\n{CELL_CODE}\n```"
)
- for language in language_rules:
- if len(language_rules[language]) == 0:
- continue
-
- rules = "\n".join(
- f"{i + 1}. {rule}"
- for i, rule in enumerate(language_rules[language])
- )
-
- system_prompt += f"\n\nRules for {language}:\n{rules}"
+ # When we are modifying or inserting into an existing cell, we need to
+ if cell_code:
+ # Assertions, otherwise the system prompt will be wrong
+ if is_insert:
+ assert "<insert_here>" in cell_code
+ system_prompt += "The point you'll need to insert at is marked with <insert_here></insert_here>.\n"
+ else:
+ assert "<rewrite_this>" in cell_code
+ system_prompt += "The section you'll need to rewrite is marked with <rewrite_this></rewrite_this> tags.\n"
- if custom_rules and custom_rules.strip():
- system_prompt += f"\n\nAdditional rules:\n{custom_rules}"
+ if cell_code:
+ system_prompt += "\n\n" + _tag("document", cell_code) + "\n\n"
- if variables:
+ if is_insert:
system_prompt += (
- f"\n\nVariables to use but not define:\n{variables}"
+ "You can't replace the content, your answer will be inserted in place of the "
+ "<insert_here></insert_here> tags. Don't include the insert_here tags in your output.\n"
+ "Match the indentation in the original file in the inserted content, "
+ "don't include any indentation on blank lines.\n"
+ "Immediately start with the following format with no remarks:\n\n"
+ "```\n{INSERTED_CODE}\n```"
)
-
- if include_other_code:
+ else:
system_prompt += (
- f"\n\nCode from other cells:\n{include_other_code.strip()}"
+ "Only make changes that are necessary to fulfill the prompt, leave everything else as-is. "
+ "All surrounding content will be preserved.\n"
+ "Start at the indentation level in the original file in the rewritten content. "
+ "Don't stop until you've rewritten the entire section, even if you have no more changes to make, "
+ "always write out the whole section with no unnecessary elisions.\n"
+ "Immediately start with the following format with no remarks:\n\n"
+ "```\n{REWRITTEN_CODE}\n```"
)
- system_prompt += _format_schema_info(context)
+ if selected_text:
+ system_prompt += "\n\nAnd here's the section to rewrite based on that prompt again for reference:\n\n"
+ system_prompt += _tag("rewrite_this", selected_text)
+
+ if language in language_rules and language_rules[language]:
+ system_prompt += (
+ f"\n\n## Rules for {language}\n{_rules(language_rules[language])}"
+ )
+
+ if custom_rules and custom_rules.strip():
+ system_prompt += f"\n\n## Additional rules:\n{custom_rules}"
+
+ if context:
+ system_prompt += _format_variables(context.variables)
+ system_prompt += _format_schema_info(context.schema)
+
+ if other_cell_codes:
+ system_prompt += "\n\n" + _tag(
+ "code_from_other_cells", other_cell_codes
+ )
+
+ return system_prompt
+
+
+def get_inline_system_prompt(*, language: Language) -> str:
+ return (
+ f"You are a {language} programmer that replaces {FILL_ME_TAG} part with the right code. "
+ f"Only output the code that replaces {FILL_ME_TAG} part. Do not add any explanation or markdown."
+ )
+
+
+def get_chat_system_prompt(
+ *,
+ custom_rules: Optional[str],
+ context: Optional[AiCompletionContext],
+ include_other_code: str,
+) -> str:
+ system_prompt: str = """
+You are an AI assistant integrated into the marimo notebook code editor.
+You are a specialized AI assistant designed to help create data science notebooks using marimo.
+You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+
+Your goal is to do one of the following two things:
+
+1. Help users answer questions related to their notebook.
+2. Answer general-purpose questions unrelated to their particular notebook.
+
+It will be up to you to decide which of these you are doing based on what the user has told you. When unclear, ask clarifying questions to understand the user's intent before proceeding.
+
+You can respond with markdown, code, or a combination of both. You only work with two languages: Python and SQL.
+When responding in code, think of each block of code as a separate cell in the notebook.
+
+You have the following rules:
+
+- Do not import the same library twice.
+- Do not define a variable if it already exists. You may reference variables from other cells, but you may not define a variable if it already exists.
+
+# Marimo fundamentals
+
+Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+- Cells execute automatically when their dependencies change
+- Variables cannot be redeclared across cells
+- The notebook forms a directed acyclic graph (DAG)
+- The last expression in a cell is automatically displayed
+- UI elements are reactive and update the notebook automatically
+
+Marimo's reactivity means:
+- When a variable changes, all cells that use that variable automatically re-execute
+- UI elements trigger updates when their values change without explicit callbacks
+- UI element values are accessed through `.value` attribute
+- You cannot access a UI element's value in the same cell where it's defined
+
+## Best Practices
+
+<ui_elements>
+- Access UI element values with .value attribute (e.g., slider.value)
+- Create UI elements in one cell and reference them in later cells
+- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+- Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+- Group related UI elements for better organization
+</ui_elements>
+
+## Available UI elements
+
+* `mo.ui.altair_chart(altair_chart)` - create a reactive Altair chart
+* `mo.ui.button(value=None, kind='primary')` - create a clickable button
+* `mo.ui.run_button(label=None, tooltip=None, kind='primary')` - create a button that runs code
+* `mo.ui.checkbox(label='', value=False)` - create a checkbox
+* `mo.ui.chat(placeholder='', value=None)` - create a chat interface
+* `mo.ui.date(value=None, label=None, full_width=False)` - create a date picker
+* `mo.ui.dropdown(options, value=None, label=None, full_width=False)` - create a dropdown menu
+* `mo.ui.file(label='', multiple=False, full_width=False)` - create a file upload element
+* `mo.ui.number(value=None, label=None, full_width=False)` - create a number input
+* `mo.ui.radio(options, value=None, label=None, full_width=False)` - create radio buttons
+* `mo.ui.refresh(options: List[str], default_interval: str)` - create a refresh control
+* `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a slider
+* `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a range slider
+* `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)` - create an interactive table
+* `mo.ui.text(value='', label=None, full_width=False)` - create a text input
+* `mo.ui.text_area(value='', label=None, full_width=False)` - create a multi-line text input
+* `mo.ui.data_explorer(df)` - create an interactive dataframe explorer
+* `mo.ui.dataframe(df)` - display a dataframe with search, filter, and sort capabilities
+* `mo.ui.plotly(plotly_figure)` - create a reactive Plotly chart (supports scatter, treemap, and sunburst)
+* `mo.ui.tabs(elements: dict[str, mo.ui.Element])` - create a tabbed interface from a dictionary
+* `mo.ui.array(elements: list[mo.ui.Element])` - create an array of UI elements
+* `mo.ui.form(element: mo.ui.Element, label='', bordered=True)` - wrap an element in a form
+
+## Layout and utility functions
+
+* `mo.stop(predicate, output=None)` - stop execution conditionally
+* `mo.Html(html)` - display HTML
+* `mo.image(image)` - display an image
+* `mo.hstack(elements)` - stack elements horizontally
+* `mo.vstack(elements)` - stack elements vertically
+* `mo.tabs(elements)` - create a tabbed interface
+* `mo.mpl.interactive()` - make matplotlib plots interactive
+
+## Examples
+
+<example title="Basic UI with reactivity">
+import marimo as mo
+import matplotlib.pyplot as plt
+import numpy as np
+
+# Create a slider and display it
+n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+n_points # Display the slider
+
+# Generate random data based on slider value
+# This cell automatically re-executes when n_points.value changes
+x = np.random.rand(n_points.value)
+y = np.random.rand(n_points.value)
+
+plt.figure(figsize=(8, 6))
+plt.scatter(x, y, alpha=0.7)
+plt.title(f"Scatter plot with {n_points.value} points")
+plt.xlabel("X axis")
+plt.ylabel("Y axis")
+plt.gca() # Return the current axes to display the plot
+</example>"""
+
+ for language in language_rules:
+ if len(language_rules[language]) == 0:
+ continue
+
+ system_prompt += (
+ f"\n\n## Rules for {language}:\n{_rules(language_rules[language])}"
+ )
+
+ if custom_rules and custom_rules.strip():
+ system_prompt += f"\n\n## Additional rules:\n{custom_rules}"
+
+ if include_other_code:
+ system_prompt += "\n\n" + _tag(
+ "code_from_other_cells", include_other_code
+ )
+
+ if context:
+ system_prompt += _format_variables(context.variables)
+ system_prompt += _format_schema_info(context.schema)
+
+ return system_prompt
+
- return system_prompt
+def _tag(text: str, children: str) -> str:
+ return f"<{text}>\n{children.strip()}\n</{text}>"
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index 091992f817..2cf78bae9a 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -2,7 +2,7 @@
from __future__ import annotations
from abc import ABC, abstractmethod
-from collections.abc import Generator
+from collections.abc import Generator, Iterator
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
@@ -165,37 +165,16 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
"""Extract content from a response chunk."""
pass
- def as_stream_response(
- self, response: StreamT
- ) -> Generator[str, None, None]:
- """Convert a stream to a generator of strings."""
- original_content = ""
- buffer = ""
-
- for chunk in cast(Generator[ResponseT, None, None], response):
- content = self.extract_content(chunk)
- if not content:
- continue
-
- buffer += content
- original_content += content
-
- yield buffer
- buffer = ""
-
- LOGGER.debug(f"Completion content: {original_content}")
-
def collect_stream(self, response: StreamT) -> str:
"""Collect a stream into a single string."""
return "".join(self.as_stream_response(response))
- def make_stream_response(
+ def as_stream_response(
self, response: StreamT
) -> Generator[str, None, None]:
- """Convert a stream to a generator of strings, handling code blocks."""
+ """Convert a stream to a generator of strings."""
original_content = ""
buffer = ""
- in_code_fence = False
for chunk in cast(Generator[ResponseT, None, None], response):
content = self.extract_content(chunk)
@@ -204,39 +183,6 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
buffer += content
original_content += content
- first_newline = buffer.find("\n")
-
- # Open code-fence, with no newline
- # wait for the next newline
- if (
- buffer.startswith("```")
- and first_newline == -1
- and not in_code_fence
- ):
- continue
-
- if (
- buffer.startswith("```")
- and first_newline > 0
- and not in_code_fence
- ):
- # And also ends with ```
- if buffer.endswith("```"):
- yield buffer[first_newline + 1 : -3]
- buffer = ""
- in_code_fence = False
- continue
-
- yield buffer[first_newline + 1 :]
- buffer = ""
- in_code_fence = True
- continue
-
- if buffer.endswith("```") and in_code_fence:
- yield buffer[:-3]
- buffer = ""
- in_code_fence = False
- continue
yield buffer
buffer = ""
@@ -485,3 +431,76 @@ def get_max_tokens(config: MarimoConfig) -> int:
if "max_tokens" not in config["ai"]:
return DEFAULT_MAX_TOKENS
return config["ai"]["max_tokens"]
+
+
+def merge_backticks(chunks: Iterator[str]) -> Generator[str, None, None]:
+ buffer: Optional[str] = None
+
+ for chunk in chunks:
+ if buffer is None:
+ buffer = chunk
+ else:
+ # If buffer contains backticks, keep merging until we have no backticks,
+ # encounter a newline, or run out of chunks
+ if "`" in buffer:
+ buffer += chunk
+ # If we've hit a newline or no more backticks, yield the buffer
+ if "\n" in chunk or "`" not in buffer:
+ yield buffer
+ buffer = None
+ else:
+ # No backticks in buffer, yield it separately
+ yield buffer
+ buffer = chunk
+
+ # Return the last chunk if there's anything left
+ if buffer is not None:
+ yield buffer
+
+
+def without_wrapping_backticks(
+ chunks: Iterator[str],
+) -> Generator[str, None, None]:
+ """
+ Removes the first and last backticks (```) from a stream of text chunks.
+
+ Args:
+ chunks: An iterator of text chunks
+
+ Yields:
+ Text chunks with the first and last backticks removed if they exist
+ """
+
+ # First, merge backticks across chunks
+ chunks = merge_backticks(chunks)
+
+ first_chunk = True
+ buffer: Optional[str] = None
+ has_starting_backticks = False
+
+ for chunk in chunks:
+ # Handle the first chunk
+ if first_chunk:
+ first_chunk = False
+ if chunk.startswith("```"):
+ has_starting_backticks = True
+ chunk = chunk[3:] # Remove the starting backticks
+ # Also remove starting newline if present
+ if chunk.startswith("\n"):
+ chunk = chunk[1:]
+
+ # If we have a buffered chunk, yield it now
+ if buffer is not None:
+ yield buffer
+
+ # Store the current chunk as buffer for the next iteration
+ buffer = chunk
+
+ # Handle the last chunk
+ if buffer is not None:
+ # Remove ending newline if present
+ if buffer.endswith("\n```"):
+ buffer = buffer[:-4] # Remove the ending newline and backticks
+ elif has_starting_backticks and buffer.endswith("```"):
+ buffer = buffer[:-3] # Remove just the ending backticks
+ yield buffer
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index ba072f998f..99d6236861 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -10,13 +10,19 @@ from starlette.responses import PlainTextResponse, StreamingResponse
from marimo import _loggers
from marimo._ai._types import ChatMessage
from marimo._config.config import AiConfig, MarimoConfig
-from marimo._server.ai.prompts import Prompter
+from marimo._server.ai.prompts import (
+ FILL_ME_TAG,
+ get_chat_system_prompt,
+ get_inline_system_prompt,
+ get_refactor_or_insert_notebook_cell_system_prompt,
+)
from marimo._server.ai.providers import (
DEFAULT_MODEL,
AnyProviderConfig,
get_completion_provider,
get_max_tokens,
get_model,
+ without_wrapping_backticks,
)
from marimo._server.api.deps import AppState
from marimo._server.api.status import HTTPStatus
@@ -81,13 +87,16 @@ async def ai_completion(
custom_rules = ai_config.get("rules", None)
- prompter = Prompter(code=body.code)
- system_prompt = Prompter.get_system_prompt(
- language=body.language, custom_rules=custom_rules
- )
- prompt = prompter.get_prompt(
- user_prompt=body.prompt, include_other_code=body.include_other_code
+ system_prompt = get_refactor_or_insert_notebook_cell_system_prompt(
+ language=body.language,
+ is_insert=False,
+ custom_rules=custom_rules,
+ cell_code=body.code,
+ selected_text=body.selected_text,
+ other_cell_codes=body.include_other_code,
+ context=body.context,
)
+ prompt = body.prompt
model = get_model(ai_config)
provider = get_completion_provider(
@@ -101,7 +110,9 @@ async def ai_completion(
)
return StreamingResponse(
- content=provider.as_stream_response(response),
+ content=without_wrapping_backticks(
+ provider.as_stream_response(response)
+ ),
media_type="application/json",
)
@@ -128,12 +139,12 @@ async def ai_chat(
request, cls=ChatRequest, allow_unknown_keys=True
)
ai_config = get_ai_config(config)
+ custom_rules = ai_config.get("rules", None)
messages = body.messages
# Get the system prompt
- system_prompt = Prompter.get_chat_system_prompt(
- custom_rules=config.get("ai", {}).get("rules", None),
- variables=body.variables,
+ system_prompt = get_chat_system_prompt(
+ custom_rules=custom_rules,
context=body.context,
include_other_code=body.include_other_code,
)
@@ -185,9 +196,9 @@ async def ai_inline_completion(
body = await parse_request(
request, cls=AiInlineCompletionRequest, allow_unknown_keys=True
)
- prompt = f"{body.prefix}<FILL_ME>{body.suffix}"
+ prompt = f"{body.prefix}{FILL_ME_TAG}{body.suffix}"
messages = [ChatMessage(role="user", content=prompt)]
- system_prompt = Prompter.get_inline_system_prompt(language=body.language)
+ system_prompt = get_inline_system_prompt(language=body.language)
# This is currently not configurable and smaller than the default
# of 4096, since it is smaller/faster for inline completions
diff --git a/marimo/_server/models/completion.py b/marimo/_server/models/completion.py
index 29fa0f41c1..c7bb3c1b25 100644
--- a/marimo/_server/models/completion.py
+++ b/marimo/_server/models/completion.py
@@ -2,7 +2,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import Any, Literal, Optional
+from typing import Any, Literal, Optional, Union
from marimo._ai._types import ChatMessage
@@ -20,9 +20,17 @@ class SchemaTable:
columns: list[SchemaColumn]
+@dataclass
+class VariableContext:
+ name: str
+ value_type: str
+ preview_value: Any
+
+
@dataclass
class AiCompletionContext:
schema: list[SchemaTable] = field(default_factory=list)
+ variables: list[Union[VariableContext, str]] = field(default_factory=list)
Language = Literal["python", "markdown", "sql"]
@@ -33,6 +41,7 @@ class AiCompletionRequest:
prompt: str
include_other_code: str
code: str
+ selected_text: Optional[str] = None
context: Optional[AiCompletionContext] = None
language: Language = "python"
@@ -50,4 +59,4 @@ class ChatRequest:
include_other_code: str
messages: list[ChatMessage]
model: Optional[str] = None
- variables: Optional[list[str]] = None
+ variables: Optional[list[Union[VariableContext, str]]] = None
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 4bbb82cf7d..5a981dabea 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -13,8 +13,15 @@ components:
items:
$ref: '#/components/schemas/SchemaTable'
type: array
+ variables:
+ items:
+ oneOf:
+ - $ref: '#/components/schemas/VariableContext'
+ - type: string
+ type: array
required:
- schema
+ - variables
type: object
AiCompletionRequest:
properties:
@@ -33,6 +40,9 @@ components:
type: string
prompt:
type: string
+ selectedText:
+ nullable: true
+ type: string
required:
- prompt
- includeOtherCode
@@ -271,7 +281,9 @@ components:
type: string
variables:
items:
- type: string
+ oneOf:
+ - $ref: '#/components/schemas/VariableContext'
+ - type: string
nullable: true
type: array
required:
@@ -2404,6 +2416,18 @@ components:
- objectIds
- values
type: object
+ VariableContext:
+ properties:
+ name:
+ type: string
+ previewValue: {}
+ valueType:
+ type: string
+ required:
+ - name
+ - valueType
+ - previewValue
+ type: object
VariableDeclaration:
properties:
declared_by:
@@ -2483,7 +2507,7 @@ components:
type: object
info:
title: marimo API
- version: 0.12.2
+ version: 0.12.4
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index c0e27f45a9..450dfca4c7 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2338,6 +2338,7 @@ export interface components {
};
AiCompletionContext: {
schema: components["schemas"]["SchemaTable"][];
+ variables: (components["schemas"]["VariableContext"] | string)[];
};
AiCompletionRequest: {
code: string;
@@ -2346,6 +2347,7 @@ export interface components {
/** @enum {string} */
language: "python" | "markdown" | "sql";
prompt: string;
+ selectedText?: string | null;
};
AiInlineCompletionRequest: {
/** @enum {string} */
@@ -2448,7 +2450,7 @@ export interface components {
role: "user" | "assistant" | "system";
}[];
model?: string | null;
- variables?: string[] | null;
+ variables?: (components["schemas"]["VariableContext"] | string)[] | null;
};
CodeCompletionRequest: {
cellId: string;
@@ -3331,6 +3333,11 @@ export interface components {
objectIds: string[];
values: unknown[];
};
+ VariableContext: {
+ name: string;
+ previewValue: unknown;
+ valueType: string;
+ };
VariableDeclaration: {
declared_by: string[];
name: string;
diff --git a/tests/_server/ai/snapshots/chat_system_prompts.txt b/tests/_server/ai/snapshots/chat_system_prompts.txt
index 8d653790cf..3370280d28 100644
--- a/tests/_server/ai/snapshots/chat_system_prompts.txt
+++ b/tests/_server/ai/snapshots/chat_system_prompts.txt
@@ -2,71 +2,610 @@
==================== no custom rules ====================
-You are a helpful assistant working in a marimo notebook. You can answer questions and help with tasks. You may respond with markdown, code, or a combination of both. If you respond in code, you must use the appropriate language block. And you only work with two languages: Python and SQL. When responding in code, think of each block of code as a separate cell in the notebook. The notebook has 2 hard rules:
-1. Do not import the same library twice.
-2. Do not define a variable if it already exists. You may reference variables from previous cells, but you may not define a variable if it already exists.
+You are an AI assistant integrated into the marimo notebook code editor.
+You are a specialized AI assistant designed to help create data science notebooks using marimo.
+You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+
+Your goal is to do one of the following two things:
+
+1. Help users answer questions related to their notebook.
+2. Answer general-purpose questions unrelated to their particular notebook.
+
+It will be up to you to decide which of these you are doing based on what the user has told you. When unclear, ask clarifying questions to understand the user's intent before proceeding.
+
+You can respond with markdown, code, or a combination of both. You only work with two languages: Python and SQL.
+When responding in code, think of each block of code as a separate cell in the notebook.
+
+You have the following rules:
+
+- Do not import the same library twice.
+- Do not define a variable if it already exists. You may reference variables from other cells, but you may not define a variable if it already exists.
+
+# Marimo fundamentals
+
+Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+- Cells execute automatically when their dependencies change
+- Variables cannot be redeclared across cells
+- The notebook forms a directed acyclic graph (DAG)
+- The last expression in a cell is automatically displayed
+- UI elements are reactive and update the notebook automatically
+
+Marimo's reactivity means:
+- When a variable changes, all cells that use that variable automatically re-execute
+- UI elements trigger updates when their values change without explicit callbacks
+- UI element values are accessed through `.value` attribute
+- You cannot access a UI element's value in the same cell where it's defined
+
+## Best Practices
+
+<ui_elements>
+- Access UI element values with .value attribute (e.g., slider.value)
+- Create UI elements in one cell and reference them in later cells
+- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+- Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+- Group related UI elements for better organization
+</ui_elements>
+
+## Available UI elements
+
+* `mo.ui.altair_chart(altair_chart)` - create a reactive Altair chart
+* `mo.ui.button(value=None, kind='primary')` - create a clickable button
+* `mo.ui.run_button(label=None, tooltip=None, kind='primary')` - create a button that runs code
+* `mo.ui.checkbox(label='', value=False)` - create a checkbox
+* `mo.ui.chat(placeholder='', value=None)` - create a chat interface
+* `mo.ui.date(value=None, label=None, full_width=False)` - create a date picker
+* `mo.ui.dropdown(options, value=None, label=None, full_width=False)` - create a dropdown menu
+* `mo.ui.file(label='', multiple=False, full_width=False)` - create a file upload element
+* `mo.ui.number(value=None, label=None, full_width=False)` - create a number input
+* `mo.ui.radio(options, value=None, label=None, full_width=False)` - create radio buttons
+* `mo.ui.refresh(options: List[str], default_interval: str)` - create a refresh control
+* `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a slider
+* `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a range slider
+* `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)` - create an interactive table
+* `mo.ui.text(value='', label=None, full_width=False)` - create a text input
+* `mo.ui.text_area(value='', label=None, full_width=False)` - create a multi-line text input
+* `mo.ui.data_explorer(df)` - create an interactive dataframe explorer
+* `mo.ui.dataframe(df)` - display a dataframe with search, filter, and sort capabilities
+* `mo.ui.plotly(plotly_figure)` - create a reactive Plotly chart (supports scatter, treemap, and sunburst)
+* `mo.ui.tabs(elements: dict[str, mo.ui.Element])` - create a tabbed interface from a dictionary
+* `mo.ui.array(elements: list[mo.ui.Element])` - create an array of UI elements
+* `mo.ui.form(element: mo.ui.Element, label='', bordered=True)` - wrap an element in a form
+
+## Layout and utility functions
+
+* `mo.stop(predicate, output=None)` - stop execution conditionally
+* `mo.Html(html)` - display HTML
+* `mo.image(image)` - display an image
+* `mo.hstack(elements)` - stack elements horizontally
+* `mo.vstack(elements)` - stack elements vertically
+* `mo.tabs(elements)` - create a tabbed interface
+* `mo.mpl.interactive()` - make matplotlib plots interactive
+
+## Examples
+
+<example title="Basic UI with reactivity">
+import marimo as mo
+import matplotlib.pyplot as plt
+import numpy as np
-Rules for python:
-1. When using matplotlib to show plots, use plt.gca() instead of plt.show().
-2. If an import already exists, do not import it again.
-3. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
-
-Rules for sql:
+# Create a slider and display it
+n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+n_points # Display the slider
+
+# Generate random data based on slider value
+# This cell automatically re-executes when n_points.value changes
+x = np.random.rand(n_points.value)
+y = np.random.rand(n_points.value)
+
+plt.figure(figsize=(8, 6))
+plt.scatter(x, y, alpha=0.7)
+plt.title(f"Scatter plot with {n_points.value} points")
+plt.xlabel("X axis")
+plt.ylabel("Y axis")
+plt.gca() # Return the current axes to display the plot
+</example>
+
+## Rules for python:
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Rules for sql:
1. The SQL must use duckdb syntax.
==================== with custom rules ====================
-You are a helpful assistant working in a marimo notebook. You can answer questions and help with tasks. You may respond with markdown, code, or a combination of both. If you respond in code, you must use the appropriate language block. And you only work with two languages: Python and SQL. When responding in code, think of each block of code as a separate cell in the notebook. The notebook has 2 hard rules:
-1. Do not import the same library twice.
-2. Do not define a variable if it already exists. You may reference variables from previous cells, but you may not define a variable if it already exists.
-
-Rules for python:
-1. When using matplotlib to show plots, use plt.gca() instead of plt.show().
-2. If an import already exists, do not import it again.
-3. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+You are an AI assistant integrated into the marimo notebook code editor.
+You are a specialized AI assistant designed to help create data science notebooks using marimo.
+You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+
+Your goal is to do one of the following two things:
+
+1. Help users answer questions related to their notebook.
+2. Answer general-purpose questions unrelated to their particular notebook.
+
+It will be up to you to decide which of these you are doing based on what the user has told you. When unclear, ask clarifying questions to understand the user's intent before proceeding.
+
+You can respond with markdown, code, or a combination of both. You only work with two languages: Python and SQL.
+When responding in code, think of each block of code as a separate cell in the notebook.
+
+You have the following rules:
+
+- Do not import the same library twice.
+- Do not define a variable if it already exists. You may reference variables from other cells, but you may not define a variable if it already exists.
+
+# Marimo fundamentals
+
+Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+- Cells execute automatically when their dependencies change
+- Variables cannot be redeclared across cells
+- The notebook forms a directed acyclic graph (DAG)
+- The last expression in a cell is automatically displayed
+- UI elements are reactive and update the notebook automatically
+
+Marimo's reactivity means:
+- When a variable changes, all cells that use that variable automatically re-execute
+- UI elements trigger updates when their values change without explicit callbacks
+- UI element values are accessed through `.value` attribute
+- You cannot access a UI element's value in the same cell where it's defined
+
+## Best Practices
+
+<ui_elements>
+- Access UI element values with .value attribute (e.g., slider.value)
+- Create UI elements in one cell and reference them in later cells
+- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+- Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+- Group related UI elements for better organization
+</ui_elements>
+
+## Available UI elements
+
+* `mo.ui.altair_chart(altair_chart)` - create a reactive Altair chart
+* `mo.ui.button(value=None, kind='primary')` - create a clickable button
+* `mo.ui.run_button(label=None, tooltip=None, kind='primary')` - create a button that runs code
+* `mo.ui.checkbox(label='', value=False)` - create a checkbox
+* `mo.ui.chat(placeholder='', value=None)` - create a chat interface
+* `mo.ui.date(value=None, label=None, full_width=False)` - create a date picker
+* `mo.ui.dropdown(options, value=None, label=None, full_width=False)` - create a dropdown menu
+* `mo.ui.file(label='', multiple=False, full_width=False)` - create a file upload element
+* `mo.ui.number(value=None, label=None, full_width=False)` - create a number input
+* `mo.ui.radio(options, value=None, label=None, full_width=False)` - create radio buttons
+* `mo.ui.refresh(options: List[str], default_interval: str)` - create a refresh control
+* `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a slider
+* `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a range slider
+* `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)` - create an interactive table
+* `mo.ui.text(value='', label=None, full_width=False)` - create a text input
+* `mo.ui.text_area(value='', label=None, full_width=False)` - create a multi-line text input
+* `mo.ui.data_explorer(df)` - create an interactive dataframe explorer
+* `mo.ui.dataframe(df)` - display a dataframe with search, filter, and sort capabilities
+* `mo.ui.plotly(plotly_figure)` - create a reactive Plotly chart (supports scatter, treemap, and sunburst)
+* `mo.ui.tabs(elements: dict[str, mo.ui.Element])` - create a tabbed interface from a dictionary
+* `mo.ui.array(elements: list[mo.ui.Element])` - create an array of UI elements
+* `mo.ui.form(element: mo.ui.Element, label='', bordered=True)` - wrap an element in a form
+
+## Layout and utility functions
+
+* `mo.stop(predicate, output=None)` - stop execution conditionally
+* `mo.Html(html)` - display HTML
+* `mo.image(image)` - display an image
+* `mo.hstack(elements)` - stack elements horizontally
+* `mo.vstack(elements)` - stack elements vertically
+* `mo.tabs(elements)` - create a tabbed interface
+* `mo.mpl.interactive()` - make matplotlib plots interactive
+
+## Examples
+
+<example title="Basic UI with reactivity">
+import marimo as mo
+import matplotlib.pyplot as plt
+import numpy as np
-Rules for sql:
+# Create a slider and display it
+n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+n_points # Display the slider
+
+# Generate random data based on slider value
+# This cell automatically re-executes when n_points.value changes
+x = np.random.rand(n_points.value)
+y = np.random.rand(n_points.value)
+
+plt.figure(figsize=(8, 6))
+plt.scatter(x, y, alpha=0.7)
+plt.title(f"Scatter plot with {n_points.value} points")
+plt.xlabel("X axis")
+plt.ylabel("Y axis")
+plt.gca() # Return the current axes to display the plot
+</example>
+
+## Rules for python:
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Rules for sql:
1. The SQL must use duckdb syntax.
-Additional rules:
+## Additional rules:
Always be polite.
==================== with variables ====================
-You are a helpful assistant working in a marimo notebook. You can answer questions and help with tasks. You may respond with markdown, code, or a combination of both. If you respond in code, you must use the appropriate language block. And you only work with two languages: Python and SQL. When responding in code, think of each block of code as a separate cell in the notebook. The notebook has 2 hard rules:
-1. Do not import the same library twice.
-2. Do not define a variable if it already exists. You may reference variables from previous cells, but you may not define a variable if it already exists.
+You are an AI assistant integrated into the marimo notebook code editor.
+You are a specialized AI assistant designed to help create data science notebooks using marimo.
+You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+
+Your goal is to do one of the following two things:
+
+1. Help users answer questions related to their notebook.
+2. Answer general-purpose questions unrelated to their particular notebook.
+
+It will be up to you to decide which of these you are doing based on what the user has told you. When unclear, ask clarifying questions to understand the user's intent before proceeding.
+
+You can respond with markdown, code, or a combination of both. You only work with two languages: Python and SQL.
+When responding in code, think of each block of code as a separate cell in the notebook.
+
+You have the following rules:
+
+- Do not import the same library twice.
+- Do not define a variable if it already exists. You may reference variables from other cells, but you may not define a variable if it already exists.
+
+# Marimo fundamentals
+
+Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+- Cells execute automatically when their dependencies change
+- Variables cannot be redeclared across cells
+- The notebook forms a directed acyclic graph (DAG)
+- The last expression in a cell is automatically displayed
+- UI elements are reactive and update the notebook automatically
+
+Marimo's reactivity means:
+- When a variable changes, all cells that use that variable automatically re-execute
+- UI elements trigger updates when their values change without explicit callbacks
+- UI element values are accessed through `.value` attribute
+- You cannot access a UI element's value in the same cell where it's defined
+
+## Best Practices
+
+<ui_elements>
+- Access UI element values with .value attribute (e.g., slider.value)
+- Create UI elements in one cell and reference them in later cells
+- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+- Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+- Group related UI elements for better organization
+</ui_elements>
+
+## Available UI elements
+
+* `mo.ui.altair_chart(altair_chart)` - create a reactive Altair chart
+* `mo.ui.button(value=None, kind='primary')` - create a clickable button
+* `mo.ui.run_button(label=None, tooltip=None, kind='primary')` - create a button that runs code
+* `mo.ui.checkbox(label='', value=False)` - create a checkbox
+* `mo.ui.chat(placeholder='', value=None)` - create a chat interface
+* `mo.ui.date(value=None, label=None, full_width=False)` - create a date picker
+* `mo.ui.dropdown(options, value=None, label=None, full_width=False)` - create a dropdown menu
+* `mo.ui.file(label='', multiple=False, full_width=False)` - create a file upload element
+* `mo.ui.number(value=None, label=None, full_width=False)` - create a number input
+* `mo.ui.radio(options, value=None, label=None, full_width=False)` - create radio buttons
+* `mo.ui.refresh(options: List[str], default_interval: str)` - create a refresh control
+* `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a slider
+* `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a range slider
+* `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)` - create an interactive table
+* `mo.ui.text(value='', label=None, full_width=False)` - create a text input
+* `mo.ui.text_area(value='', label=None, full_width=False)` - create a multi-line text input
+* `mo.ui.data_explorer(df)` - create an interactive dataframe explorer
+* `mo.ui.dataframe(df)` - display a dataframe with search, filter, and sort capabilities
+* `mo.ui.plotly(plotly_figure)` - create a reactive Plotly chart (supports scatter, treemap, and sunburst)
+* `mo.ui.tabs(elements: dict[str, mo.ui.Element])` - create a tabbed interface from a dictionary
+* `mo.ui.array(elements: list[mo.ui.Element])` - create an array of UI elements
+* `mo.ui.form(element: mo.ui.Element, label='', bordered=True)` - wrap an element in a form
+
+## Layout and utility functions
+
+* `mo.stop(predicate, output=None)` - stop execution conditionally
+* `mo.Html(html)` - display HTML
+* `mo.image(image)` - display an image
+* `mo.hstack(elements)` - stack elements horizontally
+* `mo.vstack(elements)` - stack elements vertically
+* `mo.tabs(elements)` - create a tabbed interface
+* `mo.mpl.interactive()` - make matplotlib plots interactive
+
+## Examples
+
+<example title="Basic UI with reactivity">
+import marimo as mo
+import matplotlib.pyplot as plt
+import numpy as np
-Rules for python:
-1. When using matplotlib to show plots, use plt.gca() instead of plt.show().
-2. If an import already exists, do not import it again.
-3. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+# Create a slider and display it
+n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+n_points # Display the slider
+
+# Generate random data based on slider value
+# This cell automatically re-executes when n_points.value changes
+x = np.random.rand(n_points.value)
+y = np.random.rand(n_points.value)
+
+plt.figure(figsize=(8, 6))
+plt.scatter(x, y, alpha=0.7)
+plt.title(f"Scatter plot with {n_points.value} points")
+plt.xlabel("X axis")
+plt.ylabel("Y axis")
+plt.gca() # Return the current axes to display the plot
+</example>
+
+## Rules for python:
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Rules for sql:
+1. The SQL must use duckdb syntax.
+
+## Available variables from other cells:
+- variable: `var1`- variable: `var2`
+
+==================== with VariableContext objects ====================
+
+
+You are an AI assistant integrated into the marimo notebook code editor.
+You are a specialized AI assistant designed to help create data science notebooks using marimo.
+You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+
+Your goal is to do one of the following two things:
+
+1. Help users answer questions related to their notebook.
+2. Answer general-purpose questions unrelated to their particular notebook.
+
+It will be up to you to decide which of these you are doing based on what the user has told you. When unclear, ask clarifying questions to understand the user's intent before proceeding.
+
+You can respond with markdown, code, or a combination of both. You only work with two languages: Python and SQL.
+When responding in code, think of each block of code as a separate cell in the notebook.
+
+You have the following rules:
+
+- Do not import the same library twice.
+- Do not define a variable if it already exists. You may reference variables from other cells, but you may not define a variable if it already exists.
+
+# Marimo fundamentals
+
+Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+- Cells execute automatically when their dependencies change
+- Variables cannot be redeclared across cells
+- The notebook forms a directed acyclic graph (DAG)
+- The last expression in a cell is automatically displayed
+- UI elements are reactive and update the notebook automatically
+
+Marimo's reactivity means:
+- When a variable changes, all cells that use that variable automatically re-execute
+- UI elements trigger updates when their values change without explicit callbacks
+- UI element values are accessed through `.value` attribute
+- You cannot access a UI element's value in the same cell where it's defined
+
+## Best Practices
+
+<ui_elements>
+- Access UI element values with .value attribute (e.g., slider.value)
+- Create UI elements in one cell and reference them in later cells
+- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+- Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+- Group related UI elements for better organization
+</ui_elements>
+
+## Available UI elements
+
+* `mo.ui.altair_chart(altair_chart)` - create a reactive Altair chart
+* `mo.ui.button(value=None, kind='primary')` - create a clickable button
+* `mo.ui.run_button(label=None, tooltip=None, kind='primary')` - create a button that runs code
+* `mo.ui.checkbox(label='', value=False)` - create a checkbox
+* `mo.ui.chat(placeholder='', value=None)` - create a chat interface
+* `mo.ui.date(value=None, label=None, full_width=False)` - create a date picker
+* `mo.ui.dropdown(options, value=None, label=None, full_width=False)` - create a dropdown menu
+* `mo.ui.file(label='', multiple=False, full_width=False)` - create a file upload element
+* `mo.ui.number(value=None, label=None, full_width=False)` - create a number input
+* `mo.ui.radio(options, value=None, label=None, full_width=False)` - create radio buttons
+* `mo.ui.refresh(options: List[str], default_interval: str)` - create a refresh control
+* `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a slider
+* `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a range slider
+* `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)` - create an interactive table
+* `mo.ui.text(value='', label=None, full_width=False)` - create a text input
+* `mo.ui.text_area(value='', label=None, full_width=False)` - create a multi-line text input
+* `mo.ui.data_explorer(df)` - create an interactive dataframe explorer
+* `mo.ui.dataframe(df)` - display a dataframe with search, filter, and sort capabilities
+* `mo.ui.plotly(plotly_figure)` - create a reactive Plotly chart (supports scatter, treemap, and sunburst)
+* `mo.ui.tabs(elements: dict[str, mo.ui.Element])` - create a tabbed interface from a dictionary
+* `mo.ui.array(elements: list[mo.ui.Element])` - create an array of UI elements
+* `mo.ui.form(element: mo.ui.Element, label='', bordered=True)` - wrap an element in a form
+
+## Layout and utility functions
+
+* `mo.stop(predicate, output=None)` - stop execution conditionally
+* `mo.Html(html)` - display HTML
+* `mo.image(image)` - display an image
+* `mo.hstack(elements)` - stack elements horizontally
+* `mo.vstack(elements)` - stack elements vertically
+* `mo.tabs(elements)` - create a tabbed interface
+* `mo.mpl.interactive()` - make matplotlib plots interactive
+
+## Examples
+
+<example title="Basic UI with reactivity">
+import marimo as mo
+import matplotlib.pyplot as plt
+import numpy as np
-Rules for sql:
+# Create a slider and display it
+n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+n_points # Display the slider
+
+# Generate random data based on slider value
+# This cell automatically re-executes when n_points.value changes
+x = np.random.rand(n_points.value)
+y = np.random.rand(n_points.value)
+
+plt.figure(figsize=(8, 6))
+plt.scatter(x, y, alpha=0.7)
+plt.title(f"Scatter plot with {n_points.value} points")
+plt.xlabel("X axis")
+plt.ylabel("Y axis")
+plt.gca() # Return the current axes to display the plot
+</example>
+
+## Rules for python:
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Rules for sql:
1. The SQL must use duckdb syntax.
-Variables to use but not define:
-['var1', 'var2']
+## Available variables from other cells:
+- variable: `df`
+ - value_type: DataFrame
+ - value_preview: <DataFrame with 100 rows and 5 columns>
+- variable: `model`
+ - value_type: Model
+ - value_preview: <Model object>
-==================== with context ====================
-You are a helpful assistant working in a marimo notebook. You can answer questions and help with tasks. You may respond with markdown, code, or a combination of both. If you respond in code, you must use the appropriate language block. And you only work with two languages: Python and SQL. When responding in code, think of each block of code as a separate cell in the notebook. The notebook has 2 hard rules:
-1. Do not import the same library twice.
-2. Do not define a variable if it already exists. You may reference variables from previous cells, but you may not define a variable if it already exists.
+==================== with context ====================
-Rules for python:
-1. When using matplotlib to show plots, use plt.gca() instead of plt.show().
-2. If an import already exists, do not import it again.
-3. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+You are an AI assistant integrated into the marimo notebook code editor.
+You are a specialized AI assistant designed to help create data science notebooks using marimo.
+You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+
+Your goal is to do one of the following two things:
+
+1. Help users answer questions related to their notebook.
+2. Answer general-purpose questions unrelated to their particular notebook.
+
+It will be up to you to decide which of these you are doing based on what the user has told you. When unclear, ask clarifying questions to understand the user's intent before proceeding.
+
+You can respond with markdown, code, or a combination of both. You only work with two languages: Python and SQL.
+When responding in code, think of each block of code as a separate cell in the notebook.
+
+You have the following rules:
+
+- Do not import the same library twice.
+- Do not define a variable if it already exists. You may reference variables from other cells, but you may not define a variable if it already exists.
+
+# Marimo fundamentals
+
+Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+- Cells execute automatically when their dependencies change
+- Variables cannot be redeclared across cells
+- The notebook forms a directed acyclic graph (DAG)
+- The last expression in a cell is automatically displayed
+- UI elements are reactive and update the notebook automatically
+
+Marimo's reactivity means:
+- When a variable changes, all cells that use that variable automatically re-execute
+- UI elements trigger updates when their values change without explicit callbacks
+- UI element values are accessed through `.value` attribute
+- You cannot access a UI element's value in the same cell where it's defined
+
+## Best Practices
+
+<ui_elements>
+- Access UI element values with .value attribute (e.g., slider.value)
+- Create UI elements in one cell and reference them in later cells
+- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+- Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+- Group related UI elements for better organization
+</ui_elements>
+
+## Available UI elements
+
+* `mo.ui.altair_chart(altair_chart)` - create a reactive Altair chart
+* `mo.ui.button(value=None, kind='primary')` - create a clickable button
+* `mo.ui.run_button(label=None, tooltip=None, kind='primary')` - create a button that runs code
+* `mo.ui.checkbox(label='', value=False)` - create a checkbox
+* `mo.ui.chat(placeholder='', value=None)` - create a chat interface
+* `mo.ui.date(value=None, label=None, full_width=False)` - create a date picker
+* `mo.ui.dropdown(options, value=None, label=None, full_width=False)` - create a dropdown menu
+* `mo.ui.file(label='', multiple=False, full_width=False)` - create a file upload element
+* `mo.ui.number(value=None, label=None, full_width=False)` - create a number input
+* `mo.ui.radio(options, value=None, label=None, full_width=False)` - create radio buttons
+* `mo.ui.refresh(options: List[str], default_interval: str)` - create a refresh control
+* `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a slider
+* `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a range slider
+* `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)` - create an interactive table
+* `mo.ui.text(value='', label=None, full_width=False)` - create a text input
+* `mo.ui.text_area(value='', label=None, full_width=False)` - create a multi-line text input
+* `mo.ui.data_explorer(df)` - create an interactive dataframe explorer
+* `mo.ui.dataframe(df)` - display a dataframe with search, filter, and sort capabilities
+* `mo.ui.plotly(plotly_figure)` - create a reactive Plotly chart (supports scatter, treemap, and sunburst)
+* `mo.ui.tabs(elements: dict[str, mo.ui.Element])` - create a tabbed interface from a dictionary
+* `mo.ui.array(elements: list[mo.ui.Element])` - create an array of UI elements
+* `mo.ui.form(element: mo.ui.Element, label='', bordered=True)` - wrap an element in a form
+
+## Layout and utility functions
+
+* `mo.stop(predicate, output=None)` - stop execution conditionally
+* `mo.Html(html)` - display HTML
+* `mo.image(image)` - display an image
+* `mo.hstack(elements)` - stack elements horizontally
+* `mo.vstack(elements)` - stack elements vertically
+* `mo.tabs(elements)` - create a tabbed interface
+* `mo.mpl.interactive()` - make matplotlib plots interactive
+
+## Examples
+
+<example title="Basic UI with reactivity">
+import marimo as mo
+import matplotlib.pyplot as plt
+import numpy as np
-Rules for sql:
+# Create a slider and display it
+n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+n_points # Display the slider
+
+# Generate random data based on slider value
+# This cell automatically re-executes when n_points.value changes
+x = np.random.rand(n_points.value)
+y = np.random.rand(n_points.value)
+
+plt.figure(figsize=(8, 6))
+plt.scatter(x, y, alpha=0.7)
+plt.title(f"Scatter plot with {n_points.value} points")
+plt.xlabel("X axis")
+plt.ylabel("Y axis")
+plt.gca() # Return the current axes to display the plot
+</example>
+
+## Rules for python:
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Rules for sql:
1. The SQL must use duckdb syntax.
-Available schema:
+## Available schema:
- Table: df_1
- Column: age
- Type: int
@@ -85,49 +624,257 @@ Available schema:
==================== with other code ====================
-You are a helpful assistant working in a marimo notebook. You can answer questions and help with tasks. You may respond with markdown, code, or a combination of both. If you respond in code, you must use the appropriate language block. And you only work with two languages: Python and SQL. When responding in code, think of each block of code as a separate cell in the notebook. The notebook has 2 hard rules:
-1. Do not import the same library twice.
-2. Do not define a variable if it already exists. You may reference variables from previous cells, but you may not define a variable if it already exists.
+You are an AI assistant integrated into the marimo notebook code editor.
+You are a specialized AI assistant designed to help create data science notebooks using marimo.
+You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+
+Your goal is to do one of the following two things:
+
+1. Help users answer questions related to their notebook.
+2. Answer general-purpose questions unrelated to their particular notebook.
+
+It will be up to you to decide which of these you are doing based on what the user has told you. When unclear, ask clarifying questions to understand the user's intent before proceeding.
+
+You can respond with markdown, code, or a combination of both. You only work with two languages: Python and SQL.
+When responding in code, think of each block of code as a separate cell in the notebook.
+
+You have the following rules:
+
+- Do not import the same library twice.
+- Do not define a variable if it already exists. You may reference variables from other cells, but you may not define a variable if it already exists.
+
+# Marimo fundamentals
+
+Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+- Cells execute automatically when their dependencies change
+- Variables cannot be redeclared across cells
+- The notebook forms a directed acyclic graph (DAG)
+- The last expression in a cell is automatically displayed
+- UI elements are reactive and update the notebook automatically
+
+Marimo's reactivity means:
+- When a variable changes, all cells that use that variable automatically re-execute
+- UI elements trigger updates when their values change without explicit callbacks
+- UI element values are accessed through `.value` attribute
+- You cannot access a UI element's value in the same cell where it's defined
+
+## Best Practices
+
+<ui_elements>
+- Access UI element values with .value attribute (e.g., slider.value)
+- Create UI elements in one cell and reference them in later cells
+- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+- Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+- Group related UI elements for better organization
+</ui_elements>
+
+## Available UI elements
+
+* `mo.ui.altair_chart(altair_chart)` - create a reactive Altair chart
+* `mo.ui.button(value=None, kind='primary')` - create a clickable button
+* `mo.ui.run_button(label=None, tooltip=None, kind='primary')` - create a button that runs code
+* `mo.ui.checkbox(label='', value=False)` - create a checkbox
+* `mo.ui.chat(placeholder='', value=None)` - create a chat interface
+* `mo.ui.date(value=None, label=None, full_width=False)` - create a date picker
+* `mo.ui.dropdown(options, value=None, label=None, full_width=False)` - create a dropdown menu
+* `mo.ui.file(label='', multiple=False, full_width=False)` - create a file upload element
+* `mo.ui.number(value=None, label=None, full_width=False)` - create a number input
+* `mo.ui.radio(options, value=None, label=None, full_width=False)` - create radio buttons
+* `mo.ui.refresh(options: List[str], default_interval: str)` - create a refresh control
+* `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a slider
+* `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a range slider
+* `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)` - create an interactive table
+* `mo.ui.text(value='', label=None, full_width=False)` - create a text input
+* `mo.ui.text_area(value='', label=None, full_width=False)` - create a multi-line text input
+* `mo.ui.data_explorer(df)` - create an interactive dataframe explorer
+* `mo.ui.dataframe(df)` - display a dataframe with search, filter, and sort capabilities
+* `mo.ui.plotly(plotly_figure)` - create a reactive Plotly chart (supports scatter, treemap, and sunburst)
+* `mo.ui.tabs(elements: dict[str, mo.ui.Element])` - create a tabbed interface from a dictionary
+* `mo.ui.array(elements: list[mo.ui.Element])` - create an array of UI elements
+* `mo.ui.form(element: mo.ui.Element, label='', bordered=True)` - wrap an element in a form
+
+## Layout and utility functions
+
+* `mo.stop(predicate, output=None)` - stop execution conditionally
+* `mo.Html(html)` - display HTML
+* `mo.image(image)` - display an image
+* `mo.hstack(elements)` - stack elements horizontally
+* `mo.vstack(elements)` - stack elements vertically
+* `mo.tabs(elements)` - create a tabbed interface
+* `mo.mpl.interactive()` - make matplotlib plots interactive
+
+## Examples
+
+<example title="Basic UI with reactivity">
+import marimo as mo
+import matplotlib.pyplot as plt
+import numpy as np
-Rules for python:
-1. When using matplotlib to show plots, use plt.gca() instead of plt.show().
-2. If an import already exists, do not import it again.
-3. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
-
-Rules for sql:
+# Create a slider and display it
+n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+n_points # Display the slider
+
+# Generate random data based on slider value
+# This cell automatically re-executes when n_points.value changes
+x = np.random.rand(n_points.value)
+y = np.random.rand(n_points.value)
+
+plt.figure(figsize=(8, 6))
+plt.scatter(x, y, alpha=0.7)
+plt.title(f"Scatter plot with {n_points.value} points")
+plt.xlabel("X axis")
+plt.ylabel("Y axis")
+plt.gca() # Return the current axes to display the plot
+</example>
+
+## Rules for python:
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Rules for sql:
1. The SQL must use duckdb syntax.
-Code from other cells:
+<code_from_other_cells>
import pandas as pd
import numpy as np
+</code_from_other_cells>
==================== kitchen sink ====================
-You are a helpful assistant working in a marimo notebook. You can answer questions and help with tasks. You may respond with markdown, code, or a combination of both. If you respond in code, you must use the appropriate language block. And you only work with two languages: Python and SQL. When responding in code, think of each block of code as a separate cell in the notebook. The notebook has 2 hard rules:
-1. Do not import the same library twice.
-2. Do not define a variable if it already exists. You may reference variables from previous cells, but you may not define a variable if it already exists.
+You are an AI assistant integrated into the marimo notebook code editor.
+You are a specialized AI assistant designed to help create data science notebooks using marimo.
+You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+
+Your goal is to do one of the following two things:
+
+1. Help users answer questions related to their notebook.
+2. Answer general-purpose questions unrelated to their particular notebook.
+
+It will be up to you to decide which of these you are doing based on what the user has told you. When unclear, ask clarifying questions to understand the user's intent before proceeding.
+
+You can respond with markdown, code, or a combination of both. You only work with two languages: Python and SQL.
+When responding in code, think of each block of code as a separate cell in the notebook.
+
+You have the following rules:
+
+- Do not import the same library twice.
+- Do not define a variable if it already exists. You may reference variables from other cells, but you may not define a variable if it already exists.
+
+# Marimo fundamentals
+
+Marimo is a reactive notebook that differs from traditional notebooks in key ways:
+- Cells execute automatically when their dependencies change
+- Variables cannot be redeclared across cells
+- The notebook forms a directed acyclic graph (DAG)
+- The last expression in a cell is automatically displayed
+- UI elements are reactive and update the notebook automatically
+
+Marimo's reactivity means:
+- When a variable changes, all cells that use that variable automatically re-execute
+- UI elements trigger updates when their values change without explicit callbacks
+- UI element values are accessed through `.value` attribute
+- You cannot access a UI element's value in the same cell where it's defined
+
+## Best Practices
+
+<ui_elements>
+- Access UI element values with .value attribute (e.g., slider.value)
+- Create UI elements in one cell and reference them in later cells
+- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()
+- Prefer reactive updates over callbacks (marimo handles reactivity automatically)
+- Group related UI elements for better organization
+</ui_elements>
+
+## Available UI elements
+
+* `mo.ui.altair_chart(altair_chart)` - create a reactive Altair chart
+* `mo.ui.button(value=None, kind='primary')` - create a clickable button
+* `mo.ui.run_button(label=None, tooltip=None, kind='primary')` - create a button that runs code
+* `mo.ui.checkbox(label='', value=False)` - create a checkbox
+* `mo.ui.chat(placeholder='', value=None)` - create a chat interface
+* `mo.ui.date(value=None, label=None, full_width=False)` - create a date picker
+* `mo.ui.dropdown(options, value=None, label=None, full_width=False)` - create a dropdown menu
+* `mo.ui.file(label='', multiple=False, full_width=False)` - create a file upload element
+* `mo.ui.number(value=None, label=None, full_width=False)` - create a number input
+* `mo.ui.radio(options, value=None, label=None, full_width=False)` - create radio buttons
+* `mo.ui.refresh(options: List[str], default_interval: str)` - create a refresh control
+* `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a slider
+* `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)` - create a range slider
+* `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)` - create an interactive table
+* `mo.ui.text(value='', label=None, full_width=False)` - create a text input
+* `mo.ui.text_area(value='', label=None, full_width=False)` - create a multi-line text input
+* `mo.ui.data_explorer(df)` - create an interactive dataframe explorer
+* `mo.ui.dataframe(df)` - display a dataframe with search, filter, and sort capabilities
+* `mo.ui.plotly(plotly_figure)` - create a reactive Plotly chart (supports scatter, treemap, and sunburst)
+* `mo.ui.tabs(elements: dict[str, mo.ui.Element])` - create a tabbed interface from a dictionary
+* `mo.ui.array(elements: list[mo.ui.Element])` - create an array of UI elements
+* `mo.ui.form(element: mo.ui.Element, label='', bordered=True)` - wrap an element in a form
+
+## Layout and utility functions
+
+* `mo.stop(predicate, output=None)` - stop execution conditionally
+* `mo.Html(html)` - display HTML
+* `mo.image(image)` - display an image
+* `mo.hstack(elements)` - stack elements horizontally
+* `mo.vstack(elements)` - stack elements vertically
+* `mo.tabs(elements)` - create a tabbed interface
+* `mo.mpl.interactive()` - make matplotlib plots interactive
+
+## Examples
+
+<example title="Basic UI with reactivity">
+import marimo as mo
+import matplotlib.pyplot as plt
+import numpy as np
-Rules for python:
-1. When using matplotlib to show plots, use plt.gca() instead of plt.show().
-2. If an import already exists, do not import it again.
-3. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
-
-Rules for sql:
+# Create a slider and display it
+n_points = mo.ui.slider(10, 100, value=50, label="Number of points")
+n_points # Display the slider
+
+# Generate random data based on slider value
+# This cell automatically re-executes when n_points.value changes
+x = np.random.rand(n_points.value)
+y = np.random.rand(n_points.value)
+
+plt.figure(figsize=(8, 6))
+plt.scatter(x, y, alpha=0.7)
+plt.title(f"Scatter plot with {n_points.value} points")
+plt.xlabel("X axis")
+plt.ylabel("Y axis")
+plt.gca() # Return the current axes to display the plot
+</example>
+
+## Rules for python:
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Rules for sql:
1. The SQL must use duckdb syntax.
-Additional rules:
+## Additional rules:
Always be polite.
-Variables to use but not define:
-['var1', 'var2']
-
-Code from other cells:
+<code_from_other_cells>
import pandas as pd
import numpy as np
+</code_from_other_cells>
+
+## Available variables from other cells:
+- variable: `var1`- variable: `var2`
-Available schema:
+## Available schema:
- Table: df_1
- Column: age
- Type: int
diff --git a/tests/_server/ai/snapshots/edit_inline_prompts.txt b/tests/_server/ai/snapshots/edit_inline_prompts.txt
new file mode 100644
index 0000000000..ba7cfec4b1
--- /dev/null
+++ b/tests/_server/ai/snapshots/edit_inline_prompts.txt
@@ -0,0 +1 @@
+You are a python programmer that replaces <FILL_ME> part with the right code. Only output the code that replaces <FILL_ME> part. Do not add any explanation or markdown.
\ No newline at end of file
diff --git a/tests/_server/ai/snapshots/system_prompts.txt b/tests/_server/ai/snapshots/system_prompts.txt
index a564170284..2ca0e3db40 100644
--- a/tests/_server/ai/snapshots/system_prompts.txt
+++ b/tests/_server/ai/snapshots/system_prompts.txt
@@ -2,52 +2,116 @@
==================== python ====================
-You are a helpful assistant that can answer questions about python. Here are your rules:
-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.
+You are an AI assistant integrated into the marimo notebook code editor.
+You goal is to create a new cell in the notebook.
+Your output must be valid python code.
+You can use the provided context to help you write the new cell.
+You can reference variables from other cells, but you cannot redefine a variable if it already exists.
+Immediately start with the following format with no remarks.
+
+```
+{CELL_CODE}
+```
+
+## Rules for python
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
==================== markdown ====================
-You are a helpful assistant that can answer questions about markdown. Here are your rules:
-1. Do not describe the code, just write the code.
-2. Do not output markdown or backticks.
+You are an AI assistant integrated into the marimo notebook code editor.
+You goal is to create a new cell in the notebook.
+Your output must be valid markdown code.
+You can use the provided context to help you write the new cell.
+You can reference variables from other cells, but you cannot redefine a variable if it already exists.
+Immediately start with the following format with no remarks.
+
+```
+{CELL_CODE}
+```
==================== sql ====================
-You are a helpful assistant that can answer questions about sql. Here are your rules:
-1. Do not describe the code, just write the code.
-2. Do not output markdown or backticks.
-3. The SQL must use duckdb syntax.
+You are an AI assistant integrated into the marimo notebook code editor.
+You goal is to create a new cell in the notebook.
+Your output must be valid sql code.
+You can use the provided context to help you write the new cell.
+You can reference variables from other cells, but you cannot redefine a variable if it already exists.
+Immediately start with the following format with no remarks.
+
+```
+{CELL_CODE}
+```
+
+## Rules for sql
+1. The SQL must use duckdb syntax.
==================== idk ====================
-You are a helpful assistant that can answer questions.
+You are an AI assistant integrated into the marimo notebook code editor.
+You goal is to create a new cell in the notebook.
+Your output must be valid idk code.
+You can use the provided context to help you write the new cell.
+You can reference variables from other cells, but you cannot redefine a variable if it already exists.
+Immediately start with the following format with no remarks.
+
+```
+{CELL_CODE}
+```
==================== with custom rules ====================
-You are a helpful assistant that can answer questions about python. Here are your rules:
-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.
+You are an AI assistant integrated into the marimo notebook code editor.
+You goal is to create a new cell in the notebook.
+Your output must be valid python code.
+You can use the provided context to help you write the new cell.
+You can reference variables from other cells, but you cannot redefine a variable if it already exists.
+Immediately start with the following format with no remarks.
+
+```
+{CELL_CODE}
+```
-Additional rules:
+## Rules for python
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Additional rules:
Always use type hints.
==================== with context ====================
-You are a helpful assistant that can answer questions about python. Here are your rules:
-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.
+You are an AI assistant integrated into the marimo notebook code editor.
+You goal is to create a new cell in the notebook.
+Your output must be valid python code.
+You can use the provided context to help you write the new cell.
+You can reference variables from other cells, but you cannot redefine a variable if it already exists.
+Immediately start with the following format with no remarks.
+
+```
+{CELL_CODE}
+```
-Available schema:
+## Rules for python
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Available schema:
- Table: df_1
- Column: age
- Type: int
@@ -55,3 +119,172 @@ Available schema:
- Column: name
- Type: str
- Sample values: Alice, Bob, Charlie
+
+
+==================== with is_insert=True ====================
+
+Here's a python document from a Python notebook that I'm going to ask you to make an edit to.
+
+The point you'll need to insert at is marked with <insert_here></insert_here>.
+
+
+<document>
+def fib(n):
+ <insert_here></insert_here>
+</document>
+
+You can't replace the content, your answer will be inserted in place of the <insert_here></insert_here> tags. Don't include the insert_here tags in your output.
+Match the indentation in the original file in the inserted content, don't include any indentation on blank lines.
+Immediately start with the following format with no remarks:
+
+```
+{INSERTED_CODE}
+```
+
+## Rules for python
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+==================== with cell_code ====================
+
+Here's a python document from a Python notebook that I'm going to ask you to make an edit to.
+
+The section you'll need to rewrite is marked with <rewrite_this></rewrite_this> tags.
+
+
+<document>
+def hello():
+ <rewrite_this>print('Hello, world!')</rewrite_this>
+</document>
+
+Only make changes that are necessary to fulfill the prompt, leave everything else as-is. All surrounding content will be preserved.
+Start at the indentation level in the original file in the rewritten content. Don't stop until you've rewritten the entire section, even if you have no more changes to make, always write out the whole section with no unnecessary elisions.
+Immediately start with the following format with no remarks:
+
+```
+{REWRITTEN_CODE}
+```
+
+And here's the section to rewrite based on that prompt again for reference:
+
+<rewrite_this>
+print('Hello, world!')
+</rewrite_this>
+
+## Rules for python
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+==================== with selected_text ====================
+
+Here's a python document from a Python notebook that I'm going to ask you to make an edit to.
+
+The section you'll need to rewrite is marked with <rewrite_this></rewrite_this> tags.
+
+
+<document>
+def hello():
+ <rewrite_this>print('Hello, world!')</rewrite_this>
+</document>
+
+Only make changes that are necessary to fulfill the prompt, leave everything else as-is. All surrounding content will be preserved.
+Start at the indentation level in the original file in the rewritten content. Don't stop until you've rewritten the entire section, even if you have no more changes to make, always write out the whole section with no unnecessary elisions.
+Immediately start with the following format with no remarks:
+
+```
+{REWRITTEN_CODE}
+```
+
+And here's the section to rewrite based on that prompt again for reference:
+
+<rewrite_this>
+print('Hello, world!')
+</rewrite_this>
+
+## Rules for python
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+==================== with other_cell_codes ====================
+
+Here's a python document from a Python notebook that I'm going to ask you to make an edit to.
+
+The section you'll need to rewrite is marked with <rewrite_this></rewrite_this> tags.
+
+
+<document>
+<rewrite_this>pl.DataFrame()</rewrite_this>
+</document>
+
+Only make changes that are necessary to fulfill the prompt, leave everything else as-is. All surrounding content will be preserved.
+Start at the indentation level in the original file in the rewritten content. Don't stop until you've rewritten the entire section, even if you have no more changes to make, always write out the whole section with no unnecessary elisions.
+Immediately start with the following format with no remarks:
+
+```
+{REWRITTEN_CODE}
+```
+
+And here's the section to rewrite based on that prompt again for reference:
+
+<rewrite_this>
+pl.DataFrame()
+</rewrite_this>
+
+## Rules for python
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+<code_from_other_cells>
+import pandas as pd
+import numpy as np
+</code_from_other_cells>
+
+==================== with VariableContext objects ====================
+
+You are an AI assistant integrated into the marimo notebook code editor.
+You goal is to create a new cell in the notebook.
+Your output must be valid python code.
+You can use the provided context to help you write the new cell.
+You can reference variables from other cells, but you cannot redefine a variable if it already exists.
+Immediately start with the following format with no remarks.
+
+```
+{CELL_CODE}
+```
+
+## Rules for python
+1. For matplotlib: use plt.gca() as the last expression instead of plt.show().
+2. For plotly: return the figure object directly.
+3. For altair: return the chart object directly. Add tooltips where appropriate.
+4. Include proper labels, titles, and color schemes.
+5. Make visualizations interactive where appropriate.
+6. If an import already exists, do not import it again.
+7. If a variable is already defined, use another name, or make it private by adding an underscore at the beginning.
+
+## Available variables from other cells:
+- variable: `df`
+ - value_type: DataFrame
+ - value_preview: <DataFrame with 100 rows and 5 columns>
+- variable: `model`
+ - value_type: Model
+ - value_preview: <Model object>
diff --git a/tests/_server/ai/snapshots/user_prompts.txt b/tests/_server/ai/snapshots/user_prompts.txt
deleted file mode 100644
index a1030c79f1..0000000000
--- a/tests/_server/ai/snapshots/user_prompts.txt
+++ /dev/null
@@ -1,47 +0,0 @@
-
-
-==================== no code ====================
-
-Create a pandas dataframe
-
-==================== with code ====================
-
-Create a pandas dataframe
-
-<current-code>
-df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
-</current-code>
-
-==================== with code and other code ====================
-
-Create a pandas dataframe
-
-<code-from-other-cells>
-import pandas as pd
-import numpy as np
-</code-from-other-cells>
-
-<current-code>
-df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
-</current-code>
-
-==================== with just other code ====================
-
-Create a pandas dataframe
-
-<code-from-other-cells>
-import pandas as pd
-import numpy as np
-</code-from-other-cells>
-
-==================== with context ====================
-
-Create a pandas dataframe
-
-<code-from-other-cells>
-import marimo as mo
-</code-from-other-cells>
-
-<current-code>
-import pandas as pd
-</current-code>
\ No newline at end of file
diff --git a/tests/_server/ai/test_prompts.py b/tests/_server/ai/test_prompts.py
index d7eab90bec..1b7fe7c932 100644
--- a/tests/_server/ai/test_prompts.py
+++ b/tests/_server/ai/test_prompts.py
@@ -4,11 +4,18 @@ from __future__ import annotations
from typing import cast
from marimo._ast.visitor import Language
-from marimo._server.ai.prompts import Prompter
+from marimo._server.ai.prompts import (
+ FILL_ME_TAG,
+ _format_variables,
+ get_chat_system_prompt,
+ get_inline_system_prompt,
+ get_refactor_or_insert_notebook_cell_system_prompt,
+)
from marimo._server.models.completion import (
AiCompletionContext,
SchemaColumn,
SchemaTable,
+ VariableContext,
)
from tests.mocks import snapshotter
@@ -23,15 +30,29 @@ def test_system_prompts():
result = ""
for language in ("python", "markdown", "sql", "idk"):
result += _header(language)
- result += Prompter.get_system_prompt(language=cast(Language, language))
+ result += get_refactor_or_insert_notebook_cell_system_prompt(
+ language=cast(Language, language),
+ is_insert=False,
+ custom_rules=None,
+ cell_code=None,
+ selected_text=None,
+ other_cell_codes=None,
+ context=None,
+ )
result += _header("with custom rules")
- result += Prompter.get_system_prompt(
- language="python", custom_rules="Always use type hints."
+ result += get_refactor_or_insert_notebook_cell_system_prompt(
+ language="python",
+ is_insert=False,
+ custom_rules="Always use type hints.",
+ cell_code=None,
+ selected_text=None,
+ other_cell_codes=None,
+ context=None,
)
result += _header("with context")
- result += Prompter.get_system_prompt(
+ result += get_refactor_or_insert_notebook_cell_system_prompt(
language="python",
context=AiCompletionContext(
schema=[
@@ -50,93 +71,162 @@ def test_system_prompts():
)
]
),
+ is_insert=False,
+ custom_rules=None,
+ cell_code=None,
+ selected_text=None,
+ other_cell_codes=None,
)
- snapshot("system_prompts.txt", result)
-
-
-def test_empty_rules():
- assert Prompter.get_system_prompt(
- language="python"
- ) == Prompter.get_system_prompt(
+ # New test cases for get_refactor_or_insert_notebook_cell_system_prompt
+ result += _header("with is_insert=True")
+ result += get_refactor_or_insert_notebook_cell_system_prompt(
language="python",
- custom_rules=" ",
+ is_insert=True,
+ custom_rules=None,
+ cell_code="def fib(n):\n <insert_here></insert_here>",
+ selected_text=None,
+ other_cell_codes=None,
+ context=None,
)
-
-def test_user_prompts():
- prompt = "Create a pandas dataframe"
-
- result: str = ""
- result += _header("no code")
- result += Prompter(code="").get_prompt(
- user_prompt=prompt, include_other_code=""
+ result += _header("with cell_code")
+ result += get_refactor_or_insert_notebook_cell_system_prompt(
+ language="python",
+ is_insert=False,
+ custom_rules=None,
+ cell_code="def hello():\n <rewrite_this>print('Hello, world!')</rewrite_this>",
+ selected_text="print('Hello, world!')",
+ other_cell_codes=None,
+ context=None,
)
- result += _header("with code")
- result += Prompter(
- code="df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})",
- ).get_prompt(user_prompt=prompt, include_other_code="")
-
- result += _header("with code and other code")
- result += Prompter(
- code="df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})",
- ).get_prompt(
- user_prompt=prompt,
- include_other_code="import pandas as pd\nimport numpy as np\n",
+ result += _header("with selected_text")
+ result += get_refactor_or_insert_notebook_cell_system_prompt(
+ language="python",
+ is_insert=False,
+ custom_rules=None,
+ cell_code="def hello():\n <rewrite_this>print('Hello, world!')</rewrite_this>",
+ selected_text="print('Hello, world!')",
+ other_cell_codes=None,
+ context=None,
)
- result += _header("with just other code")
- result += Prompter(
- code="",
- ).get_prompt(
- user_prompt=prompt,
- include_other_code="import pandas as pd\nimport numpy as np\n",
+ result += _header("with other_cell_codes")
+ result += get_refactor_or_insert_notebook_cell_system_prompt(
+ language="python",
+ is_insert=False,
+ custom_rules=None,
+ cell_code="<rewrite_this>pl.DataFrame()</rewrite_this>",
+ selected_text="pl.DataFrame()",
+ other_cell_codes="import pandas as pd\nimport numpy as np",
+ context=None,
)
- result += _header("with context")
- result += Prompter(code="import pandas as pd").get_prompt(
- user_prompt=prompt, include_other_code="import marimo as mo"
+ result += _header("with VariableContext objects")
+ result += get_refactor_or_insert_notebook_cell_system_prompt(
+ language="python",
+ is_insert=False,
+ custom_rules=None,
+ cell_code=None,
+ selected_text=None,
+ other_cell_codes=None,
+ context=AiCompletionContext(
+ variables=[
+ VariableContext(
+ name="df",
+ value_type="DataFrame",
+ preview_value="<DataFrame with 100 rows and 5 columns>",
+ ),
+ VariableContext(
+ name="model",
+ value_type="Model",
+ preview_value="<Model object>",
+ ),
+ ]
+ ),
)
- snapshot("user_prompts.txt", result)
-
-
-def test_edit_inline_prompts():
- # Nothing fancy here, just making sure
- # that if we already give a fully formatted prompt without
- # any code, we don't add any more instructions
- prompt = """
- Given the following code context, {opts.prompt}
-
- SELECTED CODE:
- {opts.selection}
+ snapshot("system_prompts.txt", result)
- Instructions:
- 1. Modify ONLY the selected code`;
- """
- result = Prompter(code="").get_prompt(
- user_prompt=prompt,
- include_other_code="",
+def test_empty_rules():
+ assert get_refactor_or_insert_notebook_cell_system_prompt(
+ language="python",
+ is_insert=False,
+ custom_rules=None,
+ cell_code=None,
+ selected_text=None,
+ other_cell_codes=None,
+ context=None,
+ ) == get_refactor_or_insert_notebook_cell_system_prompt(
+ language="python",
+ is_insert=False,
+ custom_rules=" ",
+ cell_code=None,
+ selected_text=None,
+ other_cell_codes=None,
+ context=None,
)
- assert result == prompt
+
+def test_edit_inline_prompts():
+ result = get_inline_system_prompt(language="python")
+ snapshot("edit_inline_prompts.txt", result)
+ # <FILL_ME> is sent from the client, this cannot change without
+ # coordination
+ assert FILL_ME_TAG in result
def test_chat_system_prompts():
result: str = ""
result += _header("no custom rules")
- result += Prompter.get_chat_system_prompt()
+ result += get_chat_system_prompt(
+ custom_rules=None,
+ include_other_code="",
+ context=None,
+ )
result += _header("with custom rules")
- result += Prompter.get_chat_system_prompt(custom_rules="Always be polite.")
+ result += get_chat_system_prompt(
+ custom_rules="Always be polite.",
+ include_other_code="",
+ context=None,
+ )
result += _header("with variables")
- result += Prompter.get_chat_system_prompt(variables=["var1", "var2"])
+ result += get_chat_system_prompt(
+ custom_rules=None,
+ include_other_code="",
+ context=AiCompletionContext(
+ variables=["var1", "var2"],
+ ),
+ )
+
+ result += _header("with VariableContext objects")
+ result += get_chat_system_prompt(
+ custom_rules=None,
+ include_other_code="",
+ context=AiCompletionContext(
+ variables=[
+ VariableContext(
+ name="df",
+ value_type="DataFrame",
+ preview_value="<DataFrame with 100 rows and 5 columns>",
+ ),
+ VariableContext(
+ name="model",
+ value_type="Model",
+ preview_value="<Model object>",
+ ),
+ ]
+ ),
+ )
result += _header("with context")
- result += Prompter.get_chat_system_prompt(
+ result += get_chat_system_prompt(
+ custom_rules=None,
+ include_other_code="",
context=AiCompletionContext(
schema=[
SchemaTable(
@@ -164,20 +254,22 @@ def test_chat_system_prompts():
],
),
],
- )
+ ),
)
result += _header("with other code")
- result += Prompter.get_chat_system_prompt(
- include_other_code="import pandas as pd\nimport numpy as np\n"
+ result += get_chat_system_prompt(
+ custom_rules=None,
+ include_other_code="import pandas as pd\nimport numpy as np\n",
+ context=None,
)
result += _header("kitchen sink")
- result += Prompter.get_chat_system_prompt(
+ result += get_chat_system_prompt(
custom_rules="Always be polite.",
- variables=["var1", "var2"],
include_other_code="import pandas as pd\nimport numpy as np\n",
context=AiCompletionContext(
+ variables=["var1", "var2"],
schema=[
SchemaTable(
name="df_1",
@@ -197,3 +289,53 @@ def test_chat_system_prompts():
)
snapshot("chat_system_prompts.txt", result)
+
+
+def test_format_variables():
+ """Test the _format_variables function."""
+ # Test empty variables
+ assert _format_variables(None) == ""
+ assert _format_variables([]) == ""
+
+ variables = [
+ "var1",
+ VariableContext(
+ name="df",
+ value_type="DataFrame",
+ preview_value="<DataFrame with 100 rows and 5 columns>",
+ ),
+ "var2",
+ ]
+ expected = (
+ "\n\n## Available variables from other cells:\n"
+ "- variable: `var1`"
+ "- variable: `df`\n"
+ " - value_type: DataFrame\n"
+ " - value_preview: <DataFrame with 100 rows and 5 columns>\n"
+ "- variable: `var2`"
+ )
+ assert _format_variables(variables) == expected
+
+ # Test private variables
+ variables = [
+ "var1",
+ "_private_var",
+ VariableContext(
+ name="df",
+ value_type="DataFrame",
+ preview_value="<DataFrame with 100 rows and 5 columns>",
+ ),
+ VariableContext(
+ name="_private_df",
+ value_type="DataFrame",
+ preview_value="<Private DataFrame>",
+ ),
+ ]
+ expected = (
+ "\n\n## Available variables from other cells:\n"
+ "- variable: `var1`"
+ "- variable: `df`\n"
+ " - value_type: DataFrame\n"
+ " - value_preview: <DataFrame with 100 rows and 5 columns>\n"
+ )
+ assert _format_variables(variables) == expected
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index b3cb862fc1..79e6e10b08 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -11,7 +11,11 @@ import pytest
from marimo._config.manager import UserConfigManager
from marimo._dependencies.dependencies import DependencyManager
-from marimo._server.ai.providers import OpenAIProvider
+from marimo._server.ai.prompts import FILL_ME_TAG
+from marimo._server.ai.providers import (
+ OpenAIProvider,
+ without_wrapping_backticks,
+)
from tests._server.conftest import get_session_config_manager
from tests._server.mocks import token_header, with_session
@@ -145,7 +149,7 @@ class TestOpenAiEndpoints:
headers=HEADERS,
json={
"prompt": "Help me create a dataframe",
- "code": "import pandas as pd",
+ "code": "<rewrite_this>import pandas as pd</rewrite_this>",
"include_other_code": "",
},
)
@@ -154,9 +158,7 @@ class TestOpenAiEndpoints:
prompt = oaiclient.chat.completions.create.call_args.kwargs[
"messages"
][1]["content"]
- assert prompt == (
- "Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>"
- )
+ assert prompt == "Help me create a dataframe"
@staticmethod
@with_session(SESSION_ID)
@@ -181,7 +183,7 @@ class TestOpenAiEndpoints:
headers=HEADERS,
json={
"prompt": "Help me create a dataframe",
- "code": "import pandas as pd",
+ "code": "<rewrite_this>import pandas as pd</rewrite_this>",
"include_other_code": "",
},
)
@@ -213,7 +215,7 @@ class TestOpenAiEndpoints:
headers=HEADERS,
json={
"prompt": "Help me create a dataframe",
- "code": "import pandas as pd",
+ "code": "<rewrite_this>import pandas as pd</rewrite_this>",
"include_other_code": "",
},
)
@@ -255,7 +257,7 @@ class TestOpenAiEndpoints:
prompt = oaiclient.chat.completions.create.call_args.kwargs[
"messages"
][1]["content"]
- assert prompt == "import pandas as pd\n<FILL_ME>\ndf.head()"
+ assert prompt == f"import pandas as pd\n{FILL_ME_TAG}\ndf.head()"
# Assert the system prompt includes language-specific instructions
system_prompt = oaiclient.chat.completions.create.call_args.kwargs[
"messages"
@@ -374,7 +376,7 @@ class TestAnthropicAiEndpoints:
headers=HEADERS,
json={
"prompt": "Help me create a dataframe",
- "code": "import pandas as pd",
+ "code": "<rewrite_this>import pandas as pd</rewrite_this>",
"include_other_code": "",
},
)
@@ -383,9 +385,7 @@ class TestAnthropicAiEndpoints:
prompt: str = anthropic_client.messages.create.call_args.kwargs[
"messages"
][0]["content"]
- assert prompt == (
- "Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>"
- )
+ assert prompt == "Help me create a dataframe"
# Assert the model it was called with
model = anthropic_client.messages.create.call_args.kwargs["model"]
assert model == "claude-3.5"
@@ -420,7 +420,7 @@ class TestAnthropicAiEndpoints:
prompt: str = anthropic_client.messages.create.call_args.kwargs[
"messages"
][0]["content"]
- assert prompt == "import pandas as pd\n<FILL_ME>\ndf.head()"
+ assert prompt == f"import pandas as pd\n{FILL_ME_TAG}\ndf.head()"
# Assert the model it was called with
model = anthropic_client.messages.create.call_args.kwargs["model"]
assert model == "claude-3.5-for-inline-completion"
@@ -451,7 +451,7 @@ class TestGoogleAiEndpoints:
headers=HEADERS,
json={
"prompt": "Help me create a dataframe",
- "code": "import pandas as pd",
+ "code": "<rewrite_this>import pandas as pd</rewrite_this>",
"include_other_code": "",
},
)
@@ -460,9 +460,7 @@ class TestGoogleAiEndpoints:
prompt = google_client.generate_content.call_args.kwargs[
"contents"
]
- assert prompt[0]["parts"][0] == (
- "Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>"
- )
+ assert prompt[0]["parts"][0] == "Help me create a dataframe"
@staticmethod
@with_session(SESSION_ID)
@@ -520,7 +518,7 @@ class TestGoogleAiEndpoints:
]
assert (
prompt[0]["parts"][0]
- == "import pandas as pd\n<FILL_ME>\ndf.head()"
+ == f"import pandas as pd\n{FILL_ME_TAG}\ndf.head()"
)
@@ -693,92 +691,6 @@ def no_google_ai_config(config: UserConfigManager):
config.save_config(prev_config)
-class TestStreamResponse(unittest.TestCase):
- def simulate_stream(self, contents: list[str]) -> Any:
- @dataclass
- class MockContent:
- content: str
-
- class MockDelta:
- def __init__(self, content: str) -> None:
- self.delta = MockContent(content)
-
- class MockChunk:
- def __init__(self, content: str) -> None:
- self.choices = [MockDelta(content)]
-
- for content in contents:
- yield MockChunk(content)
-
- def test_no_code_fence(self):
- provider = OpenAIProvider(model="gpt-4o", config={})
- response = self.simulate_stream(["Hello, world!"])
- result = list(provider.make_stream_response(response))
- assert result == ["Hello, world!"]
-
- def test_single_complete_code_fence(self):
- provider = OpenAIProvider(model="gpt-4o", config={})
- response = self.simulate_stream(
- ["```python\nprint('Hello, world!')\n```"]
- )
- result = list(provider.make_stream_response(response))
- assert result == ["print('Hello, world!')\n"]
-
- def test_code_fence_across_chunks(self):
- provider = OpenAIProvider(model="gpt-4o", config={})
- response = self.simulate_stream(
- [
- "```python\nprint('Hello,",
- " world!')\n```",
- ]
- )
- result = list(provider.make_stream_response(response))
- assert result == [
- "print('Hello,",
- " world!')\n",
- ]
-
- def test_code_fence_across_more_chunks(self):
- provider = OpenAIProvider(model="gpt-4o", config={})
- response = self.simulate_stream(
- [
- "```",
- "python",
- "\nprint('Hello,",
- " world!')\n",
- "```",
- ]
- )
- result = list(provider.make_stream_response(response))
- assert result == ["print('Hello,", " world!')\n", ""]
-
- def test_multiple_code_fences(self):
- response = self.simulate_stream(
- [
- "```python\nprint('Hello',",
- " 'world!')\n```",
- "No code here",
- "```sql\nSELECT * FROM users;\n```",
- ]
- )
- provider = OpenAIProvider(model="gpt-4o", config={})
- result = list(provider.make_stream_response(response))
- assert result == [
- "print('Hello',",
- " 'world!')\n",
- "No code here",
- "SELECT * FROM users;\n",
- ]
-
- def test_nested_code_fences(self):
- response = self.simulate_stream(
- ["```python\nprint('```nested```')\n```"]
- )
- provider = OpenAIProvider(model="gpt-4o", config={})
- result = list(provider.make_stream_response(response))
- assert result == ["print('```nested```')\n"]
-
-
@with_session(SESSION_ID)
def test_chat_without_code(client: TestClient) -> None:
user_config_manager = get_session_config_manager(client)
@@ -886,3 +798,50 @@ class TestGetContent(unittest.TestCase):
# Assert that the result is the expected content
assert result == "Test content"
+
+
+ ("chunks", "expected"),
+ [
+ (["Hello", " world", "!"], "Hello world!"),
+ (
+ ["```", "print('hello')", "print('world')"],
+ "print('hello')print('world')",
+ ),
+ (
+ ["print('hello')", "print('world')", "```"],
+ "print('hello')print('world')```",
+ ),
+ (
+ ["```", "print('hello')", "```"],
+ "print('hello')",
+ ),
+ (["Hello", " ``` ", "world"], "Hello ``` world"),
+ (
+ ["``", "`print('hello')", "``", "`"],
+ "print('hello')",
+ ),
+ (
+ ["``", "`", "\n", "print('hello')", "\n", "``", "`"],
+ "print('hello')\n",
+ ),
+ (
+ ["```\n", "print('hello')", "print('world')", "\n```"],
+ "print('hello')print('world')",
+ ),
+ (
+ ["```\nprint('hello')\n", "print('world')\n```"],
+ "print('hello')\nprint('world')",
+ ),
+ (
+ ["```\n", "def test():\n ", "return True\n```"],
+ "def test():\n return True",
+ ),
+ ([], ""),
+ (["```idk```"], "idk"),
+ (["Hello world"], "Hello world"),
+ ],
+)
+def test_without_wrapping_backticks(chunks: list[str], expected: str) -> None:
+ result = list(without_wrapping_backticks(iter(chunks)))
+ assert "".join(result) == expected