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: include samples in AI prompt (#3028)

Myles Scolnick9d537ee053db
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index b20b34a6b7..798db1b75c 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -72,7 +72,8 @@ export const ChatPanel = () => {
const setInput = (newValue: string) => {
setInputInternal(newValue);
- setCompletionBody(getAICompletionBody(newValue));
+ const messagesConcat = messages.map((m) => m.content).join("\n");
+ setCompletionBody(getAICompletionBody(`${messagesConcat}\n\n${newValue}`));
};
useEffect(() => {
diff --git a/frontend/src/components/editor/ai/completion-utils.ts b/frontend/src/components/editor/ai/completion-utils.ts
index fe1c537436..eab20dbc5a 100644
--- a/frontend/src/components/editor/ai/completion-utils.ts
+++ b/frontend/src/components/editor/ai/completion-utils.ts
@@ -24,6 +24,7 @@ export function getAICompletionBody(
columns: dataset.columns.map((column) => ({
name: column.name,
type: column.type,
+ sampleValues: column.sample_values,
})),
})),
},
diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.py
index 2241a6e47c..4b60a6184c 100644
--- a/marimo/_data/get_datasets.py
+++ b/marimo/_data/get_datasets.py
@@ -33,6 +33,7 @@ def _get_data_table(value: object, variable_name: str) -> Optional[DataTable]:
name=column_name,
type=column_type[0],
external_type=column_type[1],
+ sample_values=table.get_sample_values(column_name),
)
for column_name, column_type in table.get_field_types()
]
@@ -115,6 +116,7 @@ def _get_datasets_from_duckdb_internal() -> List[DataTable]:
name=column_name,
type=_db_type_to_data_type(column_type),
external_type=column_type,
+ sample_values=[],
)
for column_name, column_type in zip(
cast(list[str], column_names),
diff --git a/marimo/_data/models.py b/marimo/_data/models.py
index 07b30e1c29..8dc08ae390 100644
--- a/marimo/_data/models.py
+++ b/marimo/_data/models.py
@@ -34,6 +34,7 @@ class DataTableColumn:
name: str
type: DataType
external_type: ExternalDataType
+ sample_values: List[str]
DataTableSource = Literal["local", "duckdb"]
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 000fed8e5f..7c7bc1f580 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -250,6 +250,9 @@ class DefaultTableManager(TableManager[JsonTableData]):
self._as_table_manager().get_unique_column_values(column)
)
+ def get_sample_values(self, column: str) -> list[Any]:
+ return self._as_table_manager().get_sample_values(column)
+
def sort_values(
self, by: ColumnName, descending: bool
) -> DefaultTableManager:
diff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.py
index 64c9e7e7c1..7d4df7d4ff 100644
--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py
+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py
@@ -162,6 +162,12 @@ class IbisTableManagerFactory(TableManagerFactory):
)
return result # type: ignore
+ def get_sample_values(self, column: str) -> list[Any]:
+ # Don't sample values for Ibis tables
+ # since it can be expensive
+ del column
+ return []
+
def sort_values(
self, by: ColumnName, descending: bool
) -> IbisTableManager:
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index b3d8e75b65..31c37e1973 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -263,6 +263,15 @@ class NarwhalsTableManager(
def get_unique_column_values(self, column: str) -> list[str | int | float]:
return self.data[column].unique().to_list()
+ def get_sample_values(self, column: str) -> list[Any]:
+ # Sample 3 values from the column
+ SAMPLE_SIZE = 3
+ try:
+ return self.data[column].head(SAMPLE_SIZE).to_list()
+ except Exception:
+ # May be metadata-only frame
+ return []
+
def sort_values(
self, by: ColumnName, descending: bool
) -> TableManager[Any]:
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index be19dfb28f..7a6bd0a088 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -146,6 +146,10 @@ class TableManager(abc.ABC, Generic[T]):
def get_unique_column_values(self, column: str) -> list[str | int | float]:
raise NotImplementedError
+ @abc.abstractmethod
+ def get_sample_values(self, column: str) -> list[Any]:
+ raise NotImplementedError
+
def __repr__(self) -> str:
rows = self.get_num_rows(force=False)
columns = self.get_num_columns()
diff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.py
index d84adadc8e..c63f617ba2 100644
--- a/marimo/_server/ai/prompts.py
+++ b/marimo/_server/ai/prompts.py
@@ -10,8 +10,6 @@ from marimo._server.models.completion import (
language_rules = {
"python": [
- "Do not describe the code, just write the code.",
- "Do not output markdown or backticks.",
"When using matplotlib to show plots, use plt.gca() instead of plt.show().",
"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.",
@@ -23,23 +21,39 @@ language_rules = {
}
+def _format_schema_info(context: Optional[AiCompletionContext]) -> str:
+ """Helper to format schema information from context"""
+ if not context or not context.schema:
+ return ""
+
+ schema_info = "\n\nAvailable schema:\n"
+ for schema in context.schema:
+ schema_info += f"- Table: {schema.name}\n"
+ for col in schema.columns:
+ schema_info += f" - Column: {col.name}\n"
+ schema_info += f" - Type: {col.type}\n"
+ if col.sample_values:
+ samples = ", ".join(f"{v}" for v in col.sample_values)
+ schema_info += f" - Sample values: {samples}\n"
+ return schema_info
+
+
class Prompter:
- def __init__(
- self,
- code: str,
- context: Optional[AiCompletionContext],
- ):
+ def __init__(self, code: str):
self.code = code
- self.context = context
@staticmethod
def get_system_prompt(
- *, language: Language, custom_rules: Optional[str] = None
+ *,
+ language: Language,
+ custom_rules: Optional[str] = None,
+ context: Optional[AiCompletionContext] = None,
) -> str:
if language in language_rules:
- all_rules = [f"You can only output {language}."] + language_rules[
- language
- ]
+ 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)
)
@@ -50,25 +64,23 @@ class Prompter:
if custom_rules and custom_rules.strip():
system_prompt += f"\n\nAdditional rules:\n{custom_rules}"
-
- return system_prompt
else:
- return "You are a helpful assistant that can answer questions."
+ system_prompt = (
+ "You are a helpful assistant that can answer questions."
+ )
+
+ system_prompt += _format_schema_info(context)
+
+ return system_prompt
def get_prompt(self, *, user_prompt: str, include_other_code: str) -> str:
prompt = user_prompt
if include_other_code:
- prompt += f"\n\nCode from other cells:\n{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\nCurrent code:\n{self.code}"
- if self.context and self.context.schema:
- schema_info = "\n\nAvailable schema:\n"
- for schema in self.context.schema:
- columns = ", ".join(
- [f"{col.name} ({col.type})" for col in schema.columns]
- )
- schema_info += f"- {schema.name}: {columns}\n"
- prompt += schema_info
+ prompt += (
+ f"\n\n<current-code>\n{self.code.strip()}\n</current-code>"
+ )
return prompt
@staticmethod
@@ -116,13 +128,6 @@ class Prompter:
f"\n\nCode from other cells:\n{include_other_code.strip()}"
)
- if context and context.schema:
- schema_info = "\n\nAvailable schema:\n"
- for schema in context.schema:
- columns = ", ".join(
- [f"{col.name} ({col.type})" for col in schema.columns]
- )
- schema_info += f"- {schema.name}: {columns}\n"
- system_prompt += schema_info
+ system_prompt += _format_schema_info(context)
return system_prompt
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index 737fc65215..ea40ce31dd 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -312,7 +312,7 @@ async def ai_completion(
body = await parse_request(request, cls=AiCompletionRequest)
custom_rules = config.get("ai", {}).get("rules", None)
- prompter = Prompter(code=body.code, context=body.context)
+ prompter = Prompter(code=body.code)
system_prompt = Prompter.get_system_prompt(
language=body.language, custom_rules=custom_rules
)
diff --git a/marimo/_server/models/completion.py b/marimo/_server/models/completion.py
index 6138f2e10c..69f7fcf2e7 100644
--- a/marimo/_server/models/completion.py
+++ b/marimo/_server/models/completion.py
@@ -11,6 +11,7 @@ from marimo._ai.types import ChatMessage
class SchemaColumn:
name: str
type: str
+ sample_values: List[str]
@dataclass
@@ -38,8 +39,8 @@ class AiCompletionRequest:
@dataclass
class ChatRequest:
+ context: AiCompletionContext
+ include_other_code: str
messages: List[ChatMessage]
model: Optional[str] = None
variables: Optional[List[str]] = None
- context: Optional[AiCompletionContext] = None
- include_other_code: str = ""
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 1c82b47c5c..69ee70a466 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -22,11 +22,16 @@ components:
properties:
name:
type: string
+ sampleValues:
+ items:
+ type: string
+ type: array
type:
type: string
required:
- name
- type
+ - sampleValues
type: object
type: array
name:
@@ -421,12 +426,17 @@ components:
type: string
name:
type: string
+ sample_values:
+ items:
+ type: string
+ type: array
type:
$ref: '#/components/schemas/DataType'
required:
- name
- type
- external_type
+ - sample_values
type: object
DataType:
enum:
@@ -1916,7 +1926,7 @@ components:
type: object
info:
title: marimo API
- version: 0.9.21
+ version: 0.9.28
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index eae5cb6d9d..968e2a8b8a 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2005,6 +2005,7 @@ export interface components {
schema: {
columns: {
name: string;
+ sampleValues: string[];
type: string;
}[];
name: string;
@@ -2162,6 +2163,7 @@ export interface components {
DataTableColumn: {
external_type: string;
name: string;
+ sample_values: string[];
type: components["schemas"]["DataType"];
};
/** @enum {string} */
diff --git a/tests/_data/test_get_datasets.py b/tests/_data/test_get_datasets.py
index 6608db76fe..f229d8ffa7 100644
--- a/tests/_data/test_get_datasets.py
+++ b/tests/_data/test_get_datasets.py
@@ -66,84 +66,136 @@ def test_get_datasets() -> None:
variable_name=None,
columns=[
DataTableColumn(
- name="col_boolean", type="boolean", external_type="BOOLEAN"
+ name="col_boolean",
+ type="boolean",
+ external_type="BOOLEAN",
+ sample_values=[],
),
DataTableColumn(
- name="col_tinyint", type="integer", external_type="TINYINT"
+ name="col_tinyint",
+ type="integer",
+ external_type="TINYINT",
+ sample_values=[],
),
DataTableColumn(
name="col_smallint",
type="integer",
external_type="SMALLINT",
+ sample_values=[],
),
DataTableColumn(
- name="col_integer", type="integer", external_type="INTEGER"
+ name="col_integer",
+ type="integer",
+ external_type="INTEGER",
+ sample_values=[],
),
DataTableColumn(
- name="col_bigint", type="integer", external_type="BIGINT"
+ name="col_bigint",
+ type="integer",
+ external_type="BIGINT",
+ sample_values=[],
),
DataTableColumn(
- name="col_hugeint", type="integer", external_type="HUGEINT"
+ name="col_hugeint",
+ type="integer",
+ external_type="HUGEINT",
+ sample_values=[],
),
DataTableColumn(
name="col_utinyint",
type="integer",
external_type="UTINYINT",
+ sample_values=[],
),
DataTableColumn(
name="col_usmallint",
type="integer",
external_type="USMALLINT",
+ sample_values=[],
),
DataTableColumn(
name="col_uinteger",
type="integer",
external_type="UINTEGER",
+ sample_values=[],
),
DataTableColumn(
- name="col_ubigint", type="integer", external_type="UBIGINT"
+ name="col_ubigint",
+ type="integer",
+ external_type="UBIGINT",
+ sample_values=[],
),
DataTableColumn(
- name="col_float", type="number", external_type="FLOAT"
+ name="col_float",
+ type="number",
+ external_type="FLOAT",
+ sample_values=[],
),
DataTableColumn(
- name="col_double", type="number", external_type="DOUBLE"
+ name="col_double",
+ type="number",
+ external_type="DOUBLE",
+ sample_values=[],
),
DataTableColumn(
name="col_decimal",
type="number",
external_type="DECIMAL(18,3)",
+ sample_values=[],
),
DataTableColumn(
- name="col_varchar", type="string", external_type="VARCHAR"
+ name="col_varchar",
+ type="string",
+ external_type="VARCHAR",
+ sample_values=[],
),
DataTableColumn(
- name="col_date", type="date", external_type="DATE"
+ name="col_date",
+ type="date",
+ external_type="DATE",
+ sample_values=[],
),
DataTableColumn(
- name="col_time", type="time", external_type="TIME"
+ name="col_time",
+ type="time",
+ external_type="TIME",
+ sample_values=[],
),
DataTableColumn(
name="col_timestamp",
type="datetime",
external_type="TIMESTAMP",
+ sample_values=[],
),
DataTableColumn(
name="col_interval",
type="datetime",
external_type="INTERVAL",
+ sample_values=[],
),
DataTableColumn(
- name="col_blob", type="string", external_type="BLOB"
+ name="col_blob",
+ type="string",
+ external_type="BLOB",
+ sample_values=[],
),
DataTableColumn(
- name="col_bit", type="string", external_type="BIT"
+ name="col_bit",
+ type="string",
+ external_type="BIT",
+ sample_values=[],
),
DataTableColumn(
- name="col_uuid", type="string", external_type="UUID"
+ name="col_uuid",
+ type="string",
+ external_type="UUID",
+ sample_values=[],
),
DataTableColumn(
- name="col_json", type="unknown", external_type="JSON"
+ name="col_json",
+ type="unknown",
+ external_type="JSON",
+ sample_values=[],
),
],
)
@@ -163,6 +215,11 @@ def test_get_datasets_from_variables(df: Any) -> None:
rows = datatests[0].num_rows
assert rows is None or rows == 3
+ sample_values1 = datatests[0].columns[0].sample_values
+ sample_values2 = datatests[0].columns[1].sample_values
+ assert sample_values1 == [1, 2, 3] or sample_values1 == []
+ assert sample_values2 == ["a", "a", "a"] or sample_values2 == []
+
assert datatests == [
DataTable(
name="my_df",
@@ -176,11 +233,13 @@ def test_get_datasets_from_variables(df: Any) -> None:
name="A",
type="integer",
external_type=external_type1,
+ sample_values=sample_values1,
),
DataTableColumn(
name="B",
type="string",
external_type=external_type2,
+ sample_values=sample_values2,
),
],
)
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index 69de213b94..1e9e325627 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -348,6 +348,20 @@ class TestColumnarDefaultTable(unittest.TestCase):
unique_values = self.manager.get_unique_column_values("age")
assert unique_values == [22, 25, 28, 30, 35]
+ @pytest.mark.skipif(
+ not HAS_DEPS, reason="optional dependencies not installed"
+ )
+ def test_get_sample_values(self) -> None:
+ data = {
+ "age": [22, 25, 28, 30, 35],
+ "name": ["Alice", "Bob", "Charlie", "Dave", "Eve"],
+ }
+ manager = DefaultTableManager(data)
+ sample_values = manager.get_sample_values("age")
+ assert sample_values == [22, 25, 28]
+ sample_values = manager.get_sample_values("name")
+ assert sample_values == ["Alice", "Bob", "Charlie"]
+
def test_search(self) -> None:
searched_manager = self.manager.search("alice")
expected_data = {
diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
index f121a7781a..7a395798a5 100644
--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
@@ -208,6 +208,10 @@ class TestIbisTableManagerFactory(unittest.TestCase):
unique_values = self.manager.get_unique_column_values(column)
assert sorted(unique_values) == [1, 2, 3]
+ def test_get_sample_values(self) -> None:
+ sample_values = self.manager.get_sample_values("A")
+ assert sample_values == []
+
def test_search(self) -> None:
import ibis
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index f5e2ea7a20..a2157c89eb 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -739,3 +739,35 @@ def test_sort_values_with_nulls(df: Any) -> None:
first = unwrap_py_scalar(sorted_manager.data["A"][0])
assert first is None or isnan(first)
assert sorted_manager.data["A"].to_list()[1:] == [3, 2, 1]
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {"A": [1, 2, 3, 4], "B": ["a", "b", "c", "d"]},
+ exclude=["ibis", "duckdb"],
+ ),
+)
+def test_get_sample_values(df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ sample_values = manager.get_sample_values("A")
+ assert sample_values == [1, 2, 3]
+ sample_values = manager.get_sample_values("B")
+ assert sample_values == ["a", "b", "c"]
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {"A": [1, 2, 3, 4], "B": ["a", "b", "c", "d"]},
+ include=["ibis", "duckdb"],
+ ),
+)
+def test_get_sample_values_with_metadata_only_frame(df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ sample_values = manager.get_sample_values("A")
+ assert sample_values == []
+ sample_values = manager.get_sample_values("B")
+ assert sample_values == []
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 37bc5fab76..005057b18f 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -818,3 +818,11 @@ class TestPandasTableManager(unittest.TestCase):
"datetime64[ns]",
)
assert manager.get_field_type("time_col") == ("string", "object")
+
+ def test_get_sample_values(self) -> None:
+ df = pd.DataFrame({"A": [1, 2, 3, 4], "B": ["a", "b", "c", "d"]})
+ manager = self.factory.create()(df)
+ sample_values = manager.get_sample_values("A")
+ assert sample_values == [1, 2, 3]
+ sample_values = manager.get_sample_values("B")
+ assert sample_values == ["a", "b", "c"]
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index 5621ecc788..10b78d9f58 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -395,6 +395,12 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
unique_values = self.manager.get_unique_column_values(column)
assert unique_values == [1, 2, 3]
+ def test_get_sample_values(self) -> None:
+ sample_values = self.manager.get_sample_values("A")
+ assert sample_values == [1, 2, 3]
+ sample_values = self.manager.get_sample_values("B")
+ assert sample_values == ["a", "b", "c"]
+
def test_search(self) -> None:
import polars as pl
diff --git a/tests/_server/ai/snapshots/chat_system_prompts.txt b/tests/_server/ai/snapshots/chat_system_prompts.txt
index 0f0da29198..8d653790cf 100644
--- a/tests/_server/ai/snapshots/chat_system_prompts.txt
+++ b/tests/_server/ai/snapshots/chat_system_prompts.txt
@@ -8,11 +8,9 @@ You are a helpful assistant working in a marimo notebook. You can answer questio
Rules for python:
-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.
+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:
1. The SQL must use duckdb syntax.
@@ -25,11 +23,9 @@ You are a helpful assistant working in a marimo notebook. You can answer questio
Rules for python:
-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.
+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:
1. The SQL must use duckdb syntax.
@@ -45,11 +41,9 @@ You are a helpful assistant working in a marimo notebook. You can answer questio
Rules for python:
-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.
+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:
1. The SQL must use duckdb syntax.
@@ -65,18 +59,28 @@ You are a helpful assistant working in a marimo notebook. You can answer questio
Rules for python:
-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.
+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:
1. The SQL must use duckdb syntax.
Available schema:
-- df_1: age (int), name (str)
-- d2_2: a (int), b (int)
+- Table: df_1
+ - Column: age
+ - Type: int
+ - Sample values: 1, 2, 3
+ - Column: name
+ - Type: str
+ - Sample values: Alice, Bob, Charlie
+- Table: d2_2
+ - Column: a
+ - Type: int
+ - Sample values: 1, 2, 3
+ - Column: b
+ - Type: int
+ - Sample values: 4, 5, 6
==================== with other code ====================
@@ -87,11 +91,9 @@ You are a helpful assistant working in a marimo notebook. You can answer questio
Rules for python:
-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.
+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:
1. The SQL must use duckdb syntax.
@@ -108,11 +110,9 @@ You are a helpful assistant working in a marimo notebook. You can answer questio
Rules for python:
-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.
+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:
1. The SQL must use duckdb syntax.
@@ -128,4 +128,10 @@ import pandas as pd
import numpy as np
Available schema:
-- df_1: age (int), name (str)
+- Table: df_1
+ - Column: age
+ - Type: int
+ - Sample values: 1, 2, 3
+ - Column: name
+ - Type: str
+ - Sample values: Alice, Bob, Charlie
diff --git a/tests/_server/ai/snapshots/system_prompts.txt b/tests/_server/ai/snapshots/system_prompts.txt
index 34bfd61428..a564170284 100644
--- a/tests/_server/ai/snapshots/system_prompts.txt
+++ b/tests/_server/ai/snapshots/system_prompts.txt
@@ -3,23 +3,24 @@
==================== python ====================
You are a helpful assistant that can answer questions about python. Here are your rules:
-1. You can only output python.
-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.
+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.
==================== markdown ====================
You are a helpful assistant that can answer questions about markdown. Here are your rules:
-1. You can only output markdown.
+1. Do not describe the code, just write the code.
+2. Do not output markdown or backticks.
==================== sql ====================
You are a helpful assistant that can answer questions about sql. Here are your rules:
-1. You can only output sql.
-2. The SQL must use duckdb syntax.
+1. Do not describe the code, just write the code.
+2. Do not output markdown or backticks.
+3. The SQL must use duckdb syntax.
==================== idk ====================
@@ -28,12 +29,29 @@ 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.
-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.
+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.
Additional rules:
-Always use type hints.
\ No newline at end of file
+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.
+
+Available schema:
+- Table: df_1
+ - Column: age
+ - Type: int
+ - Sample values: 1, 2, 3
+ - Column: name
+ - Type: str
+ - Sample values: Alice, Bob, Charlie
diff --git a/tests/_server/ai/snapshots/user_prompts.txt b/tests/_server/ai/snapshots/user_prompts.txt
index 33128a32e4..a1030c79f1 100644
--- a/tests/_server/ai/snapshots/user_prompts.txt
+++ b/tests/_server/ai/snapshots/user_prompts.txt
@@ -8,40 +8,40 @@ Create a pandas dataframe
Create a pandas dataframe
-Current code:
+<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:
+<code-from-other-cells>
import pandas as pd
import numpy as np
+</code-from-other-cells>
-
-Current code:
+<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:
+<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:
+<code-from-other-cells>
import marimo as mo
+</code-from-other-cells>
-Current code:
+<current-code>
import pandas as pd
-
-Available schema:
-- df_1: age (int), name (str)
-- d2_2: a (int), b (int)
+</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 f798442886..9eb841fcb5 100644
--- a/tests/_server/ai/test_prompts.py
+++ b/tests/_server/ai/test_prompts.py
@@ -30,6 +30,28 @@ def test_system_prompts():
language="python", custom_rules="Always use type hints."
)
+ result += _header("with context")
+ result += Prompter.get_system_prompt(
+ language="python",
+ context=AiCompletionContext(
+ schema=[
+ SchemaTable(
+ name="df_1",
+ columns=[
+ SchemaColumn(
+ "age", "int", sample_values=["1", "2", "3"]
+ ),
+ SchemaColumn(
+ "name",
+ "str",
+ sample_values=["Alice", "Bob", "Charlie"],
+ ),
+ ],
+ )
+ ]
+ ),
+ )
+
snapshot("system_prompts.txt", result)
@@ -47,20 +69,18 @@ def test_user_prompts():
result: str = ""
result += _header("no code")
- result += Prompter(code="", context=AiCompletionContext()).get_prompt(
+ result += Prompter(code="").get_prompt(
user_prompt=prompt, include_other_code=""
)
result += _header("with code")
result += Prompter(
code="df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})",
- context=AiCompletionContext(),
).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]})",
- context=AiCompletionContext(),
).get_prompt(
user_prompt=prompt,
include_other_code="import pandas as pd\nimport numpy as np\n",
@@ -69,34 +89,15 @@ def test_user_prompts():
result += _header("with just other code")
result += Prompter(
code="",
- context=AiCompletionContext(),
).get_prompt(
user_prompt=prompt,
include_other_code="import pandas as pd\nimport numpy as np\n",
)
result += _header("with context")
- result += Prompter(
- code="import pandas as pd",
- context=AiCompletionContext(
- schema=[
- SchemaTable(
- name="df_1",
- columns=[
- SchemaColumn("age", "int"),
- SchemaColumn("name", "str"),
- ],
- ),
- SchemaTable(
- name="d2_2",
- columns=[
- SchemaColumn("a", "int"),
- SchemaColumn("b", "int"),
- ],
- ),
- ],
- ),
- ).get_prompt(user_prompt=prompt, include_other_code="import marimo as mo")
+ result += Prompter(code="import pandas as pd").get_prompt(
+ user_prompt=prompt, include_other_code="import marimo as mo"
+ )
snapshot("user_prompts.txt", result)
@@ -119,15 +120,25 @@ def test_chat_system_prompts():
SchemaTable(
name="df_1",
columns=[
- SchemaColumn("age", "int"),
- SchemaColumn("name", "str"),
+ SchemaColumn(
+ "age", "int", sample_values=["1", "2", "3"]
+ ),
+ SchemaColumn(
+ "name",
+ "str",
+ sample_values=["Alice", "Bob", "Charlie"],
+ ),
],
),
SchemaTable(
name="d2_2",
columns=[
- SchemaColumn("a", "int"),
- SchemaColumn("b", "int"),
+ SchemaColumn(
+ "a", "int", sample_values=["1", "2", "3"]
+ ),
+ SchemaColumn(
+ "b", "int", sample_values=["4", "5", "6"]
+ ),
],
),
],
@@ -149,8 +160,14 @@ def test_chat_system_prompts():
SchemaTable(
name="df_1",
columns=[
- SchemaColumn("age", "int"),
- SchemaColumn("name", "str"),
+ SchemaColumn(
+ "age", "int", sample_values=["1", "2", "3"]
+ ),
+ SchemaColumn(
+ "name",
+ "str",
+ sample_values=["Alice", "Bob", "Charlie"],
+ ),
],
),
],
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index 601c1bc400..b82ed7f4ef 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -152,7 +152,7 @@ class TestOpenAiEndpoints:
"messages"
][1]["content"]
assert prompt == (
- "Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501
+ "Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>"
)
@staticmethod
@@ -279,7 +279,7 @@ class TestAnthropicAiEndpoints:
"messages"
][0]["content"]
assert prompt == (
- "Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501
+ "Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>"
)
@@ -318,7 +318,7 @@ class TestGoogleAiEndpoints:
"contents"
]
assert prompt == (
- "Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501
+ "Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>"
)
@staticmethod
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index e199abf144..567202658b 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -249,6 +249,7 @@ def test_add_datasets() -> None:
name="col1",
type="boolean",
external_type="BOOL",
+ sample_values=["true", "false"],
)
],
num_rows=1,
@@ -263,7 +264,8 @@ def test_add_datasets() -> None:
DataTableColumn(
name="col2",
type="integer",
- external_type="BOOL",
+ external_type="INT",
+ sample_values=["1", "2"],
)
],
num_rows=2,
@@ -295,6 +297,7 @@ def test_add_datasets() -> None:
name="new_col",
type="boolean",
external_type="BOOL",
+ sample_values=["true", "false"],
)
],
num_rows=20,