A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: custom ai assist rules (#2591)
Myles Scolnick214c4997ed47
diff --git a/docs/guides/editor_features/ai_completion.md b/docs/guides/editor_features/ai_completion.mdindex 0bee37da68..f9ed08b04a 100644--- a/docs/guides/editor_features/ai_completion.md+++ b/docs/guides/editor_features/ai_completion.md@@ -132,16 +132,16 @@ Gemma 2) on your local machine. To integrate Ollama with marimo:1. Download and install [Ollama](https://ollama.com/).2. Download the model you want to use:- 1. `ollama pull llama2`- 2. We also recommend `codellama` (code specific) or `llama3.1` (more advanced, but larger).-3. Start the Ollama server: `ollama run llama2`+ 1. `ollama pull llama3.1`+ 2. We also recommend `codellama` (code specific).+3. Start the Ollama server: `ollama run llama3.1`4. Visit <http://localhost:11434> to confirm that the server is running.5. Add the following to your `marimo.toml`:```toml[ai.open_ai]api_key = "ollama" # This is not used, but required-model = "llama2" # or the model you downloaded from above+model = "llama3.1" # or the model you downloaded from abovebase_url = "http://localhost:11434/v1"```diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 81b60c75f6..9dc8935d9a 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -43,6 +43,7 @@ import {} from "lucide-react";import { cn } from "@/utils/cn";import { KNOWN_AI_MODELS } from "./constants";+import { Textarea } from "../ui/textarea";const formItemClasses = "flex flex-row items-center space-x-1 space-y-0";@@ -691,6 +692,175 @@ export const UserConfigForm: React.FC = () => {case "ai":return (<>+ <SettingGroup title="AI Code Completion">+ <p className="text-sm text-muted-secondary">+ You may use GitHub Copilot or Codeium for AI code completion.+ </p>++ <FormField+ control={form.control}+ name="completion.copilot"+ render={({ field }) => (+ <div className="flex flex-col space-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel>Provider</FormLabel>+ <FormControl>+ <NativeSelect+ data-testid="copilot-select"+ onChange={(e) => {+ if (e.target.value === "none") {+ field.onChange(false);+ } else {+ field.onChange(e.target.value);+ }+ }}+ value={+ field.value === true+ ? "github"+ : field.value === false+ ? "none"+ : field.value+ }+ disabled={field.disabled}+ className="inline-flex mr-2"+ >+ {["none", "github", "codeium"].map((option) => (+ <option value={option} key={option}>+ {option}+ </option>+ ))}+ </NativeSelect>+ </FormControl>+ <FormMessage />+ </FormItem>+ </div>+ )}+ />++ {renderCopilotProvider()}+ </SettingGroup>+ <SettingGroup title="AI Keys">+ <FormField+ control={form.control}+ name="ai.open_ai.api_key"+ render={({ field }) => (+ <div className="flex flex-col space-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel>OpenAI API Key</FormLabel>+ <FormControl>+ <Input+ data-testid="ai-openai-api-key-input"+ className="m-0 inline-flex"+ placeholder="sk-proj..."+ {...field}+ onChange={(e) => {+ const value = e.target.value;+ // Don't allow *+ if (!value.includes("*")) {+ field.onChange(value);+ }+ }}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ <FormDescription>+ Your OpenAI API key from{" "}+ <a+ className="text-link hover:underline"+ href="https://platform.openai.com/account/api-keys"+ target="_blank"+ rel="noreferrer"+ >+ platform.openai.com+ </a>+ .+ </FormDescription>+ </div>+ )}+ />++ <FormField+ control={form.control}+ name="ai.anthropic.api_key"+ render={({ field }) => (+ <div className="flex flex-col space-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel>Anthropic API Key</FormLabel>+ <FormControl>+ <Input+ data-testid="ai-anthropic-api-key-input"+ className="m-0 inline-flex"+ placeholder="sk-ant..."+ {...field}+ onChange={(e) => {+ const value = e.target.value;+ // Don't allow *+ if (!value.includes("*")) {+ field.onChange(value);+ }+ }}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ <FormDescription>+ Your Anthropic API key from{" "}+ <a+ className="text-link hover:underline"+ href="https://console.anthropic.com/settings/keys"+ target="_blank"+ rel="noreferrer"+ >+ console.anthropic.com+ </a>+ .+ </FormDescription>+ </div>+ )}+ />++ <FormField+ control={form.control}+ name="ai.google.api_key"+ render={({ field }) => (+ <div className="flex flex-col space-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel>Google AI API Key</FormLabel>+ <FormControl>+ <Input+ data-testid="ai-google-api-key-input"+ className="m-0 inline-flex"+ placeholder="AI..."+ {...field}+ onChange={(e) => {+ const value = e.target.value;+ // Don't allow *+ if (!value.includes("*")) {+ field.onChange(value);+ }+ }}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ <FormDescription>+ Your Google AI API key from{" "}+ <a+ className="text-link hover:underline"+ href="https://aistudio.google.com/app/apikey"+ target="_blank"+ rel="noreferrer"+ >+ aistudio.google.com+ </a>+ .+ </FormDescription>+ </div>+ )}+ />+ </SettingGroup>+<SettingGroup title="AI Assist"><p className="text-sm text-muted-secondary">Add an API key to <Kbd className="inline">marimo.toml</Kbd> to@@ -764,174 +934,31 @@ export const UserConfigForm: React.FC = () => {</div>)}/>- <SettingGroup title="AI Keys">- <FormField- control={form.control}- name="ai.open_ai.api_key"- render={({ field }) => (- <div className="flex flex-col space-y-1">- <FormItem className={formItemClasses}>- <FormLabel>OpenAI API Key</FormLabel>- <FormControl>- <Input- data-testid="ai-openai-api-key-input"- className="m-0 inline-flex"- placeholder="sk-proj..."- {...field}- onChange={(e) => {- const value = e.target.value;- // Don't allow *- if (!value.includes("*")) {- field.onChange(value);- }- }}- />- </FormControl>- <FormMessage />- </FormItem>- <FormDescription>- Your OpenAI API key from{" "}- <a- className="text-link hover:underline"- href="https://platform.openai.com/account/api-keys"- target="_blank"- rel="noreferrer"- >- platform.openai.com- </a>- .- </FormDescription>- </div>- )}- />-- <FormField- control={form.control}- name="ai.anthropic.api_key"- render={({ field }) => (- <div className="flex flex-col space-y-1">- <FormItem className={formItemClasses}>- <FormLabel>Anthropic API Key</FormLabel>- <FormControl>- <Input- data-testid="ai-anthropic-api-key-input"- className="m-0 inline-flex"- placeholder="sk-ant..."- {...field}- onChange={(e) => {- const value = e.target.value;- // Don't allow *- if (!value.includes("*")) {- field.onChange(value);- }- }}- />- </FormControl>- <FormMessage />- </FormItem>- <FormDescription>- Your Anthropic API key from{" "}- <a- className="text-link hover:underline"- href="https://console.anthropic.com/settings/keys"- target="_blank"- rel="noreferrer"- >- console.anthropic.com- </a>- .- </FormDescription>- </div>- )}- />-- <FormField- control={form.control}- name="ai.google.api_key"- render={({ field }) => (- <div className="flex flex-col space-y-1">- <FormItem className={formItemClasses}>- <FormLabel>Google AI API Key</FormLabel>- <FormControl>- <Input- data-testid="ai-google-api-key-input"- className="m-0 inline-flex"- placeholder="AI..."- {...field}- onChange={(e) => {- const value = e.target.value;- // Don't allow *- if (!value.includes("*")) {- field.onChange(value);- }- }}- />- </FormControl>- <FormMessage />- </FormItem>- <FormDescription>- Your Google AI API key from{" "}- <a- className="text-link hover:underline"- href="https://aistudio.google.com/app/apikey"- target="_blank"- rel="noreferrer"- >- aistudio.google.com- </a>- .- </FormDescription>- </div>- )}- />- </SettingGroup>- </SettingGroup>- <SettingGroup title="AI Code Completion">- <p className="text-sm text-muted-secondary">- You may use GitHub Copilot or Codeium for AI code completion.- </p><FormFieldcontrol={form.control}- name="completion.copilot"+ name="ai.rules"render={({ field }) => (- <div className="flex flex-col space-y-1">- <FormItem className={formItemClasses}>- <FormLabel>Provider</FormLabel>+ <div className="flex flex-col">+ <FormItem>+ <FormLabel>Custom Rules</FormLabel><FormControl>- <NativeSelect- data-testid="copilot-select"- onChange={(e) => {- if (e.target.value === "none") {- field.onChange(false);- } else {- field.onChange(e.target.value);- }- }}- value={- field.value === true- ? "github"- : field.value === false- ? "none"- : field.value- }- disabled={field.disabled}- className="inline-flex mr-2"- >- {["none", "github", "codeium"].map((option) => (- <option value={option} key={option}>- {option}- </option>- ))}- </NativeSelect>+ <Textarea+ data-testid="ai-rules-input"+ className="m-0 inline-flex w-full h-32 p-2 text-sm"+ placeholder="e.g. Always use type hints; prefer polars over pandas"+ {...field}+ value={field.value}+ /></FormControl><FormMessage /></FormItem>+ <FormDescription>+ Custom rules to include in all AI completion prompts.+ </FormDescription></div>)}/>-- {renderCopilotProvider()}</SettingGroup></>);diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsxindex b081439219..55b483f07c 100644--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx@@ -334,7 +334,7 @@ export const PromptInput = ({return (<ReactCodeMirrorref={inputRef}- className="flex-1 font-sans"+ className="flex-1 font-sans overflow-auto my-1"autoFocus={true}width="100%"value={value}diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsxindex 5477061009..ebad86b6d4 100644--- a/frontend/src/components/editor/ai/ai-completion-editor.tsx+++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx@@ -116,9 +116,9 @@ export const AiCompletionEditor: React.FC<Props> = ({<div className="flex flex-col w-full rounded-[inherit] overflow-hidden"><divclassName={cn(- "flex items-center gap-2 border-b px-3 transition-[height] rounded-[inherit] rounded-b-none duration-300 overflow-hidden",- enabled && "min-h-10 visible",- !enabled && "h-0 invisible",+ "flex items-center gap-2 border-b px-3 transition-all rounded-[inherit] rounded-b-none duration-300 overflow-hidden",+ enabled && "max-h-[400px] min-h-11 visible",+ !enabled && "max-h-0 min-h-0 invisible",)}>{enabled && (diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex 6bff4bcebf..8b2cf04805 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -30,7 +30,9 @@ test("default UserConfig - empty", () => {const defaultConfig = UserConfigSchema.parse({});expect(defaultConfig).toMatchInlineSnapshot(`{- "ai": {},+ "ai": {+ "rules": "",+ },"completion": {"activate_on_typing": true,"copilot": false,@@ -80,7 +82,9 @@ test("default UserConfig - one level", () => {});expect(defaultConfig).toMatchInlineSnapshot(`{- "ai": {},+ "ai": {+ "rules": "",+ },"completion": {"activate_on_typing": true,"copilot": false,diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 65d53191e1..5a43382990 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -99,6 +99,7 @@ export const UserConfigSchema = z.default({ manager: "pip" }),ai: z.object({+ rules: z.string().default(""),open_ai: z.object({api_key: z.string().optional(),@@ -141,6 +142,7 @@ export const UserConfigSchema = zexperimental: {},server: {},ai: {+ rules: "",open_ai: {},},});diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 2d441a57ab..acd28800f0 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -172,11 +172,13 @@ class AiConfig(TypedDict, total=False):**Keys.**+ - `rules`: custom rules to include in all AI completion prompts- `open_ai`: the OpenAI config- `anthropic`: the Anthropic config- `google`: the Google AI config"""+ rules: NotRequired[str]open_ai: OpenAiConfiganthropic: AnthropicConfiggoogle: GoogleAiConfigdiff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.pyindex d40f730726..d90b82d33e 100644--- a/marimo/_server/ai/prompts.py+++ b/marimo/_server/ai/prompts.py@@ -18,7 +18,9 @@ class Prompter:self.context = context@staticmethod- def get_system_prompt(language: Language) -> str:+ def get_system_prompt(+ language: Language, custom_rules: Optional[str] = None+ ) -> str:language_rules = {"python": ["You can only output python code.",@@ -40,10 +42,15 @@ class Prompter:f"{i+1}. {rule}"for i, rule in enumerate(language_rules[language]))- return (+ system_prompt = (f"You are a helpful assistant that can answer questions about {language}." # noqa: E501f" Here are your rules: \n{rules}")++ if custom_rules and custom_rules.strip():+ system_prompt += f"\n\nAdditional rules:\n{custom_rules}"++ return system_promptelse:return "You are a helpful assistant that can answer questions."diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex dfe7bc9227..fb66d1eda5 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -277,9 +277,12 @@ async def ai_completion(app_state.require_current_session()config = app_state.config_manager.get_config(hide_secrets=False)body = await parse_request(request, cls=AiCompletionRequest)+ custom_rules = config.get("ai", {}).get("rules", None)prompter = Prompter(body.code, body.include_other_code, body.context)- system_prompt = Prompter.get_system_prompt(body.language)+ system_prompt = Prompter.get_system_prompt(+ body.language, custom_rules=custom_rules+ )prompt = prompter.get_prompt(body.prompt)model = get_model(config)diff --git a/openapi/api.yaml b/openapi/api.yamlindex 4d9dfe340d..a17078effa 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1054,6 +1054,8 @@ components:model:type: stringtype: object+ rules:+ type: stringtype: objectcompletion:properties:@@ -1909,7 +1911,7 @@ components:type: objectinfo:title: marimo API- version: 0.9.4+ version: 0.9.6openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex f942551f68..d443f559ea 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2401,6 +2401,7 @@ export interface components {base_url?: string;model?: string;};+ rules?: string;};completion: {activate_on_typing: boolean;diff --git a/tests/_server/ai/snapshots/system_prompts.txt b/tests/_server/ai/snapshots/system_prompts.txtindex abc8ed8ab9..ad4a699d18 100644--- a/tests/_server/ai/snapshots/system_prompts.txt+++ b/tests/_server/ai/snapshots/system_prompts.txt@@ -23,4 +23,17 @@ You are a helpful assistant that can answer questions about sql. Here are your r==================== idk ====================-You are a helpful assistant that can answer questions.\ No newline at end of file+You are a helpful assistant that can answer questions.++==================== with custom rules ====================++You are a helpful assistant that can answer questions about python. Here are your rules:+1. You can only output python code.+2. Do not describe the code, just write the code.+3. Do not output markdown or backticks.+4. When using matplotlib to show plots, use plt.gca() instead of plt.show().+5. If an import already exists, do not import it again.+6. 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.\ No newline at end of filediff --git a/tests/_server/ai/test_prompts.py b/tests/_server/ai/test_prompts.pyindex e5e062c4c7..ebf44a95e8 100644--- a/tests/_server/ai/test_prompts.py+++ b/tests/_server/ai/test_prompts.py@@ -25,9 +25,21 @@ def test_system_prompts():result += _header(language)result += Prompter.get_system_prompt(cast(Language, language))+ result += _header("with custom rules")+ result += Prompter.get_system_prompt(+ "python", custom_rules="Always use type hints."+ )+snapshot("system_prompts.txt", result)+def test_empty_rules():+ assert Prompter.get_system_prompt("python") == Prompter.get_system_prompt(+ "python",+ custom_rules=" ",+ )++def test_user_prompts():prompt = "Create a pandas dataframe"