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 fill-in-the-middle prompting (#6028)

Myles Scolnickaa839dc5b843
diff --git a/frontend/package.json b/frontend/package.json
index 827f2fcfb4..c4ccab1c41 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -48,7 +48,7 @@
"@lezer/lr": "^1.4.2",
"@lezer/markdown": "^1.4.3",
"@lezer/python": "^1.1.18",
- "@marimo-team/codemirror-ai": "^0.1.11",
+ "@marimo-team/codemirror-ai": "^0.3.1",
"@marimo-team/codemirror-languageserver": "^1.15.24",
"@marimo-team/codemirror-mcp": "^0.1.5",
"@marimo-team/llm-info": "workspace:*",
diff --git a/frontend/src/core/codemirror/copilot/__tests__/trim-utils.test.ts b/frontend/src/core/codemirror/copilot/__tests__/trim-utils.test.ts
new file mode 100644
index 0000000000..8e01345bcb
--- /dev/null
+++ b/frontend/src/core/codemirror/copilot/__tests__/trim-utils.test.ts
@@ -0,0 +1,291 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { trimAutocompleteResponse } from "../trim-utils";
+
+const trim = trimAutocompleteResponse;
+
+describe("trimAutocompleteResponse", () => {
+ it("should return the response unchanged when no prefix or suffix", () => {
+ expect(
+ trim({
+ response: "console.log('hello');",
+ prefix: "",
+ suffix: "",
+ }),
+ ).toBe("console.log('hello');");
+ });
+
+ it("should handle empty response", () => {
+ expect(
+ trim({
+ response: "",
+ prefix: "prefix",
+ suffix: "suffix",
+ }),
+ ).toBe("");
+ });
+
+ it("should handle null/undefined inputs gracefully", () => {
+ expect(
+ trim({
+ response: "",
+ prefix: "",
+ suffix: "",
+ }),
+ ).toBe("");
+ });
+
+ describe("basic prefix trimming", () => {
+ it("should trim exact prefix match", () => {
+ expect(
+ trim({
+ response: "const x = 42;",
+ prefix: "const x = ",
+ suffix: "",
+ }),
+ ).toBe("42;");
+ });
+
+ it("should not trim when prefix doesn't match", () => {
+ expect(
+ trim({
+ response: "const x = 42;",
+ prefix: "let x = ",
+ suffix: "",
+ }),
+ ).toBe("const x = 42;");
+ });
+
+ it("should handle empty prefix", () => {
+ expect(
+ trim({
+ response: "const x = 42;",
+ prefix: "",
+ suffix: "",
+ }),
+ ).toBe("const x = 42;");
+ });
+ });
+
+ describe("basic suffix trimming", () => {
+ it("should trim exact suffix match", () => {
+ expect(
+ trim({
+ response: "42 + 1",
+ prefix: "",
+ suffix: " + 1",
+ }),
+ ).toBe("42");
+ });
+
+ it("should not trim when suffix doesn't match", () => {
+ expect(
+ trim({
+ response: "42 + 1",
+ prefix: "",
+ suffix: " + 2",
+ }),
+ ).toBe("42 + 1");
+ });
+
+ it("should handle empty suffix", () => {
+ expect(
+ trim({
+ response: "const x = 42;",
+ prefix: "",
+ suffix: "",
+ }),
+ ).toBe("const x = 42;");
+ });
+ });
+
+ describe("combined prefix and suffix trimming", () => {
+ it("should trim both prefix and suffix", () => {
+ expect(
+ trim({
+ response: "def func(): print('hello') return",
+ prefix: "def func():",
+ suffix: " return",
+ }),
+ ).toBe(" print('hello')");
+ });
+
+ it("should handle overlapping prefix and suffix", () => {
+ expect(
+ trim({
+ response: "abcdefabc",
+ prefix: "abc",
+ suffix: "abc",
+ }),
+ ).toBe("def");
+ });
+ });
+
+ describe("multiple occurrences", () => {
+ it("should trim multiple consecutive prefixes", () => {
+ expect(
+ trim({
+ response: ">>>>>>hello",
+ prefix: ">>>",
+ suffix: "",
+ }),
+ ).toBe(">>>hello");
+ });
+
+ it("should trim multiple consecutive suffixes", () => {
+ expect(
+ trim({
+ response: "hello<<<<<<",
+ prefix: "",
+ suffix: "<<<",
+ }),
+ ).toBe("hello<<<");
+ });
+ });
+
+ describe("real-world scenarios", () => {
+ it("should handle multiline Python function completion", () => {
+ expect(
+ trim({
+ response:
+ "def calculate_sum(a, b):\n result = a + b\n return result",
+ prefix: "def calculate_sum(a, b):",
+ suffix: "\n return result",
+ }),
+ ).toBe("\n result = a + b");
+ });
+
+ it("should handle Python list comprehension", () => {
+ expect(
+ trim({
+ response: "1, 2, 3, 4, 5];",
+ prefix: "const items = [",
+ suffix: "];",
+ }),
+ ).toBe("1, 2, 3, 4, 5");
+ });
+
+ it("should handle HTML tag completion", () => {
+ expect(
+ trim({
+ response: " <p>Hello World</p></div>",
+ prefix: '<div class="container">',
+ suffix: "</div>",
+ }),
+ ).toBe(" <p>Hello World</p>");
+ });
+
+ it("should handle SQL query completion", () => {
+ expect(
+ trim({
+ response: " age > 18 AND status = 'active' ORDER BY id",
+ prefix: "SELECT * FROM users WHERE",
+ suffix: "ORDER BY id",
+ }),
+ ).toBe(" age > 18 AND status = 'active' ");
+ });
+
+ it("should handle markdown completion", () => {
+ expect(
+ trim({
+ response: "## Introduction\n\nThis is a sample",
+ prefix: "## ",
+ suffix: "",
+ }),
+ ).toBe("Introduction\n\nThis is a sample");
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle response that is exactly the prefix", () => {
+ expect(
+ trim({
+ response: "hello",
+ prefix: "hello",
+ suffix: "",
+ }),
+ ).toBe("");
+ });
+
+ it("should handle response that is exactly the suffix", () => {
+ expect(
+ trim({
+ response: "world",
+ prefix: "",
+ suffix: "world",
+ }),
+ ).toBe("");
+ });
+
+ it("should handle response that is exactly prefix + suffix", () => {
+ expect(
+ trim({
+ response: "helloworld",
+ prefix: "hello",
+ suffix: "world",
+ }),
+ ).toBe("");
+ });
+
+ it("should handle very long prefix/suffix", () => {
+ expect(
+ trim({
+ response: `${"a".repeat(1000)}middle${"b".repeat(1000)}`,
+ prefix: "a".repeat(1000),
+ suffix: "b".repeat(1000),
+ }),
+ ).toBe("middle");
+ });
+
+ it("should handle special characters in prefix/suffix", () => {
+ expect(
+ trim({
+ response: "function test() { /* comment */ return 42; /* end */ }",
+ prefix: "function test() { /* comment */",
+ suffix: "/* end */ }",
+ }),
+ ).toBe(" return 42; ");
+ });
+
+ it("should handle unicode characters", () => {
+ expect(
+ trim({
+ response: "const 🚀 = '🎉 Hello World! 🌟';",
+ prefix: "const 🚀 = ",
+ suffix: ";",
+ }),
+ ).toBe("'🎉 Hello World! 🌟'");
+ });
+
+ it("should handle newlines in prefix/suffix", () => {
+ expect(
+ trim({
+ response: "if (condition) {\n console.log('test');\n}",
+ prefix: "if (condition) {\n",
+ suffix: "\n}",
+ }),
+ ).toBe(" console.log('test');");
+ });
+
+ it("should handle cases where AI response doesn't include context", () => {
+ expect(
+ trim({
+ response: "42",
+ prefix: "const x = ",
+ suffix: ";",
+ }),
+ ).toBe("42");
+ });
+
+ it("should handle partial matches correctly (not trim them)", () => {
+ // Should not trim partial matches
+ expect(
+ trim({
+ response: "function test() hello world return x",
+ prefix: "function test() {",
+ suffix: "return x;",
+ }),
+ ).toBe("function test() hello world return x");
+ });
+ });
+});
diff --git a/frontend/src/core/codemirror/copilot/extension.ts b/frontend/src/core/codemirror/copilot/extension.ts
index f2200beff7..e2f3db1cda 100644
--- a/frontend/src/core/codemirror/copilot/extension.ts
+++ b/frontend/src/core/codemirror/copilot/extension.ts
@@ -32,13 +32,14 @@ import { isInVimMode } from "../utils";
import { COPILOT_FILENAME, copilotServer, getCopilotClient } from "./client";
import { getCodes } from "./getCodes";
import { isCopilotEnabled } from "./state";
+import { trimAutocompleteResponse } from "./trim-utils";
const copilotCompartment = new Compartment();
const logger = Logger.get("@github/copilot-language-server");
const commonInlineCompletionConfig = {
- delay: 500, // default is 500ms
+ delay: 300, // default is 500ms
includeKeymap: true,
events: {
// Only show suggestions when the editor is focused
@@ -78,11 +79,16 @@ export const copilotBundle = (config: CompletionConfig): Extension => {
extensions.push(
inlineCompletion({
...commonInlineCompletionConfig,
- fetchFn: async (state) => {
+ fetchFn: async (state, _abortSignal, view) => {
+ const currentPosition = state.selection.main.head;
if (!isCopilotEnabled()) {
return "";
}
+ if (!view.hasFocus) {
+ return "";
+ }
+
// If no text, don't fetch
if (state.doc.length === 0) {
return "";
@@ -96,6 +102,12 @@ export const copilotBundle = (config: CompletionConfig): Extension => {
const request = getCopilotRequest(state, allCode);
const response = await getCopilotClient().getCompletion(request);
+ // If we are at a new position, ignore the response
+ if (currentPosition !== view.state.selection.main.head) {
+ Logger.debug("ignoring response because of new position");
+ return "";
+ }
+
const suggestion = getSuggestion(response, request.position, state);
return suggestion;
},
@@ -107,12 +119,18 @@ export const copilotBundle = (config: CompletionConfig): Extension => {
extensions.push(
inlineCompletion({
...commonInlineCompletionConfig,
- fetchFn: async (state) => {
+ fetchFn: async (state, _abortSignal, view) => {
+ const currentPosition = state.selection.main.head;
+
if (state.doc.length === 0) {
return "";
}
// If not focused, don't fetch
+ if (!view.hasFocus) {
+ return "";
+ }
+
const prefix = state.doc.sliceString(0, state.selection.main.head);
const suffix = state.doc.sliceString(
state.selection.main.head,
@@ -130,14 +148,15 @@ export const copilotBundle = (config: CompletionConfig): Extension => {
{ prefix, suffix, language },
);
- // Sometimes the prefix might get included in the response, so we need to trim it
- if (prefix && res.startsWith(prefix)) {
- res = res.slice(prefix.length);
- }
- if (suffix && res.endsWith(suffix)) {
- res = res.slice(0, -suffix.length);
+ // If we are at a new position, ignore the response
+ if (currentPosition !== view.state.selection.main.head) {
+ Logger.debug("ignoring response because of new position");
+ return "";
}
+ // Sometimes the prefix might get included in the response, so we need to trim it
+ res = trimAutocompleteResponse({ response: res, prefix, suffix });
+
return res;
},
}),
diff --git a/frontend/src/core/codemirror/copilot/trim-utils.ts b/frontend/src/core/codemirror/copilot/trim-utils.ts
new file mode 100644
index 0000000000..81f659f5a7
--- /dev/null
+++ b/frontend/src/core/codemirror/copilot/trim-utils.ts
@@ -0,0 +1,33 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+/**
+ * Trims prefix and suffix from an AI completion response.
+ * Handles the basic case where AI might include the original context in the response.
+ */
+export function trimAutocompleteResponse({
+ response,
+ prefix,
+ suffix,
+}: {
+ response: string;
+ prefix: string;
+ suffix: string;
+}): string {
+ if (!response) {
+ return response;
+ }
+
+ let trimmed = response;
+
+ // Trim exact prefix match
+ if (prefix && trimmed.startsWith(prefix)) {
+ trimmed = trimmed.slice(prefix.length);
+ }
+
+ // Trim exact suffix match
+ if (suffix && trimmed.endsWith(suffix)) {
+ trimmed = trimmed.slice(0, -suffix.length);
+ }
+
+ return trimmed;
+}
diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.ts
index db1809917f..2ff98e097f 100644
--- a/frontend/src/core/network/api.ts
+++ b/frontend/src/core/network/api.ts
@@ -25,6 +25,7 @@ export const API = {
opts: {
headers?: Record<string, string>;
baseUrl?: string;
+ signal?: AbortSignal;
} = {},
): Promise<RESP> {
const baseUrl = Strings.withTrailingSlash(
@@ -39,6 +40,7 @@ export const API = {
...opts.headers,
},
body: JSON.stringify(body),
+ signal: opts.signal,
})
.then(async (response) => {
const isJson = response.headers
diff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.py
index 66d6afba0d..47b90b84c5 100644
--- a/marimo/_server/ai/prompts.py
+++ b/marimo/_server/ai/prompts.py
@@ -11,7 +11,9 @@ from marimo._server.models.completion import (
VariableContext,
)
-FILL_ME_TAG = "<FILL_ME>"
+FIM_PREFIX_TAG = "<|fim_prefix|>"
+FIM_SUFFIX_TAG = "<|fim_suffix|>"
+FIM_MIDDLE_TAG = "<|fim_middle|>"
language_rules = {
"python": [
@@ -163,8 +165,9 @@ def get_refactor_or_insert_notebook_cell_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."
+ f"You are a {language} code completion assistant. "
+ f"Complete the missing code between the prefix and suffix while maintaining proper syntax, style, and functionality."
+ f"Only output the code that goes after the {FIM_SUFFIX_TAG} part. Do not add any explanation or markdown."
)
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index 34066e4e27..4204f97187 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -23,7 +23,9 @@ from marimo._server.ai.config import (
get_max_tokens,
)
from marimo._server.ai.prompts import (
- FILL_ME_TAG,
+ FIM_MIDDLE_TAG,
+ FIM_PREFIX_TAG,
+ FIM_SUFFIX_TAG,
get_chat_system_prompt,
get_inline_system_prompt,
get_refactor_or_insert_notebook_cell_system_prompt,
@@ -216,7 +218,8 @@ async def ai_inline_completion(
body = await parse_request(
request, cls=AiInlineCompletionRequest, allow_unknown_keys=True
)
- prompt = f"{body.prefix}{FILL_ME_TAG}{body.suffix}"
+ # Use FIM (Fill-In-Middle) format for inline completion
+ prompt = f"{FIM_PREFIX_TAG}{body.prefix}{FIM_SUFFIX_TAG}{body.suffix}{FIM_MIDDLE_TAG}"
messages = [ChatMessage(role="user", content=prompt)]
system_prompt = get_inline_system_prompt(language=body.language)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a0aeb9dc4f..7024b93be3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -128,8 +128,8 @@ importers:
specifier: ^1.1.18
version: 1.1.18
'@marimo-team/codemirror-ai':
- specifier: ^0.1.11
- version: 0.1.11(@codemirror/[email protected])(@codemirror/[email protected])
+ specifier: ^0.3.1
+ version: 0.3.1(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/codemirror-languageserver':
specifier: ^1.15.24
version: 1.15.24(@codemirror/[email protected])(@codemirror/[email protected])
@@ -1791,8 +1791,8 @@ packages:
'@marijn/[email protected]':
resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==}
- '@marimo-team/[email protected]':
- resolution: {integrity: sha512-EGFdLmJP5i4fV0Mec0V48Wlav7bvzbC+GWPmOmYmX49v1LLo1ie1x4CcbcM4IC3baH8MP3AdGvzD/7fSXBoupg==}
+ '@marimo-team/[email protected]':
+ resolution: {integrity: sha512-mkDM9BVfVCVX9Plf8TsqX36zMLvgzN++dzAR//HF3BhGrT9IvUvcwkzFWHUeN7iZIY8Hb/yh4MuoxrjuBrOZsg==}
peerDependencies:
'@codemirror/state': ^6
'@codemirror/view': ^6
@@ -5349,6 +5349,10 @@ packages:
resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
+ resolution: {integrity: sha512-sSuxWU5j5SR9QQji/o2qMvqRNYRDOcBTgsJ/DeCf4iSN4gW+gNMXM7wFIP+fdXZxoNiAnHUTGjCr+TSWXdRDKg==}
+ engines: {node: '>=0.3.1'}
+
resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}
engines: {node: '>=8'}
@@ -11180,10 +11184,11 @@ snapshots:
'@marijn/[email protected]': {}
- '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
+ '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/state': 6.5.2
'@codemirror/view': 6.38.1
+ diff: 8.0.2
'@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
@@ -15526,6 +15531,8 @@ snapshots:
+
dependencies:
path-type: 4.0.0
diff --git a/tests/_server/ai/snapshots/edit_inline_prompts.txt b/tests/_server/ai/snapshots/edit_inline_prompts.txt
index ba7cfec4b1..0b04994a5d 100644
--- a/tests/_server/ai/snapshots/edit_inline_prompts.txt
+++ b/tests/_server/ai/snapshots/edit_inline_prompts.txt
@@ -1 +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
+You are a python code completion assistant. Complete the missing code between the prefix and suffix while maintaining proper syntax, style, and functionality.Only output the code that goes after the <|fim_suffix|> part. Do not add any explanation or markdown.
\ No newline at end of file
diff --git a/tests/_server/ai/test_prompts.py b/tests/_server/ai/test_prompts.py
index 5d1ffe9d40..19ac91638f 100644
--- a/tests/_server/ai/test_prompts.py
+++ b/tests/_server/ai/test_prompts.py
@@ -5,7 +5,7 @@ from typing import cast
from marimo._ast.visitor import Language
from marimo._server.ai.prompts import (
- FILL_ME_TAG,
+ FIM_SUFFIX_TAG,
_format_variables,
get_chat_system_prompt,
get_inline_system_prompt,
@@ -173,9 +173,7 @@ def test_empty_rules():
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
+ assert FIM_SUFFIX_TAG in result
def test_chat_system_prompts():
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index f0a658a362..72d64c4209 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -9,7 +9,11 @@ from unittest.mock import MagicMock, Mock, patch
import pytest
from marimo._dependencies.dependencies import DependencyManager
-from marimo._server.ai.prompts import FILL_ME_TAG
+from marimo._server.ai.prompts import (
+ FIM_MIDDLE_TAG,
+ FIM_PREFIX_TAG,
+ FIM_SUFFIX_TAG,
+)
from marimo._server.ai.providers import (
AnyProviderConfig,
OpenAIProvider,
@@ -279,12 +283,18 @@ class TestOpenAiEndpoints:
prompt = oaiclient.chat.completions.create.call_args.kwargs[
"messages"
][1]["content"]
- assert prompt == f"import pandas as pd\n{FILL_ME_TAG}\ndf.head()"
- # Assert the system prompt includes language-specific instructions
+ assert (
+ prompt
+ == f"{FIM_PREFIX_TAG}import pandas as pd\n{FIM_SUFFIX_TAG}\ndf.head(){FIM_MIDDLE_TAG}"
+ )
+ # Assert the system prompt for FIM models
system_prompt = oaiclient.chat.completions.create.call_args.kwargs[
"messages"
][0]["content"]
- assert "python" in system_prompt
+ assert (
+ system_prompt
+ == f"You are a python code completion assistant. Complete the missing code between the prefix and suffix while maintaining proper syntax, style, and functionality.Only output the code that goes after the {FIM_SUFFIX_TAG} part. Do not add any explanation or markdown."
+ )
# Assert the model it was called with
model = oaiclient.chat.completions.create.call_args.kwargs["model"]
assert model == "gpt-marimo-for-inline-completion"
@@ -341,11 +351,14 @@ class TestOpenAiEndpoints:
},
)
assert response.status_code == 200, response.text
- # Assert the system prompt includes language-specific instructions
+ # Assert the system prompt for FIM models
system_prompt = oaiclient.chat.completions.create.call_args.kwargs[
"messages"
][0]["content"]
- assert "sql" in system_prompt
+ assert (
+ system_prompt
+ == f"You are a sql code completion assistant. Complete the missing code between the prefix and suffix while maintaining proper syntax, style, and functionality.Only output the code that goes after the {FIM_SUFFIX_TAG} part. Do not add any explanation or markdown."
+ )
# Assert model
model = oaiclient.chat.completions.create.call_args.kwargs["model"]
assert model == "gpt-marimo-for-inline-completion"
@@ -452,7 +465,10 @@ class TestAnthropicAiEndpoints:
prompt: str = anthropic_client.messages.create.call_args.kwargs[
"messages"
][0]["content"]
- assert prompt == f"import pandas as pd\n{FILL_ME_TAG}\ndf.head()"
+ assert (
+ prompt
+ == f"{FIM_PREFIX_TAG}import pandas as pd\n{FIM_SUFFIX_TAG}\ndf.head(){FIM_MIDDLE_TAG}"
+ )
# Assert the model it was called with
model = anthropic_client.messages.create.call_args.kwargs["model"]
assert model == "claude-3.5-for-inline-completion"
@@ -585,7 +601,7 @@ class TestGoogleAiEndpoints:
)
assert (
prompt[0]["parts"][0]["text"]
- == f"import pandas as pd\n{FILL_ME_TAG}\ndf.head()"
+ == f"{FIM_PREFIX_TAG}import pandas as pd\n{FIM_SUFFIX_TAG}\ndf.head(){FIM_MIDDLE_TAG}"
)