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
experimental: chat sidebar (#2989)
Myles Scolnick53d6dc408cca
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 264ff6267f..9bf0cf3d9d 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -1,4 +1,4 @@-fail_fast: true+fail_fast: falserepos:- repo: https://github.com/pre-commit/pre-commit-hooksdiff --git a/development_docs/prompts.md b/development_docs/prompts.mdnew file mode 100644index 0000000000..6e22001cc3--- /dev/null+++ b/development_docs/prompts.md@@ -0,0 +1,13 @@+# Prompts++## System prompts++Prompts are generated using the `Prompter` class in `marimo/_server/ai/prompts.py`.++### Snapshots++You can create snapshots of the prompts using the `snapshot` function in `tests/_server/ai/test_prompts.py`. These snapshots are checked into the repo, and you can use them to verify that the prompts have not changed. To run these snapshots, run:++```bash+hatch run +py=3.12 test-optional:test tests/_server/ai/test_prompts.py+```diff --git a/docs/api/inputs/chat.md b/docs/api/inputs/chat.mdindex b32fc5d17d..60ef4c8dba 100644--- a/docs/api/inputs/chat.md+++ b/docs/api/inputs/chat.md@@ -87,7 +87,7 @@ containing `role`, `content`, and optional `attachments` attributes... autoclass:: ChatMessage:members:- .. autoclasstoc:: marimo._plugins.ui._impl.chat.types.ChatMessage+ .. autoclasstoc:: marimo._ai.types.types.ChatMessage```## Custom Model with Additional Context@@ -167,7 +167,7 @@ mo.ui.chat(.. autoclass:: marimo.ai.llm.openai:members:- .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.openai+ .. autoclasstoc:: marimo._ai.llm.openai```### Anthropic@@ -189,7 +189,7 @@ mo.ui.chat(.. autoclass:: marimo.ai.llm.anthropic:members:- .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.anthropic+ .. autoclasstoc:: marimo._ai.llm.anthropic```### Google AI@@ -211,7 +211,7 @@ mo.ui.chat(.. autoclass:: marimo.ai.llm.google:members:- .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.google+ .. autoclasstoc:: marimo._ai.llm.google```### Groq@@ -233,7 +233,7 @@ mo.ui.chat(.. autoclass:: marimo.ai.llm.groq:members:- .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.groq+ .. autoclasstoc:: marimo._ai.llm.groq```## Typesdiff --git a/examples/ai/chat/recipe_bot.py b/examples/ai/chat/recipe_bot.pyindex b4fd25cf3f..43c229e913 100644--- a/examples/ai/chat/recipe_bot.py+++ b/examples/ai/chat/recipe_bot.py@@ -18,8 +18,8 @@ def __():chat = mo.ui.chat(mo.ai.llm.openai("gpt-4o",- system_message="""You are a helpful assistant that can- parse my recipe and summarize them for me.+ system_message="""You are a helpful assistant that can+ parse my recipe and summarize them for me.Give me a title in the first line.""",),allow_attachments=["image/png", "image/jpeg"],diff --git a/frontend/package.json b/frontend/package.jsonindex 08015b35bb..877eaf3198 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -56,6 +56,7 @@"@radix-ui/react-popover": "~1.0.7","@radix-ui/react-progress": "~1.0.3","@radix-ui/react-radio-group": "~1.1.3",+ "@radix-ui/react-scroll-area": "^1.2.1","@radix-ui/react-select": "~2.0.0","@radix-ui/react-slider": "~1.1.2","@radix-ui/react-slot": "~1.0.2",@@ -120,6 +121,7 @@"react-error-boundary": "^4.0.13","react-grid-layout": "^1.4.4","react-hook-form": "^7.52.2",+ "react-markdown": "^9.0.1","react-plotly.js": "^2.6.0","react-resizable-panels": "2.0.19","react-use-event-hook": "^0.9.6",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex ba1e06d8a5..b6b8dda467 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -144,6 +144,9 @@ importers:'@radix-ui/react-radio-group':specifier: ~1.1.3version: 1.1.3(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-scroll-area':+ specifier: ^1.2.1+ version: 1.2.1(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])'@radix-ui/react-select':specifier: ~2.0.0version: 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])@@ -336,6 +339,9 @@ importers:react-hook-form:specifier: ^7.52.2version: 7.52.2([email protected])+ react-markdown:+ specifier: ^9.0.1+ version: 9.0.1(@types/[email protected])([email protected])react-plotly.js:specifier: ^2.6.0version: 2.6.0(patch_hash=bpeex744nmt6722etqry6essaq)([email protected]([email protected])([email protected]([email protected])))([email protected])@@ -1679,9 +1685,15 @@ packages:'@radix-ui/[email protected]':resolution: {integrity: sha512-T5gIdVO2mmPW3NNhjNgEP3cqMXjXL9UbO0BzWcXfvdBs+BohbQxvd/K5hSVKmn9/lbTdsQVKbUcP5WLCwvUbBg==}+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-V3gRzhVNU1ldS5XhAPTom1fOIo4ccrjjJgmE+LI2h/WaFpHmx0MQApT+KZHnx8abG6Avtfcz4WoEciMnpFT3HQ==}+'@radix-ui/[email protected]':resolution: {integrity: sha512-yQ8oGX2GVsEYMWGxcovu1uGWPCxV5BFfeeYxqPmuAzUyLT9qmaMXSAhXpb0WrspIeqYzdJpkh2vHModJPgRIaw==}+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-4Z8dn6Upk0qk4P74xBhZ6Hd/w0mPEzOOLxy4xiPXOXqjF7jZS0VAKk7/x/H6FyY2zCkYJqePf1G5KmkmNJ4RBA==}+'@radix-ui/[email protected]':resolution: {integrity: sha512-fDG7jcoNKVjSK6yfmuAs0EnPDro0WMXIhMtXdTBWqEioVW206ku+4Lw07e+13lUkFkpoEQ2PdeMIAGpdqEAmDg==}peerDependencies:@@ -1769,6 +1781,15 @@ packages:'@types/react':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-b4inOtiaOnYf9KWyO3jAeeCG6FeyfY6ldiEPanbUjWd+xIk5wZeHa8yVwmrJ2vderhu/BQvzCrJI0lHd+wIiqw==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-R5XaDj06Xul1KGb+WP8qiOh7tKJNz2durpLBXAGZjSVtctcRFCuEvy2gtMwRJGePwQQE5nV77gs4FwRi8T+r2g==}peerDependencies:@@ -1791,6 +1812,15 @@ packages:'@types/react':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-UASk9zi+crv9WteK/NU4PLvOoL3OuE6BWVKNF6hPRBtYBDXQ2u5iu3O59zUlJiTVvkyuycnqrztsHVJwcK9K+Q==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-GjWJX/AUpB703eEBanuBnIWdIXg6NvJFCXcNlSZk4xdszCdhrJgBoUd1cGk67vFO+WdA2pfI/plOpqz/5GUP6Q==}peerDependencies:@@ -1813,6 +1843,15 @@ packages:'@types/react':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-BUuBvgThEiAXh2DWu93XsT+a3aWrGqolGlqqw5VU1kG7p/ZH2cuDlM1sRLNnY3QcBS69UIz2mcKhMxDsdewhjg==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-aJeDjQhywg9LBu2t/At58hCvr7pEm0o2Ke1x33B+MhjNmmZ17sy4KImo0KPLgsnc/zN7GPdce8Cnn0SWvwZO7g==}peerDependencies:@@ -1966,6 +2005,19 @@ packages:'@types/react-dom':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-IeFXVi4YS1K0wVZzXNrbaaUvIJ3qdY+/Ih4eHFhWA9SwGR9UDX7Ck8abvL57C4cv3wwMvUE0OG69Qc3NCcTe/A==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-yi58uVyoAcK/Nq1inRY56ZSjKypBNKTa/1mcL8qdl6oJeEaDbOldlzrGn7P6Q3Id5d+SYNGc5AJgc4vGhjs5+g==}peerDependencies:@@ -1979,6 +2031,19 @@ packages:'@types/react-dom':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-ZSpFm0/uHa8zTvKBDjLFWLo8dkr4MBsiDLz0g3gMUwqgLHz9rTaRRGYDgvZPtBJgYCBKXkS9fzmoySgr8CO6Cw==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-5G6Om/tYSxjSeEdrb1VfKkfZfn/1IlPWd731h2RfPuSbIfNUgfqAwbKfJCg/PP6nuUCTrYzalwHSpSinoWoCag==}peerDependencies:@@ -2018,6 +2083,19 @@ packages:'@types/react-dom':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-FnM1fHfCtEZ1JkyfH/1oMiTcFBQvHKl4vD9WnpwkLgtF+UmnXMCad6ECPTaAjcDjam+ndOEJWgHyKDGNteWSHw==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-RH5b7af4oHtkcHS7pG6Sgv5rk5Wxa7XI8W5gvB1N/yiuDGZxko1ynvOiVhFM7Cis2A8zxF9bTOUVbRDzPepe6w==}peerDependencies:@@ -2053,6 +2131,15 @@ packages:'@types/react':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-FUCf5XMfmW4dtYl69pdS4DbxKy8nj4M7SafBgPllysxmdachynNflAdp/gCsnYWNDnge6tI9onzMp5ARYc1KNw==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-mxm87F88HyHztsI7N+ZUmEoARGkC22YVW5CaC+Byc+HRpuvCrOBPTAnXgf+tZ/7i0Sg/eOePGdMhUKhPaQEqow==}peerDependencies:@@ -2127,6 +2214,15 @@ packages:'@types/react':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-CasTfvsy+frcFkbXtSJ2Zu9JHpN8TYKxkgJGWbjiZhFivxaeW7rMeZt7QELGVLaYVfFMsKHjb7Ak0nMEe+2Vfw==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-Svl5GY5FQeN758fWKrjM6Qb7asvXeiZltlT4U2gVfl8Gx5UAv2sMR0LWo8yhsIZh2oQ0eFdZ59aoOOMV7b47VA==}peerDependencies:@@ -2154,6 +2250,15 @@ packages:'@types/react':optional: true+ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-+FPE0rOdziWSrH9athwI1R0HDVbWlEhd+FR+aSDk4uWGmSJ9Z54sdZVDQPZAinJhJXwfT+qnj969mCsT2gfm5w==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+'@radix-ui/[email protected]':resolution: {integrity: sha512-cV5La9DPwiQ7S0gf/0qiD6YgNqM5Fk97Kdrlc5yBcrF3jyEZQwm7vYFqMo4IfeHgJXsRaMvLABFtd0OVEmZhDw==}peerDependencies:@@ -3353,6 +3458,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==}+ '@types/[email protected]':+ resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}+'@types/[email protected]':resolution: {integrity: sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg==}@@ -3368,6 +3476,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==}+ '@types/[email protected]':+ resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}+'@types/[email protected]':resolution: {integrity: sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==}@@ -3399,6 +3510,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-RpQH4rXLuvTXKR0zqHq3go0RVXYv/YVqv4TnPH95VbwUxZdQlK1EtcMvQvMpDngHbt13Csh9Z4qT9AbkiQH5BA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}+'@types/[email protected]':resolution: {integrity: sha512-yaf7kan2Sq0goxpbcwTQ+8E9RP6HutFBPv74T/IA/ojcHKhuKVlk2YFYyHhWZeLvZPzzLE3aatuQB4h0iqyyUA==}@@ -3435,12 +3549,18 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-bpd8dRn9pr6xKvuEBQup8pwQfD4VUyqO/2deGjfpe6AwC8YRlyEipvefyRJUSiCJTZuCb8Pl1ciVV5ekqJ96Bg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}+'@types/[email protected]':resolution: {integrity: sha512-76CqzuD6Q7LC+AtbPqrvD9AqsN0k8bsYo2bM2J8pmNldP1aIPAbzUQ7QbobyXL4eLr1wK5x8FZFe8eF/ubRuBg==}'@types/[email protected]':resolution: {integrity: sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==}+'@types/[email protected]':resolution: {integrity: sha512-VEI7OdvK2wP7XHnsuXbAJnEpEkF6NjSN45QJlL4VGqZSXsnicpesdTWsg9RISeSdYd3yeRj/y3k5KGjUXYnFwQ==}@@ -3486,6 +3606,12 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-95Sfz4nvMAb0Nl9DTxN3j64adfwfbBPEYq14VN7zT5J5O2M9V6iZMIIQU1U+pJyl9agHYHNCqhCXgyEtIRRa5A==}+ '@types/[email protected]':+ resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}+'@types/[email protected]':resolution: {integrity: sha512-WUtIVRUZ9i5dYXefDEAI7sh9/O7jGvHg7Df/5O/gtH3Yabe5odI3UWopVR1qbPXQtvOxWu3mM4XxlYeZtMWF4g==}@@ -3994,6 +4120,9 @@ packages:resolution: {integrity: sha512-Wk0748DZzQEmjkEN4SbBujM5al4q5TfRBapA32ax0AID/Yek3emS+eyCvPvb4zPddYJTAF4LaJNLt8uHYfdKAQ==}+ resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}+resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}@@ -4108,6 +4237,9 @@ packages:resolution: {integrity: sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==}+ resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}+resolution: {integrity: sha512-13sOfMv2+DWduEU+/xbun3LScLoqN17nBeTLUsmDfKdoiC1fr0n9PU4guu4AhRcOVFk/sW8LyZWHuhWtQZiF+g==}engines: {node: '>=4'}@@ -4132,6 +4264,18 @@ packages:resolution: {integrity: sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==}engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}+ resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}++ resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==}++ resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}++ resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}+resolution: {integrity: sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==}@@ -4267,6 +4411,9 @@ packages:resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}+resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}@@ -4730,6 +4877,9 @@ packages:resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==}+ resolution: {integrity: sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg==}+resolution: {integrity: sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==}engines: {node: '>=6'}@@ -4777,6 +4927,9 @@ packages:resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}+ resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}+resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==}@@ -5098,6 +5251,9 @@ packages:resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==}engines: {node: '>=4.0'}+ resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}+resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}@@ -5502,6 +5658,12 @@ packages:resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-1ngXYb+V9UT5h+PxNRa1O1FYguZK/XL+gkeqvp7EdHlB9oHUG0eYRo/vY5inBdcqo3RkPMC58/H94HvkbfGdyg==}++ resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}+resolution: {integrity: sha512-SQpZK4BzR48kuOg0v4pb3EAGNclzIlqMj3Opu/mu7bbAoFw6oig6cEt/RAi0zTFW/iW6Iz9X9ggGuZTAZ/yZHg==}@@ -5543,6 +5705,9 @@ packages:resolution: {integrity: sha512-9gux8QhvjRO/erSnDPv28noDZcPZmYE7e1vFsBLKLlRlKDSqNJYebj6Qz1TGd5lsRV+X+xYyjCKjuZdABinWjA==}+ resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}+resolution: {integrity: sha512-5zfg6mHUoaer/97TxnGpxmbR7zJtPwIYFMZ/H5ucTlPZhKvtum05yiPK3Mgai3a0DyVxv7qYqoweaEd2nrYQzQ==}@@ -5651,6 +5816,12 @@ packages:resolution: {integrity: sha512-xgs2NH9AE66ucSq4cNG1nhSFghr5l6tdL15Pk+jl46bmmBapgoaY/AacXyaDznAqmGL99TiLSQgO/XazFSKYeQ==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==}++ resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==}+resolution: {integrity: sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==}engines: {node: '>= 0.4'}@@ -5699,6 +5870,9 @@ packages:resolution: {integrity: sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==}+resolution: {integrity: sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==}engines: {node: '>=8'}@@ -5739,6 +5913,9 @@ packages:resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==}+resolution: {integrity: sha512-YeLzceuwg3K6O0MLM3UyUUjKAlyULetwryFp1mHy1I5PfArK0AEqlfa+MR4gkJjcbuJXoDJCvXbyqZVf5CR2Sg==}engines: {node: '>=0.10.0'}@@ -5773,6 +5950,10 @@ packages:resolution: {integrity: sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==}engines: {node: '>=0.10.0'}@@ -6107,6 +6288,9 @@ packages:resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==}+ resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}+resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}hasBin: true@@ -6169,6 +6353,30 @@ packages:resolution: {integrity: sha512-APMBEanjybaPzUrfqU0IMU5I0AswKMH7k8OTLs0vvV4KZpExkTkY87nR/zpbuTPj+gARop7aGUbl11pnDfW6xg==}+ resolution: {integrity: sha512-uZhTV/8NBuw0WHkPTrCqDOl0zVe1BIng5ZtHoDk49ME1qqcjYmmLmOf0gELgcRMxN4w2iuIeVso5/6QymSrgmA==}++ resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}++ resolution: {integrity: sha512-bfOjvNt+1AcbPLTFMFWY149nJz0OjmewJs3LQQ5pIyVGxP4CdOqNVJL6kTaM5c68p8q82Xv3nCyFfUnuEcH3UQ==}++ resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}++ resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}++ resolution: {integrity: sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==}++ resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}++ resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}+resolution: {integrity: sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==}@@ -6202,6 +6410,69 @@ packages:resolution: {integrity: sha512-fFmf2gRXLtlGzug4wpIGN+rQdZ30M8IZEB1D3eZkXNqC7puhqeURBcD/9tbwXsqBO+A6Nzzo3MSSepmnw5xSeg==}+ resolution: {integrity: sha512-FKjQKbxd1cibWMM1P9N+H8TwlgGgSkWZMmfuVucLCHaYqeSvJ0hFeHsIa65pA2nYbes0f8LDHPMrd9X7Ujxg9w==}++ resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}++ resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==}++ resolution: {integrity: sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==}++ resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==}++ resolution: {integrity: sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==}++ resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==}++ resolution: {integrity: sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==}++ resolution: {integrity: sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==}++ resolution: {integrity: sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==}++ resolution: {integrity: sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==}++ resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==}++ resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==}++ resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==}++ resolution: {integrity: sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==}++ resolution: {integrity: sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==}++ resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==}++ resolution: {integrity: sha512-VXJJuNxYWSoYL6AJ6OQECCFGhIU2GGHMw8tahogePBrjkG8aCCas3ibkp7RnVOSTClg2is05/R7maAhF1XyQMg==}++ resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==}++ resolution: {integrity: sha512-534m2WhVTddrcKVepwmVEVnUAmtrx9bfIjNoQHRqfnvdaHQiFytEhJoTgpWJvDEXCO5gLTQh3wYC1PgOJA4NSQ==}++ resolution: {integrity: sha512-eBPdkcoCNvYcxQOAKAlceo5SNdzZWfF+FcSupREAzdAh9rRmE239CEQAiTwIgblwnoM8zzj35sZ5ZwvSEOF6Kw==}+resolution: {integrity: sha512-LPP/3KorzCwBxfeUuZmaR6bG2kdeHSbe0P2tY3FLRU4vYrjYz5hI4QZwV0njUx3jeuKe67YukQ1LSPZBKDqO/Q==}engines: {node: '>=8.6'}@@ -6484,6 +6755,9 @@ packages:resolution: {integrity: sha512-KF/U8tk54BgQewkJPvB4s/US3VQY68BRDpH638+7O/n58TpnwiwnOtGIOsT2/i+M78s61BBpeC83STB88d8sqw==}+ resolution: {integrity: sha512-SWzvYcSJh4d/SGLIOQfZ/CoNv6BTlI6YEQ7Nj82oDVnRpwe/Z/F1EMx42x3JAOwGBlCjeCH0BRJQbQ/opHL17w==}+resolution: {integrity: sha512-QR/GGaKCkhwk1ePQNYDRKYZ3mwU9ypsKhB0XyFnLQdomyEqk3e8wpW3V5Jp88zbxK4n5ST1nqo+g9juTpownhQ==}engines: {node: '>=0.10.0'}@@ -6941,6 +7215,9 @@ packages:resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}+ resolution: {integrity: sha512-PgTgs/BlvHxOu8QuEN7wi5A0OmXaBcHpmCSTehcs6Uuu9IkDIEo13Hy7n898RHfrQ49vKCoGeWZSaAK01nwVig==}+resolution: {integrity: sha512-TdDRD+/QNdrCGCE7v8340QyuXd4kIWIgapsE2+n/SaGiSSbomYl4TjHlvIoCWRpE7wFt02EpB35VVA2ImcBVqw==}@@ -7098,6 +7375,12 @@ packages:resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==}+ resolution: {integrity: sha512-186Gw/vF1uRkydbsOIkcGXw7aHq0sZOCRFFjGrr7b9+nVZg4UfA4enXCaxm4fUzecU38sWfrNDitGhshuU7rdg==}+ peerDependencies:+ '@types/react': '>=18'+ react: '>=18'+resolution: {integrity: sha512-g93xcyhAVCSt9kV1svqG1clAEdL6k3U+jjuSzfTV7owaSU9Go6Ph8bl25J+jKfKvIGAEYpe4qj++WHJuc9IaeA==}peerDependencies:@@ -7290,6 +7573,12 @@ packages:resolution: {integrity: sha512-+IOGrxl3FZ8ZM9ixCWQZzFRiRn7Rzn9bu3iFHwg/yz4tlOUQgbO4PHLgG+1ZT60zcIV8tief6Qrmyl8qcoJP0g==}+ resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}++ resolution: {integrity: sha512-g/osARvjkBXb6Wo0XvAeXQohVta8i84ACbenPpoSsxTOQH/Ae0/RGP4WZgnMH5pMLpsj4FG7OHmcIcXxpza8eQ==}+resolution: {integrity: sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==}engines: {node: '>= 6'}@@ -7491,6 +7780,9 @@ packages:resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}+resolution: {integrity: sha512-9DWBgrgYZzNghseho0JOuh+5fg9u6QWhAWa51QC7+U5rCheZ/j1DrEZnyE0RBBRqZ9uEXGPgSSM0nky6burpVw==}@@ -7594,6 +7886,9 @@ packages:resolution: {integrity: sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==}+ resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}+resolution: {integrity: sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg==}engines: {node: '>=0.10.0'}@@ -7899,10 +8194,16 @@ packages:resolution: {integrity: sha512-tk2G5R2KRwBd+ZN0zaEXpmzdKyOYksXwywulIX95MBODjSzMIuQnQ3m8JxgbhnL1LeVo7lqQKsYa1O3Htl7K5g==}engines: {node: '>=18'}+ resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}+resolution: {integrity: sha512-WZGXGstmCWgeevgTL54hrCuw1dyMQIzWy7ZfqRJfSmJZBwklI15egmQytFP6bPidmw3M8d5yEowl1niq4vmqZw==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}+resolution: {integrity: sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ==}engines: {node: '>=16'}@@ -8064,6 +8365,24 @@ packages:resolution: {integrity: sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==}+ resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}++ resolution: {integrity: sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==}++ resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}++ resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}++ resolution: {integrity: sha512-L/PqWzfTP9lzzEa6CKs0k2nARxTdZduw3zyh8d2NVBnsyvHjSX4TWse388YrrQKbvI8w20fGjGlhgT96WwKykw==}++ resolution: {integrity: sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==}+resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==}engines: {node: '>= 4.0.0'}@@ -8280,6 +8599,12 @@ packages:resolution: {integrity: sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==}engines: {'0': node >=0.6.0}+ resolution: {integrity: sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw==}++ resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}+resolution: {integrity: sha512-de6HJgzC+TFzOu0NTC4RAIsyf/DY/ibWDYQUcuEA84EMHhcefTUGkjFHKKEJhQN4A+6I0u++kr3l36ZF2d7XRw==}engines: {node: ^18.0.0 || >=20.0.0}@@ -8629,6 +8954,9 @@ packages:react:optional: true+ resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}+snapshots:'@aashutoshrathi/[email protected]': {}@@ -10015,10 +10343,14 @@ snapshots:dependencies:'@babel/runtime': 7.25.6+ '@radix-ui/[email protected]': {}+'@radix-ui/[email protected]':dependencies:'@babel/runtime': 7.25.6+ '@radix-ui/[email protected]': {}+'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.25.6@@ -10116,6 +10448,12 @@ snapshots:optionalDependencies:'@types/react': 18.3.12+ dependencies:+ react: 18.3.1+ optionalDependencies:+ '@types/react': 18.3.12+'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.25.6@@ -10138,6 +10476,12 @@ snapshots:optionalDependencies:'@types/react': 18.3.12+ dependencies:+ react: 18.3.1+ optionalDependencies:+ '@types/react': 18.3.12+'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.25.6@@ -10168,6 +10512,12 @@ snapshots:optionalDependencies:'@types/react': 18.3.12+ dependencies:+ react: 18.3.1+ optionalDependencies:+ '@types/react': 18.3.12+'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.25.6@@ -10353,6 +10703,16 @@ snapshots:'@types/react': 18.3.12'@types/react-dom': 18.3.0+ '@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])+ '@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])+ react: 18.3.1+ react-dom: 18.3.1([email protected])+ optionalDependencies:+ '@types/react': 18.3.12+ '@types/react-dom': 18.3.0+'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.25.6@@ -10363,6 +10723,15 @@ snapshots:'@types/react': 18.3.12'@types/react-dom': 18.3.0+ '@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])+ react: 18.3.1+ react-dom: 18.3.1([email protected])+ optionalDependencies:+ '@types/react': 18.3.12+ '@types/react-dom': 18.3.0+'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.25.6@@ -10411,6 +10780,23 @@ snapshots:'@types/react': 18.3.12'@types/react-dom': 18.3.0+ '@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/number': 1.1.0+ '@radix-ui/primitive': 1.1.0+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])+ '@radix-ui/react-context': 1.1.1(@types/[email protected])([email protected])+ '@radix-ui/react-direction': 1.1.0(@types/[email protected])([email protected])+ '@radix-ui/react-presence': 1.1.1(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])+ '@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])+ react: 18.3.1+ react-dom: 18.3.1([email protected])+ optionalDependencies:+ '@types/react': 18.3.12+ '@types/react-dom': 18.3.0+'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.25.6@@ -10469,6 +10855,13 @@ snapshots:optionalDependencies:'@types/react': 18.3.12+ dependencies:+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])+ react: 18.3.1+ optionalDependencies:+ '@types/react': 18.3.12+'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.25.6@@ -10563,6 +10956,12 @@ snapshots:optionalDependencies:'@types/react': 18.3.12+ dependencies:+ react: 18.3.1+ optionalDependencies:+ '@types/react': 18.3.12+dependencies:'@babel/runtime': 7.25.6@@ -10586,6 +10985,12 @@ snapshots:optionalDependencies:'@types/react': 18.3.12+ dependencies:+ react: 18.3.1+ optionalDependencies:+ '@types/react': 18.3.12+dependencies:'@babel/runtime': 7.25.6@@ -12282,6 +12687,10 @@ snapshots:'@types/d3-transition': 3.0.8'@types/d3-zoom': 3.0.8+ '@types/[email protected]':+ dependencies:+ '@types/ms': 0.7.34+'@types/[email protected]': {}'@types/[email protected]': {}@@ -12298,6 +12707,10 @@ snapshots:'@types/estree': 1.0.6'@types/json-schema': 7.0.15+ '@types/[email protected]':+ dependencies:+ '@types/estree': 1.0.6+'@types/[email protected]': {}'@types/[email protected]': {}@@ -12327,6 +12740,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/unist': 3.0.3+'@types/[email protected]': {}'@types/[email protected]': {}@@ -12366,10 +12783,16 @@ snapshots:'@types/mapbox__point-geometry': 0.1.4'@types/pbf': 3.0.5+ '@types/[email protected]':+ dependencies:+ '@types/unist': 3.0.3+'@types/[email protected]': {}'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:undici-types: 6.19.8@@ -12416,6 +12839,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}++ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -13064,6 +13491,8 @@ snapshots:zod: 3.23.8zod-validation-error: 2.1.0([email protected])+ [email protected]: {}+@@ -13171,6 +13600,8 @@ snapshots:+ [email protected]: {}+dependencies:assertion-error: 1.1.0@@ -13207,6 +13638,14 @@ snapshots:+ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}+dependencies:get-func-name: 2.0.2@@ -13386,6 +13825,8 @@ snapshots:dependencies:delayed-stream: 1.0.0+ [email protected]: {}+@@ -13901,6 +14342,10 @@ snapshots:+ dependencies:+ character-entities: 2.0.2+dependencies:type-detect: 4.0.8@@ -13958,6 +14403,10 @@ snapshots:+ dependencies:+ dequal: 2.0.3+@@ -14464,6 +14913,8 @@ snapshots:+ [email protected]: {}+@@ -14922,6 +15373,30 @@ snapshots:dependencies:function-bind: 1.1.2+ dependencies:+ '@types/estree': 1.0.6+ '@types/hast': 3.0.4+ '@types/unist': 3.0.3+ comma-separated-tokens: 2.0.3+ devlop: 1.1.0+ estree-util-is-identifier-name: 3.0.0+ hast-util-whitespace: 3.0.0+ mdast-util-mdx-expression: 2.0.1+ mdast-util-mdx-jsx: 3.1.3+ mdast-util-mdxjs-esm: 2.0.1+ property-information: 6.5.0+ space-separated-tokens: 2.0.2+ style-to-object: 1.0.6+ unist-util-position: 5.0.0+ vfile-message: 4.0.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/hast': 3.0.4+@@ -14961,6 +15436,8 @@ snapshots:+ [email protected]: {}+dependencies:domelementtype: 2.3.0@@ -15068,6 +15545,13 @@ snapshots:+ [email protected]: {}++ dependencies:+ is-alphabetical: 2.0.1+ is-decimal: 2.0.1+dependencies:call-bind: 1.0.7@@ -15117,6 +15601,8 @@ snapshots:dependencies:has-tostringtag: 1.0.2+ [email protected]: {}+@@ -15145,6 +15631,8 @@ snapshots:dependencies:is-extglob: 2.1.1+ [email protected]: {}+@@ -15165,6 +15653,8 @@ snapshots:+ [email protected]: {}+@@ -15482,6 +15972,8 @@ snapshots:+ [email protected]: {}+dependencies:js-tokens: 4.0.0@@ -15586,6 +16078,95 @@ snapshots:+ dependencies:+ '@types/mdast': 4.0.4+ '@types/unist': 3.0.3+ decode-named-character-reference: 1.0.2+ devlop: 1.1.0+ mdast-util-to-string: 4.0.0+ micromark: 4.0.1+ micromark-util-decode-numeric-character-reference: 2.0.2+ micromark-util-decode-string: 2.0.1+ micromark-util-normalize-identifier: 2.0.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1+ unist-util-stringify-position: 4.0.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/estree-jsx': 1.0.5+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ devlop: 1.1.0+ mdast-util-from-markdown: 2.0.2+ mdast-util-to-markdown: 2.1.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/estree-jsx': 1.0.5+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ '@types/unist': 3.0.3+ ccount: 2.0.1+ devlop: 1.1.0+ mdast-util-from-markdown: 2.0.2+ mdast-util-to-markdown: 2.1.2+ parse-entities: 4.0.1+ stringify-entities: 4.0.4+ unist-util-stringify-position: 4.0.0+ vfile-message: 4.0.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/estree-jsx': 1.0.5+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ devlop: 1.1.0+ mdast-util-from-markdown: 2.0.2+ mdast-util-to-markdown: 2.1.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ unist-util-is: 6.0.0++ dependencies:+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ '@ungap/structured-clone': 1.2.0+ devlop: 1.1.0+ micromark-util-sanitize-uri: 2.0.1+ trim-lines: 3.0.1+ unist-util-position: 5.0.0+ unist-util-visit: 5.0.0+ vfile: 6.0.3++ dependencies:+ '@types/mdast': 4.0.4+ '@types/unist': 3.0.3+ longest-streak: 3.1.0+ mdast-util-phrasing: 4.1.0+ mdast-util-to-string: 4.0.0+ micromark-util-classify-character: 2.0.1+ micromark-util-decode-string: 2.0.1+ unist-util-visit: 5.0.0+ zwitch: 2.0.4++ dependencies:+ '@types/mdast': 4.0.4+@@ -15632,6 +16213,139 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ decode-named-character-reference: 1.0.2+ devlop: 1.1.0+ micromark-factory-destination: 2.0.1+ micromark-factory-label: 2.0.1+ micromark-factory-space: 2.0.1+ micromark-factory-title: 2.0.1+ micromark-factory-whitespace: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-chunked: 2.0.1+ micromark-util-classify-character: 2.0.1+ micromark-util-html-tag-name: 2.0.1+ micromark-util-normalize-identifier: 2.0.1+ micromark-util-resolve-all: 2.0.1+ micromark-util-subtokenize: 2.0.3+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1++ dependencies:+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1++ dependencies:+ devlop: 1.1.0+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1++ dependencies:+ micromark-util-character: 2.1.1+ micromark-util-types: 2.0.1++ dependencies:+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1++ dependencies:+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1++ dependencies:+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1++ dependencies:+ micromark-util-symbol: 2.0.1++ dependencies:+ micromark-util-character: 2.1.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1++ dependencies:+ micromark-util-chunked: 2.0.1+ micromark-util-types: 2.0.1++ dependencies:+ micromark-util-symbol: 2.0.1++ dependencies:+ decode-named-character-reference: 1.0.2+ micromark-util-character: 2.1.1+ micromark-util-decode-numeric-character-reference: 2.0.2+ micromark-util-symbol: 2.0.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ micromark-util-symbol: 2.0.1++ dependencies:+ micromark-util-types: 2.0.1++ dependencies:+ micromark-util-character: 2.1.1+ micromark-util-encode: 2.0.1+ micromark-util-symbol: 2.0.1++ dependencies:+ devlop: 1.1.0+ micromark-util-chunked: 2.0.1+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@types/debug': 4.1.12+ debug: 4.3.6+ decode-named-character-reference: 1.0.2+ devlop: 1.1.0+ micromark-core-commonmark: 2.0.2+ micromark-factory-space: 2.0.1+ micromark-util-character: 2.1.1+ micromark-util-chunked: 2.0.1+ micromark-util-combine-extensions: 2.0.1+ micromark-util-decode-numeric-character-reference: 2.0.2+ micromark-util-encode: 2.0.1+ micromark-util-normalize-identifier: 2.0.1+ micromark-util-resolve-all: 2.0.1+ micromark-util-sanitize-uri: 2.0.1+ micromark-util-subtokenize: 2.0.3+ micromark-util-symbol: 2.0.1+ micromark-util-types: 2.0.1+ transitivePeerDependencies:+ - supports-color+dependencies:braces: 3.0.3@@ -15913,6 +16627,17 @@ snapshots:+ dependencies:+ '@types/unist': 2.0.11+ character-entities: 2.0.2+ character-entities-legacy: 3.0.0+ character-reference-invalid: 2.0.1+ decode-named-character-reference: 1.0.2+ is-alphanumerical: 2.0.1+ is-decimal: 2.0.1+ is-hexadecimal: 2.0.1+dependencies:error-ex: 1.3.2@@ -16381,6 +17106,8 @@ snapshots:object-assign: 4.1.1react-is: 16.13.1+ [email protected]: {}+@@ -16621,6 +17348,23 @@ snapshots:+ dependencies:+ '@types/hast': 3.0.4+ '@types/react': 18.3.12+ devlop: 1.1.0+ hast-util-to-jsx-runtime: 2.3.2+ html-url-attributes: 3.0.1+ mdast-util-to-hast: 13.2.0+ react: 18.3.1+ remark-parse: 11.0.0+ remark-rehype: 11.1.1+ unified: 11.0.5+ unist-util-visit: 5.0.0+ vfile: 6.0.3+ transitivePeerDependencies:+ - supports-color+[email protected](patch_hash=bpeex744nmt6722etqry6essaq)([email protected]([email protected])([email protected]([email protected])))([email protected]):dependencies:@@ -16917,6 +17661,23 @@ snapshots:+ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-from-markdown: 2.0.2+ micromark-util-types: 2.0.1+ unified: 11.0.5+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/hast': 3.0.4+ '@types/mdast': 4.0.4+ mdast-util-to-hast: 13.2.0+ unified: 11.0.5+ vfile: 6.0.3+dependencies:aws-sign2: 0.7.0@@ -17140,6 +17901,8 @@ snapshots:+ [email protected]: {}+dependencies:concat-stream: 1.6.2@@ -17293,6 +18056,11 @@ snapshots:dependencies:safe-buffer: 5.1.2+ dependencies:+ character-entities-html4: 2.1.0+ character-entities-legacy: 3.0.0+dependencies:ansi-regex: 2.1.1@@ -17661,8 +18429,12 @@ snapshots:dependencies:punycode: 2.3.1+ [email protected]: {}++ [email protected]: {}+dependencies:typescript: 5.5.4@@ -17807,6 +18579,39 @@ snapshots:+ dependencies:+ '@types/unist': 3.0.3+ bail: 2.0.2+ devlop: 1.1.0+ extend: 3.0.2+ is-plain-obj: 4.1.0+ trough: 2.2.0+ vfile: 6.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.0++ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.0+ unist-util-visit-parents: 6.0.1+@@ -18214,6 +19019,16 @@ snapshots:core-util-is: 1.0.2extsprintf: 1.3.0+ dependencies:+ '@types/unist': 3.0.3+ unist-util-stringify-position: 4.0.0++ dependencies:+ '@types/unist': 3.0.3+ vfile-message: 4.0.2+dependencies:cac: 6.7.14@@ -18578,3 +19393,5 @@ snapshots:optionalDependencies:'@types/react': 18.3.12react: 18.3.1++ [email protected]: {}diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex e60701e3b7..8fbf776364 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -1001,6 +1001,28 @@ export const UserConfigForm: React.FC = () => {</div>)}/>+ <FormField+ control={form.control}+ name="experimental.chat_sidebar"+ render={({ field }) => (+ <div className="flex flex-col gap-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel className="font-normal">Chat Sidebar</FormLabel>+ <FormControl>+ <Checkbox+ data-testid="chat-sidebar-checkbox"+ checked={field.value === true}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </FormItem>+ <FormDescription>+ Enable experimental chat sidebar to ask questions with an AI+ assistant.+ </FormDescription>+ </div>+ )}+ /></SettingGroup>);}diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsxnew file mode 100644index 0000000000..d83739842d--- /dev/null+++ b/frontend/src/components/chat/chat-panel.tsx@@ -0,0 +1,315 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { useAtom } from "jotai";+import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { ClockIcon, Loader2, PlusIcon } from "lucide-react";+import { chatStateAtom, activeChatAtom, type Chat } from "@/core/ai/state";+import { useState, useRef, useEffect } from "react";+import { generateUUID } from "@/utils/uuid";+import { useChat } from "ai/react";+import { PromptInput } from "../editor/ai/add-cell-with-ai";+import type { ReactCodeMirrorRef } from "@uiw/react-codemirror";+import { Tooltip } from "../ui/tooltip";+import { asURL } from "@/utils/url";+import { API } from "@/core/network/api";+import { cn } from "@/utils/cn";+import { MarkdownRenderer } from "./markdown-renderer";+import { Logger } from "@/utils/Logger";+import { getCodes } from "@/core/codemirror/copilot/getCodes";+import { getAICompletionBody } from "../editor/ai/completion-utils";+import { addMessageToChat } from "@/core/ai/chat-utils";+import { ErrorBanner } from "@/plugins/impl/common/error-banner";++export const ChatPanel = () => {+ const [chatState, setChatState] = useAtom(chatStateAtom);+ const [activeChat, setActiveChat] = useAtom(activeChatAtom);+ const [completionBody, setCompletionBody] = useState<object>({});+ const [newThreadInput, setNewThreadInput] = useState("");+ const newThreadInputRef = useRef<ReactCodeMirrorRef>(null);+ const newMessageInputRef = useRef<ReactCodeMirrorRef>(null);++ const {+ messages,+ input,+ setInput: setInputInternal,+ setMessages,+ append,+ handleSubmit,+ error,+ isLoading,+ reload,+ } = useChat({+ keepLastMessageOnError: true,+ api: asURL("api/ai/chat").toString(),+ headers: API.headers(),+ body: {+ ...completionBody,+ includeOtherCode: getCodes(""),+ },+ streamProtocol: "text",+ onFinish: (message) => {+ if (!chatState.activeChatId) {+ Logger.warn("No active chat");+ return;+ }+ setChatState((prev) =>+ addMessageToChat(prev, prev.activeChatId, "assistant", message.content),+ );+ },+ onError: (error) => {+ Logger.error("An error occurred:", error);+ },+ onResponse: (response) => {+ Logger.debug("Received HTTP response from server:", response);+ },+ });++ const setInput = (newValue: string) => {+ setInputInternal(newValue);+ setCompletionBody(getAICompletionBody(newValue));+ };++ useEffect(() => {+ if (activeChat) {+ setMessages(+ activeChat.messages.map(({ role, content, timestamp }) => ({+ role,+ content,+ id: timestamp.toString(),+ })),+ );+ setInput("");+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [activeChat?.id]);++ const createNewThread = (initialMessage: string) => {+ const newChat: Chat = {+ id: generateUUID(),+ title: `${initialMessage.slice(0, 30)}...`,+ messages: [+ {+ role: "user",+ content: initialMessage,+ timestamp: Date.now(),+ },+ ],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ };++ setChatState((prev) => ({+ chats: [...prev.chats, newChat],+ activeChatId: newChat.id,+ }));++ const nextCompletionBody = getAICompletionBody(initialMessage);+ setCompletionBody(nextCompletionBody);++ setMessages([]);+ append(+ {+ role: "user",+ content: initialMessage,+ },+ {+ body: {+ ...nextCompletionBody,+ includeOtherCode: getCodes(""),+ },+ },+ );+ };++ return (+ <div className="flex flex-col h-[calc(100%-53px)]">+ <div className="flex border-b px-2 py-1 justify-between flex-shrink-0">+ <Tooltip content="New chat">+ <Button+ variant="text"+ size="icon"+ onClick={() => {+ setActiveChat(null);+ setMessages([]);+ setInput("");+ setNewThreadInput("");+ }}+ >+ <PlusIcon className="h-4 w-4" />+ </Button>+ </Tooltip>+ <Popover>+ <Tooltip content="Previous chats">+ <PopoverTrigger asChild={true}>+ <Button variant="text" size="icon">+ <ClockIcon className="h-4 w-4" />+ </Button>+ </PopoverTrigger>+ </Tooltip>+ <PopoverContent className="w-[520px] p-0" align="start" side="right">+ <ScrollArea className="h-[500px] p-4">+ <div className="space-y-4">+ {chatState.chats.map((chat) => (+ <div+ key={chat.id}+ className={cn(+ "p-3 rounded-md cursor-pointer hover:bg-accent",+ chat.id === activeChat?.id && "bg-accent",+ )}+ onClick={() => {+ setActiveChat(chat.id);+ setMessages(+ chat.messages.map(({ role, content, timestamp }) => ({+ role,+ content,+ id: timestamp.toString(),+ })),+ );+ }}+ >+ <div className="font-medium">{chat.title}</div>+ <div className="text-sm text-muted-foreground">+ {new Date(chat.updatedAt).toLocaleString()}+ </div>+ </div>+ ))}+ </div>+ </ScrollArea>+ </PopoverContent>+ </Popover>+ </div>++ <div className="flex-1 px-3 bg-[var(--slate-1)] gap-4 py-3 flex flex-col overflow-y-auto">+ {(!messages || messages.length === 0) && (+ <div className="flex rounded-md border px-1 bg-background">+ <PromptInput+ key="new-thread-input"+ value={newThreadInput}+ placeholder="Ask anything, @ to include context"+ theme="light"+ onClose={() => newThreadInputRef.current?.editor?.blur()}+ onChange={setNewThreadInput}+ onSubmit={() =>+ newThreadInput.trim() && createNewThread(newThreadInput.trim())+ }+ />+ </div>+ )}++ {messages.map((message, idx) => (+ <div+ key={idx}+ className={cn(+ "flex",+ message.role === "user" ? "justify-end" : "justify-start",+ )}+ >+ {message.role === "user" ? (+ <div className="w-[95%] bg-background border p-1 rounded-sm">+ <PromptInput+ key={message.id}+ value={message.content}+ theme="light"+ placeholder="Type your message..."+ onChange={() => {+ // noop+ }}+ onSubmit={(e, newValue) => {+ if (!newValue.trim()) {+ return;+ }+ // Remove all messages from here to the end+ setMessages((messages) => messages.slice(0, idx));+ setCompletionBody(getAICompletionBody(newValue));+ append({+ role: "user",+ content: newValue,+ });+ if (chatState.activeChatId) {+ setChatState((prev) =>+ addMessageToChat(+ prev,+ chatState.activeChatId,+ "user",+ newValue,+ ),+ );+ }+ }}+ onClose={() => {+ // noop+ }}+ />+ </div>+ ) : (+ <div className="w-[95%]">+ <MarkdownRenderer content={message.content} />+ </div>+ )}+ </div>+ ))}++ {isLoading && (+ <div className="flex justify-center py-4">+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ )}++ {error && (+ <div className="flex items-center justify-center space-x-2 mb-4">+ <ErrorBanner error={error} />+ <Button variant="outline" size="sm" onClick={() => reload()}>+ Retry+ </Button>+ </div>+ )}+ </div>++ {messages && messages.length > 0 && (+ <div className="px-2 py-3 border-t relative flex-shrink-0 min-h-[80px]">+ {isLoading && (+ <div className="flex justify-center mb-2 absolute -top-10 left-0 right-0">+ <Button+ variant="secondary"+ size="xs"+ onClick={() => stop()}+ className="text-muted-foreground hover:text-foreground"+ >+ Cancel+ </Button>+ </div>+ )}++ <PromptInput+ value={input}+ onChange={setInput}+ onSubmit={(e, newValue) => {+ if (!newValue.trim()) {+ return;+ }+ handleSubmit(e);+ if (chatState.activeChatId) {+ setChatState((prev) =>+ addMessageToChat(+ prev,+ chatState.activeChatId,+ "user",+ newValue,+ ),+ );+ }+ }}+ onClose={() => newMessageInputRef.current?.editor?.blur()}+ theme="light"+ placeholder="Type your message..."+ />+ </div>+ )}+ </div>+ );+};diff --git a/frontend/src/components/chat/markdown-renderer.tsx b/frontend/src/components/chat/markdown-renderer.tsxnew file mode 100644index 0000000000..1c0310dd88--- /dev/null+++ b/frontend/src/components/chat/markdown-renderer.tsx@@ -0,0 +1,159 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { useTheme } from "@/theme/useTheme";+import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";+import { useCellActions } from "@/core/cells/cells";+import { Button } from "@/components/ui/button";+import { BetweenHorizontalStartIcon } from "lucide-react";+import { EditorView } from "@codemirror/view";+import Markdown, { type Components } from "react-markdown";+import { useEffect, useState } from "react";+import { useLastFocusedCellId } from "@/core/cells/focus";+import { copyToClipboard } from "@/utils/copy";+import { SQLLanguageAdapter } from "@/core/codemirror/language/sql";+import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";+import { useAtomValue } from "jotai";+import { autoInstantiateAtom } from "@/core/config/config";+import { MarkdownLanguageAdapter } from "@/core/codemirror/language/markdown";++const extensions = [EditorView.lineWrapping];++interface CodeBlockProps {+ code: string;+ language: string | undefined;+}++const SUPPORTED_LANGUAGES = new Set([+ "python",+ "markdown",+ "sql",+ "json",+ "yaml",+ "toml",+ "shell",+ "javascript",+ "typescript",+ "jsx",+ "tsx",+ "css",+ "html",+]);++function maybeTransform(+ language: string | undefined,+ code: string,+): {+ language: string;+ code: string;+} {+ // Default to python+ if (!language) {+ return { language: "python", code };+ }+ // Already in the right language+ if (language === "python") {+ return { language, code };+ }+ // Convert to python+ if (language === "sql") {+ return { language: "python", code: SQLLanguageAdapter.fromQuery(code) };+ }+ // Convert to python+ if (language === "markdown") {+ return {+ language: "python",+ code: MarkdownLanguageAdapter.fromMarkdown(code),+ };+ }+ // Run shell commands+ if (language === "shell" || language === "bash") {+ return {+ language: "python",+ code: `import subprocess\nsubprocess.run("${code}")`,+ };+ }+ // Store as a string+ return {+ language: "python",+ code: `_${language} = """\n${code}\n"""`,+ };+}++const CodeBlock = ({ code, language }: CodeBlockProps) => {+ const { theme } = useTheme();+ const { createNewCell } = useCellActions();+ const lastFocusedCellId = useLastFocusedCellId();+ const autoInstantiate = useAtomValue(autoInstantiateAtom);+ const [value, setValue] = useState(code);++ useEffect(() => {+ setValue(code);+ }, [code]);++ const handleInsertCode = () => {+ const result = maybeTransform(language, value);++ if (language === "sql") {+ maybeAddMarimoImport(autoInstantiate, createNewCell, lastFocusedCellId);+ }+ createNewCell({+ code: result.code,+ before: false,+ cellId: lastFocusedCellId ?? "__end__",+ });+ };++ const handleCopyCode = async () => {+ await copyToClipboard(value);+ };++ return (+ <div className="relative">+ <LazyAnyLanguageCodeMirror+ theme={theme === "dark" ? "dark" : "light"}+ // Only show the language if it's supported+ language={+ language && SUPPORTED_LANGUAGES.has(language) ? language : undefined+ }+ className="cm border rounded overflow-hidden"+ extensions={extensions}+ value={value}+ onChange={setValue}+ />+ <div className="flex justify-end mt-2 space-x-2">+ <Button size="xs" variant="outline" onClick={handleCopyCode}>+ Copy+ </Button>+ <Button size="xs" variant="outline" onClick={handleInsertCode}>+ Add to Notebook+ <BetweenHorizontalStartIcon className="ml-2 h-4 w-4" />+ </Button>+ </div>+ </div>+ );+};++const COMPONENTS: Components = {+ code: ({ children, className }) => {+ const language = className?.replace("language-", "");+ if (language && typeof children === "string") {+ return (+ <div>+ <div className="text-xs text-muted-foreground pl-1">{language}</div>+ <CodeBlock code={children.trim()} language={language} />+ </div>+ );+ }+ return <code className={className}>{children}</code>;+ },+};++export const MarkdownRenderer = ({ content }: { content: string }) => {+ return (+ <Markdown+ components={COMPONENTS}+ className="prose dark:prose-invert max-w-none prose-pre:pl-0"+ >+ {content}+ </Markdown>+ );+};diff --git a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts b/frontend/src/components/editor/ai/__tests__/completion-utils.test.tsindex 7eac839940..d3f894d94e 100644--- a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts+++ b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts@@ -63,7 +63,6 @@ describe("getAICompletionBody", () => {},],},- code: "",});});@@ -76,7 +75,6 @@ describe("getAICompletionBody", () => {context: {schema: [],},- code: "",});});@@ -109,7 +107,6 @@ describe("getAICompletionBody", () => {},],},- code: "",});});@@ -150,7 +147,6 @@ describe("getAICompletionBody", () => {},],},- code: "",});});});diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsxindex b77bafebac..f93a16fcf5 100644--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx@@ -71,6 +71,7 @@ export const AddCellWithAI: React.FC<{body: {...completionBody,language: language,+ code: "",},onError: (error) => {toast({@@ -191,10 +192,12 @@ export const AddCellWithAI: React.FC<{interface PromptInputProps {inputRef?: React.RefObject<ReactCodeMirrorRef>;+ placeholder?: string;value: string;+ className?: string;onClose: () => void;onChange: (value: string) => void;- onSubmit: () => void;+ onSubmit: (e: KeyboardEvent | undefined, value: string) => void;theme: ResolvedTheme;}@@ -206,7 +209,9 @@ interface PromptInputProps {*/export const PromptInput = ({value,+ placeholder,inputRef,+ className,onChange,onSubmit,onClose,@@ -286,7 +291,7 @@ export const PromptInput = ({event.metaKey || event.ctrlKey || event.shiftKey;// If no mod key is pressed, submitif (event.key === "Enter" && !pressedModOrShift) {- handleSubmit();+ handleSubmit(event, view.state.doc.toString());event.preventDefault();event.stopPropagation();return true;@@ -349,7 +354,7 @@ export const PromptInput = ({return (<ReactCodeMirrorref={inputRef}- className="flex-1 font-sans overflow-auto my-1"+ className={cn("flex-1 font-sans overflow-auto my-1", className)}autoFocus={true}width="100%"value={value}@@ -357,7 +362,7 @@ export const PromptInput = ({extensions={extensions}onChange={onChange}theme={theme === "dark" ? "dark" : "light"}- placeholder={"Generate with AI"}+ placeholder={placeholder || "Generate with AI"}/>);};diff --git a/frontend/src/components/editor/ai/completion-utils.ts b/frontend/src/components/editor/ai/completion-utils.tsindex 85ab02602e..fe1c537436 100644--- a/frontend/src/components/editor/ai/completion-utils.ts+++ b/frontend/src/components/editor/ai/completion-utils.ts@@ -12,7 +12,7 @@ import { Maps } from "@/utils/maps";*/export function getAICompletionBody(input: string,-): Omit<AiCompletionRequest, "language" | "prompt"> {+): Omit<AiCompletionRequest, "language" | "prompt" | "code"> {const datasets = extractDatasets(input);Logger.debug("Included datasets", datasets);@@ -27,7 +27,6 @@ export function getAICompletionBody(})),})),},- code: "",};}diff --git a/frontend/src/components/editor/cell/cell-context-menu.tsx b/frontend/src/components/editor/cell/cell-context-menu.tsxindex b9c6fa028f..4b1f6973f7 100644--- a/frontend/src/components/editor/cell/cell-context-menu.tsx+++ b/frontend/src/components/editor/cell/cell-context-menu.tsx@@ -23,6 +23,7 @@ import {import { goToDefinitionAtCursorPosition } from "@/core/codemirror/go-to-definition/utils";import { CellOutputId } from "@/core/cells/ids";import { Logger } from "@/utils/Logger";+import { copyToClipboard } from "@/utils/copy";interface Props extends CellActionButtonProps {children: React.ReactNode;@@ -37,7 +38,7 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {{label: "Copy",icon: <CopyIcon size={13} strokeWidth={1.5} />,- handle: () => {+ handle: async () => {// Has selection, use browser copyconst hasSelection = window.getSelection()?.toString();if (hasSelection) {@@ -54,7 +55,7 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {return;}// Copy the output of the cell- navigator.clipboard.writeText(output.textContent ?? "");+ await copyToClipboard(output.textContent ?? "");},},{diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.tsindex b9cdc0ef30..387e54edda 100644--- a/frontend/src/components/editor/chrome/types.ts+++ b/frontend/src/components/editor/chrome/types.ts@@ -13,6 +13,7 @@ import {DatabaseIcon,NotebookPenIcon,BoxIcon,+ BotMessageSquareIcon,} from "lucide-react";export type PanelType =@@ -26,6 +27,7 @@ export type PanelType =| "snippets"| "datasources"| "scratchpad"+ | "chat"| "logs";export interface PanelDescriptor {@@ -73,6 +75,13 @@ export const PANELS: PanelDescriptor[] = [tooltip: "View outline",position: "sidebar",},+ {+ type: "chat",+ Icon: BotMessageSquareIcon,+ tooltip: "Chat with AI",+ position: "sidebar",+ hidden: !getFeatureFlag("chat_sidebar"),+ },{type: "documentation",Icon: TextSearchIcon,diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsxindex e7835f2d0d..b5b34bfa79 100644--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx@@ -28,6 +28,7 @@ import { LazyMount } from "@/components/utils/lazy-mount";import { ScratchpadPanel } from "../panels/scratchpad-panel";import { IfCapability } from "@/core/config/if-capability";import { PackagesPanel } from "../panels/packages-panel";+import { ChatPanel } from "@/components/chat/chat-panel";const LazyTerminal = React.lazy(() => import("@/components/terminal/terminal"));@@ -148,6 +149,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {{selectedPanel === "documentation" && <DocumentationPanel />}{selectedPanel === "snippets" && <SnippetsPanel />}{selectedPanel === "scratchpad" && <ScratchpadPanel />}+ {selectedPanel === "chat" && <ChatPanel />}{selectedPanel === "logs" && <LogsPanel />}</div></Suspense>diff --git a/frontend/src/components/ui/card.tsx b/frontend/src/components/ui/card.tsxnew file mode 100644index 0000000000..030b82cefe--- /dev/null+++ b/frontend/src/components/ui/card.tsx@@ -0,0 +1,83 @@+/* Copyright 2024 Marimo. All rights reserved. */+import * as React from "react";+import { cn } from "@/utils/cn";++const Card = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>+>(({ className, ...props }, ref) => (+ <div+ ref={ref}+ className={cn(+ "rounded-xl border bg-card text-card-foreground shadow",+ className,+ )}+ {...props}+ />+));+Card.displayName = "Card";++const CardHeader = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>+>(({ className, ...props }, ref) => (+ <div+ ref={ref}+ className={cn("flex flex-col space-y-1.5 p-6", className)}+ {...props}+ />+));+CardHeader.displayName = "CardHeader";++const CardTitle = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>+>(({ className, ...props }, ref) => (+ <div+ ref={ref}+ className={cn("font-semibold leading-none tracking-tight", className)}+ {...props}+ />+));+CardTitle.displayName = "CardTitle";++const CardDescription = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>+>(({ className, ...props }, ref) => (+ <div+ ref={ref}+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+));+CardDescription.displayName = "CardDescription";++const CardContent = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>+>(({ className, ...props }, ref) => (+ <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />+));+CardContent.displayName = "CardContent";++const CardFooter = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>+>(({ className, ...props }, ref) => (+ <div+ ref={ref}+ className={cn("flex items-center p-6 pt-0", className)}+ {...props}+ />+));+CardFooter.displayName = "CardFooter";++export {+ Card,+ CardHeader,+ CardFooter,+ CardTitle,+ CardDescription,+ CardContent,+};diff --git a/frontend/src/components/ui/scroll-area.tsx b/frontend/src/components/ui/scroll-area.tsxnew file mode 100644index 0000000000..115891effd--- /dev/null+++ b/frontend/src/components/ui/scroll-area.tsx@@ -0,0 +1,46 @@+/* Copyright 2024 Marimo. All rights reserved. */+import * as React from "react";+import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";+import { cn } from "@/utils/cn";++const ScrollArea = React.forwardRef<+ React.ElementRef<typeof ScrollAreaPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>+>(({ className, children, ...props }, ref) => (+ <ScrollAreaPrimitive.Root+ ref={ref}+ className={cn("relative overflow-hidden", className)}+ {...props}+ >+ <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">+ {children}+ </ScrollAreaPrimitive.Viewport>+ <ScrollBar />+ <ScrollAreaPrimitive.Corner />+ </ScrollAreaPrimitive.Root>+));+ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;++const ScrollBar = React.forwardRef<+ React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,+ React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>+>(({ className, orientation = "vertical", ...props }, ref) => (+ <ScrollAreaPrimitive.ScrollAreaScrollbar+ ref={ref}+ orientation={orientation}+ className={cn(+ "flex touch-none select-none transition-colors",+ orientation === "vertical" &&+ "h-full w-2.5 border-l border-l-transparent p-[1px]",+ orientation === "horizontal" &&+ "h-2.5 flex-col border-t border-t-transparent p-[1px]",+ className,+ )}+ {...props}+ >+ <ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />+ </ScrollAreaPrimitive.ScrollAreaScrollbar>+));+ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;++export { ScrollArea, ScrollBar };diff --git a/frontend/src/core/ai/chat-utils.ts b/frontend/src/core/ai/chat-utils.tsnew file mode 100644index 0000000000..f5a0192c5f--- /dev/null+++ b/frontend/src/core/ai/chat-utils.ts@@ -0,0 +1,32 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { ChatState } from "./state";++export const addMessageToChat = (+ chatState: ChatState,+ chatId: string | null,+ role: "user" | "assistant",+ content: string,+): ChatState => {+ if (!chatId) {+ return chatState;+ }+ return {+ ...chatState,+ chats: chatState.chats.map((chat) =>+ chat.id === chatId+ ? {+ ...chat,+ messages: [+ ...chat.messages,+ {+ role,+ content,+ timestamp: Date.now(),+ },+ ],+ updatedAt: Date.now(),+ }+ : chat,+ ),+ };+};diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.tsindex f81de3dabd..4352904661 100644--- a/frontend/src/core/ai/state.ts+++ b/frontend/src/core/ai/state.ts@@ -7,3 +7,40 @@ export const aiCompletionCellAtom = atom<{initialPrompt?: string;} | null>(null);export const includeOtherCellsAtom = atom<boolean>(false);++export interface Message {+ role: "user" | "assistant" | "function" | "data" | "system" | "tool";+ content: string;+ timestamp: number;+}++export interface Chat {+ id: string;+ title: string;+ messages: Message[];+ createdAt: number;+ updatedAt: number;+}++export interface ChatState {+ chats: Chat[];+ activeChatId: string | null;+}++export const chatStateAtom = atom<ChatState>({+ chats: [],+ activeChatId: null,+});++export const activeChatAtom = atom(+ (get) => {+ const state = get(chatStateAtom);+ return state.chats.find((chat) => chat.id === state.activeChatId);+ },+ (get, set, chatId: string | null) => {+ set(chatStateAtom, (prev) => ({+ ...prev,+ activeChatId: chatId,+ }));+ },+);diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex 22a9d10a2c..3150115916 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -56,6 +56,10 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {readonly type = "markdown";readonly defaultCode = 'mo.md(r"""\n""")';+ static fromMarkdown(markdown: string) {+ return `mo.md(r"""\n${markdown}\n""")`;+ }+lastQuotePrefix: QuotePrefixKind = "";transformIn(pythonCode: string): [string, number] {diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex c07d73f547..a228f1436a 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -11,6 +11,7 @@ export interface ExperimentalFeatures {wasm_layouts: boolean;scratchpad: boolean;multi_column: boolean;+ chat_sidebar: boolean;// Add new feature flags here}@@ -19,6 +20,7 @@ const defaultValues: ExperimentalFeatures = {wasm_layouts: false,scratchpad: true,multi_column: import.meta.env.DEV,+ chat_sidebar: import.meta.env.DEV,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/frontend/src/plugins/impl/code/any-language-editor.tsx b/frontend/src/plugins/impl/code/any-language-editor.tsxindex cba3062360..4001826fa2 100644--- a/frontend/src/plugins/impl/code/any-language-editor.tsx+++ b/frontend/src/plugins/impl/code/any-language-editor.tsx@@ -21,16 +21,19 @@ import type { ResolvedTheme } from "@/theme/useTheme";*/const AnyLanguageCodeMirror: React.FC<ReactCodeMirrorProps & {- language: string;+ language: string | undefined;theme: ResolvedTheme;}> = ({ language, extensions = [], ...props }) => {- const isNotSupported = !(language in langs);+ const isNotSupported = language && !(language in langs);if (isNotSupported) {Logger.warn(`Language ${language} not found in CodeMirror.`);}const finalExtensions = useMemo((): Extension[] => {+ if (!language) {+ return extensions;+ }return [loadLanguage(language as LanguageName), ...extensions].filter(Boolean,);diff --git a/marimo/__init__.py b/marimo/__init__.pyindex 60322d0d81..a5c1445bf2 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -83,6 +83,7 @@ __all__ = []__version__ = "0.9.27"+import marimo._ai as aiimport marimo._islands as islandsfrom marimo._ast.app import Appfrom marimo._ast.cell import Cell@@ -93,7 +94,7 @@ from marimo._output.hypertext import Htmlfrom marimo._output.justify import center, left, rightfrom marimo._output.md import mdfrom marimo._output.show_code import show_code-from marimo._plugins import ai, ui+from marimo._plugins import uifrom marimo._plugins.stateless import mpl, statusfrom marimo._plugins.stateless.accordion import accordionfrom marimo._plugins.stateless.audio import audiodiff --git a/marimo/_plugins/ai/__init__.py b/marimo/_ai/__init__.pysimilarity index 72%rename from marimo/_plugins/ai/__init__.pyrename to marimo/_ai/__init__.pyindex 2a321b916f..4334a8d356 100644--- a/marimo/_plugins/ai/__init__.py+++ b/marimo/_ai/__init__.py@@ -10,8 +10,8 @@ __all__ = ["llm",]-from marimo._plugins.ui._impl.chat import llm-from marimo._plugins.ui._impl.chat.types import (+from marimo._ai import llm+from marimo._ai.types import (ChatAttachment,ChatMessage,ChatModelConfig,diff --git a/marimo/_plugins/ui/_impl/chat/convert.py b/marimo/_ai/convert.pysimilarity index 98%rename from marimo/_plugins/ui/_impl/chat/convert.pyrename to marimo/_ai/convert.pyindex 91fe7c72e5..d23f014f3e 100644--- a/marimo/_plugins/ui/_impl/chat/convert.py+++ b/marimo/_ai/convert.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport base64from typing import Any, Dict, List, TypedDict-from marimo._plugins.ui._impl.chat.types import ChatMessage+from marimo._ai.types import ChatMessagedef convert_to_openai_messages(diff --git a/marimo/_plugins/ui/_impl/chat/llm.py b/marimo/_ai/llm.pysimilarity index 99%rename from marimo/_plugins/ui/_impl/chat/llm.pyrename to marimo/_ai/llm.pyindex 6dba99adb1..9d100990a4 100644--- a/marimo/_plugins/ui/_impl/chat/llm.py+++ b/marimo/_ai/llm.py@@ -4,18 +4,18 @@ from __future__ import annotationsimport osfrom typing import Callable, List, Optional, cast-from marimo._dependencies.dependencies import DependencyManager-from marimo._plugins.ui._impl.chat.convert import (+from marimo._ai.convert import (convert_to_anthropic_messages,convert_to_google_messages,convert_to_groq_messages,convert_to_openai_messages,)-from marimo._plugins.ui._impl.chat.types import (+from marimo._ai.types import (ChatMessage,ChatModel,ChatModelConfig,)+from marimo._dependencies.dependencies import DependencyManagerDEFAULT_SYSTEM_MESSAGE = ("You are a helpful assistant specializing in data science."diff --git a/marimo/_plugins/ui/_impl/chat/types.py b/marimo/_ai/types.pysimilarity index 100%rename from marimo/_plugins/ui/_impl/chat/types.pyrename to marimo/_ai/types.pydiff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.pyindex af17d6e665..763bd25b8e 100644--- a/marimo/_plugins/ui/_impl/chat/chat.py+++ b/marimo/_plugins/ui/_impl/chat/chat.py@@ -5,16 +5,16 @@ import inspectfrom dataclasses import dataclassfrom typing import Any, Callable, Dict, Final, List, Optional, Union, cast+from marimo._ai.types import (+ ChatMessage,+ ChatModelConfig,+ ChatModelConfigDict,+)from marimo._output.formatting import as_htmlfrom marimo._output.md import mdfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElement-from marimo._plugins.ui._impl.chat.types import (- ChatMessage,- ChatModelConfig,- ChatModelConfigDict,-)from marimo._plugins.ui._impl.chat.utils import from_chat_message_dictfrom marimo._runtime.context.kernel_context import KernelRuntimeContextfrom marimo._runtime.context.types import ContextNotInitializedErrordiff --git a/marimo/_plugins/ui/_impl/chat/utils.py b/marimo/_plugins/ui/_impl/chat/utils.pyindex f7532b289b..984f21346c 100644--- a/marimo/_plugins/ui/_impl/chat/utils.py+++ b/marimo/_plugins/ui/_impl/chat/utils.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom typing import List, Optional-from marimo._plugins.ui._impl.chat.types import (+from marimo._ai.types import (ChatAttachment,ChatMessage,ChatMessageDict,diff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.pyindex d90b82d33e..d84adadc8e 100644--- a/marimo/_server/ai/prompts.py+++ b/marimo/_server/ai/prompts.py@@ -3,47 +3,48 @@ from __future__ import annotationsfrom typing import Optional-from marimo._server.models.completion import AiCompletionContext, Language+from marimo._server.models.completion import (+ AiCompletionContext,+ Language,+)++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.",+ ],+ "markdown": [],+ "sql": [+ "The SQL must use duckdb syntax.",+ ],+}class Prompter:def __init__(self,code: str,- include_other_code: str,context: Optional[AiCompletionContext],):self.code = code- self.include_other_code = include_other_codeself.context = context@staticmethoddef get_system_prompt(- language: Language, custom_rules: Optional[str] = None+ *, language: Language, custom_rules: Optional[str] = None) -> str:- language_rules = {- "python": [- "You can only output python code.",- "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().", # noqa: E501- "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.", # noqa: E501- ],- "markdown": ["You can only output markdown."],- "sql": [- "You can only output sql.",- "The SQL must use duckdb syntax.",- ],- }-if language in language_rules:+ all_rules = [f"You can only output {language}."] + language_rules[+ language+ ]rules = "\n".join(- f"{i+1}. {rule}"- for i, rule in enumerate(language_rules[language])+ 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}." # noqa: E501+ f"You are a helpful assistant that can answer questions about {language}."f" Here are your rules: \n{rules}")@@ -54,10 +55,10 @@ class Prompter:else:return "You are a helpful assistant that can answer questions."- def get_prompt(self, user_prompt: str) -> str:+ def get_prompt(self, *, user_prompt: str, include_other_code: str) -> str:prompt = user_prompt- if self.include_other_code:- prompt += f"\n\nCode from other cells:\n{self.include_other_code}"+ if include_other_code:+ prompt += f"\n\nCode from other cells:\n{include_other_code}"if self.code.strip():prompt += f"\n\nCurrent code:\n{self.code}"if self.context and self.context.schema:@@ -69,3 +70,59 @@ class Prompter:schema_info += f"- {schema.name}: {columns}\n"prompt += schema_inforeturn 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:+ 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"+ )++ 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}"++ if custom_rules and custom_rules.strip():+ system_prompt += f"\n\nAdditional rules:\n{custom_rules}"++ if variables:+ system_prompt += (+ f"\n\nVariables to use but not define:\n{variables}"+ )++ if include_other_code:+ system_prompt += (+ 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++ return system_promptdiff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex 146e509cd8..737fc65215 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -1,13 +1,19 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, Generator, Optional+from typing import TYPE_CHECKING, Any, Generator, Optional, castfrom starlette.authentication import requiresfrom starlette.exceptions import HTTPExceptionfrom starlette.responses import StreamingResponsefrom marimo import _loggers+from marimo._ai.convert import (+ convert_to_anthropic_messages,+ convert_to_google_messages,+ convert_to_openai_messages,+)+from marimo._ai.types import ChatMessagefrom marimo._config.config import MarimoConfigfrom marimo._server.ai.prompts import Prompterfrom marimo._server.api.deps import AppState@@ -15,6 +21,7 @@ from marimo._server.api.status import HTTPStatusfrom marimo._server.api.utils import parse_requestfrom marimo._server.models.completion import (AiCompletionRequest,+ ChatRequest,)from marimo._server.router import APIRouter@@ -213,6 +220,28 @@ def make_stream_response(LOGGER.debug(f"Completion content: {original_content}")+def as_stream_response(+ response: OpenAiStream[ChatCompletionChunk]+ | AnthropicStream[RawMessageStreamEvent]+ | GenerateContentResponse,+) -> Generator[str, None, None]:+ original_content = ""+ buffer = ""++ for chunk in response:+ content = get_content(chunk)+ if not content:+ continue++ buffer += content+ original_content += content++ yield buffer+ buffer = ""++ LOGGER.debug(f"Completion content: {original_content}")++def get_google_client(config: MarimoConfig, model: str) -> "GenerativeModel":try:import google.generativeai as genai # type: ignore[import-not-found]@@ -283,11 +312,13 @@ async def ai_completion(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)+ prompter = Prompter(code=body.code, context=body.context)system_prompt = Prompter.get_system_prompt(- body.language, custom_rules=custom_rules+ language=body.language, custom_rules=custom_rules+ )+ prompt = prompter.get_prompt(+ user_prompt=body.prompt, include_other_code=body.include_other_code)- prompt = prompter.get_prompt(body.prompt)model = get_model(config)@@ -348,3 +379,81 @@ async def ai_completion(content=make_stream_response(response),media_type="application/json",)++[email protected]("/chat")+@requires("edit")+async def ai_chat(+ *,+ request: Request,+) -> StreamingResponse:+ """+ Chat endpoint that handles ongoing conversations+ """+ app_state = AppState(request)+ app_state.require_current_session()+ config = app_state.config_manager.get_config(hide_secrets=False)+ body = await parse_request(request, cls=ChatRequest)++ # Get the model from request or fallback to config+ model = body.model or get_model(config)+ 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,+ context=body.context,+ include_other_code=body.include_other_code,+ )++ # Handle different model providers+ if model.startswith("claude"):+ anthropic_client = get_anthropic_client(config)+ response = anthropic_client.messages.create(+ model=model,+ max_tokens=1000,+ messages=cast(Any, convert_to_anthropic_messages(messages)),+ system=system_prompt,+ stream=True,+ temperature=0,+ )++ return StreamingResponse(+ content=as_stream_response(response),+ media_type="application/json",+ )++ if model.startswith("google") or model.startswith("gemini"):+ google_client = get_google_client(config, model)+ response = google_client.generate_content(+ contents=convert_to_google_messages(+ [ChatMessage(role="system", content=system_prompt)] + messages+ ),+ stream=True,+ )++ return StreamingResponse(+ content=as_stream_response(response),+ media_type="application/json",+ )++ # Default to OpenAI+ openai_client = get_openai_client(config)+ response = openai_client.chat.completions.create(+ model=model,+ messages=cast(+ Any,+ convert_to_openai_messages(+ [ChatMessage(role="system", content=system_prompt)] + messages+ ),+ ),+ temperature=0,+ stream=True,+ timeout=15,+ )++ return StreamingResponse(+ content=as_stream_response(response),+ media_type="application/json",+ )diff --git a/marimo/_server/models/completion.py b/marimo/_server/models/completion.pyindex 816edd1ff3..6138f2e10c 100644--- a/marimo/_server/models/completion.py+++ b/marimo/_server/models/completion.py@@ -4,6 +4,8 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom typing import List, Literal, Optional+from marimo._ai.types import ChatMessage+@dataclassclass SchemaColumn:@@ -32,3 +34,12 @@ class AiCompletionRequest:code: strcontext: Optional[AiCompletionContext] = Nonelanguage: Language = "python"+++@dataclass+class ChatRequest:+ messages: List[ChatMessage]+ model: Optional[str] = None+ variables: Optional[List[str]] = None+ context: Optional[AiCompletionContext] = None+ include_other_code: str = ""diff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.pyindex b5188d73bb..7b23376838 100644--- a/marimo/_utils/parse_dataclass.py+++ b/marimo/_utils/parse_dataclass.py@@ -116,9 +116,11 @@ class DataclassParser:not self.allow_unknown_keysand not snake_cased_values.keys() <= types.keys()):+ unknown_keys = snake_cased_values.keys() - types.keys()raise ValueError(- "values in build_dataclass do not match arguments "- "for constructor"+ f"values in build_dataclass do not match arguments "+ f"for constructor. Unknown keys: {unknown_keys}. "+ f"Expected keys: {types.keys()}")transformed = {diff --git a/tests/_plugins/ui/_impl/chat/test_chat_convert.py b/tests/_ai/test_chat_convert.pysimilarity index 98%rename from tests/_plugins/ui/_impl/chat/test_chat_convert.pyrename to tests/_ai/test_chat_convert.pyindex 8182b967bd..4c4bd04068 100644--- a/tests/_plugins/ui/_impl/chat/test_chat_convert.py+++ b/tests/_ai/test_chat_convert.py@@ -5,13 +5,13 @@ from typing import Listimport pytest-from marimo._plugins.ui._impl.chat.convert import (+from marimo._ai.convert import (convert_to_anthropic_messages,convert_to_google_messages,convert_to_groq_messages,convert_to_openai_messages,)-from marimo._plugins.ui._impl.chat.types import (+from marimo._ai.types import (ChatAttachment,ChatMessage,)diff --git a/tests/_plugins/ui/_impl/chat/test_chat_model.py b/tests/_ai/test_chat_model.pysimilarity index 79%rename from tests/_plugins/ui/_impl/chat/test_chat_model.pyrename to tests/_ai/test_chat_model.pyindex 33590ca4c3..4e5179c7b4 100644--- a/tests/_plugins/ui/_impl/chat/test_chat_model.py+++ b/tests/_ai/test_chat_model.py@@ -1,7 +1,7 @@from __future__ import annotations-from marimo._plugins.ui._impl.chat.llm import simple-from marimo._plugins.ui._impl.chat.types import ChatMessage, ChatModelConfig+from marimo._ai.llm import simple+from marimo._ai.types import ChatMessage, ChatModelConfigdef test_simple_model():diff --git a/tests/_plugins/ui/_impl/chat/test_chat.py b/tests/_plugins/ui/_impl/chat/test_chat.pyindex 910510ebc5..737feaba6a 100644--- a/tests/_plugins/ui/_impl/chat/test_chat.py+++ b/tests/_plugins/ui/_impl/chat/test_chat.py@@ -6,14 +6,14 @@ from typing import AsyncIterator, Dict, Listimport pytest-from marimo._output.md import md-from marimo._plugins import ui-from marimo._plugins.ui._impl.chat.chat import SendMessageRequest-from marimo._plugins.ui._impl.chat.types import (+from marimo._ai.types import (ChatMessage,ChatModelConfig,ChatModelConfigDict,)+from marimo._output.md import md+from marimo._plugins import ui+from marimo._plugins.ui._impl.chat.chat import SendMessageRequestfrom marimo._runtime.functions import EmptyArgsfrom marimo._runtime.requests import SetUIElementValueRequestfrom marimo._runtime.runtime import Kerneldiff --git a/tests/_server/ai/snapshots/chat_system_prompts.txt b/tests/_server/ai/snapshots/chat_system_prompts.txtnew file mode 100644index 0000000000..0f0da29198--- /dev/null+++ b/tests/_server/ai/snapshots/chat_system_prompts.txt@@ -0,0 +1,131 @@+++==================== 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.+++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.++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. 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.++Rules for sql:+1. The SQL must use duckdb syntax.++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.+++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.++Rules for sql:+1. The SQL must use duckdb syntax.++Variables to use but not define:+['var1', 'var2']++==================== 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.+++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.++Rules for sql:+1. The SQL must use duckdb syntax.++Available schema:+- df_1: age (int), name (str)+- d2_2: a (int), b (int)+++==================== 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.+++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.++Rules for sql:+1. The SQL must use duckdb syntax.++Code from other cells:+import pandas as pd+import numpy as np++==================== 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.+++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.++Rules for sql:+1. The SQL must use duckdb syntax.++Additional rules:+Always be polite.++Variables to use but not define:+['var1', 'var2']++Code from other cells:+import pandas as pd+import numpy as np++Available schema:+- df_1: age (int), name (str)diff --git a/tests/_server/ai/snapshots/system_prompts.txt b/tests/_server/ai/snapshots/system_prompts.txtindex ad4a699d18..34bfd61428 100644--- a/tests/_server/ai/snapshots/system_prompts.txt+++ b/tests/_server/ai/snapshots/system_prompts.txt@@ -3,7 +3,7 @@==================== python ====================You are a helpful assistant that can answer questions about python. Here are your rules:-1. You can only output python code.+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().@@ -28,7 +28,7 @@ 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.+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().diff --git a/tests/_server/ai/test_prompts.py b/tests/_server/ai/test_prompts.pyindex ebf44a95e8..f798442886 100644--- a/tests/_server/ai/test_prompts.py+++ b/tests/_server/ai/test_prompts.py@@ -23,19 +23,21 @@ def test_system_prompts():result = ""for language in ("python", "markdown", "sql", "idk"):result += _header(language)- result += Prompter.get_system_prompt(cast(Language, language))+ result += Prompter.get_system_prompt(language=cast(Language, language))result += _header("with custom rules")result += Prompter.get_system_prompt(- "python", custom_rules="Always use type hints."+ language="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",+ assert Prompter.get_system_prompt(+ language="python"+ ) == Prompter.get_system_prompt(+ language="python",custom_rules=" ",)@@ -43,37 +45,39 @@ def test_empty_rules():def test_user_prompts():prompt = "Create a pandas dataframe"- result = ""+ result: str = ""result += _header("no code")- result += Prompter(- code="", include_other_code="", context=AiCompletionContext()- ).get_prompt(prompt)+ result += Prompter(code="", context=AiCompletionContext()).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]})",- include_other_code="",context=AiCompletionContext(),- ).get_prompt(prompt)+ ).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]})",- include_other_code="import pandas as pd\nimport numpy as np\n",context=AiCompletionContext(),- ).get_prompt(prompt)+ ).get_prompt(+ user_prompt=prompt,+ include_other_code="import pandas as pd\nimport numpy as np\n",+ )result += _header("with just other code")result += Prompter(code="",- include_other_code="import pandas as pd\nimport numpy as np\n",context=AiCompletionContext(),- ).get_prompt(prompt)+ ).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",- include_other_code="import marimo as mo",context=AiCompletionContext(schema=[SchemaTable(@@ -92,6 +96,65 @@ def test_user_prompts():),],),- ).get_prompt(prompt)+ ).get_prompt(user_prompt=prompt, include_other_code="import marimo as mo")snapshot("user_prompts.txt", result)+++def test_chat_system_prompts():+ result: str = ""+ result += _header("no custom rules")+ result += Prompter.get_chat_system_prompt()++ result += _header("with custom rules")+ result += Prompter.get_chat_system_prompt(custom_rules="Always be polite.")++ result += _header("with variables")+ result += Prompter.get_chat_system_prompt(variables=["var1", "var2"])++ result += _header("with context")+ result += Prompter.get_chat_system_prompt(+ 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"),+ ],+ ),+ ],+ )+ )++ result += _header("with other code")+ result += Prompter.get_chat_system_prompt(+ include_other_code="import pandas as pd\nimport numpy as np\n"+ )++ result += _header("kitchen sink")+ result += Prompter.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(+ schema=[+ SchemaTable(+ name="df_1",+ columns=[+ SchemaColumn("age", "int"),+ SchemaColumn("name", "str"),+ ],+ ),+ ],+ ),+ )++ snapshot("chat_system_prompts.txt", result)diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex a656598b81..601c1bc400 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -553,3 +553,82 @@ class TestStreamResponse(unittest.TestCase):)result = list(make_stream_response(response))assert result == ["print('```nested```')\n"]++ @staticmethod+ @with_session(SESSION_ID)+ @patch("openai.OpenAI")+ def test_chat_without_code(+ client: TestClient, openai_mock: Any+ ) -> None:+ user_config_manager = get_user_config_manager(client)++ oaiclient = MagicMock()+ openai_mock.return_value = oaiclient++ oaiclient.chat.completions.create.return_value = [+ FakeChoices(+ choices=[+ Choice(+ delta=Delta(content="Hello, how can I help you?")+ )+ ]+ )+ ]++ with openai_config(user_config_manager):+ response = client.post(+ "/api/ai/chat",+ headers=HEADERS,+ json={+ "messages": [{"role": "user", "content": "Hello"}],+ "model": "gpt-4-turbo",+ "variables": [],+ "include_other_code": "",+ },+ )+ assert response.status_code == 200, response.text+ # Assert the prompt it was called with+ prompt = oaiclient.chat.completions.create.call_args.kwargs[+ "messages"+ ][1]["content"]+ assert prompt == "Hello"++ @staticmethod+ @with_session(SESSION_ID)+ @patch("openai.OpenAI")+ def test_chat_with_code(client: TestClient, openai_mock: Any) -> None:+ user_config_manager = get_user_config_manager(client)++ oaiclient = MagicMock()+ openai_mock.return_value = oaiclient++ oaiclient.chat.completions.create.return_value = [+ FakeChoices(+ choices=[+ Choice(delta=Delta(content="import pandas as pd"))+ ]+ )+ ]++ with openai_config(user_config_manager):+ response = client.post(+ "/api/ai/chat",+ headers=HEADERS,+ json={+ "messages": [+ {+ "role": "user",+ "content": "Help me create a dataframe",+ }+ ],+ "model": "gpt-4-turbo",+ "variables": [],+ "include_other_code": "import pandas as pd",+ },+ )+ assert response.status_code == 200, response.text+ # Assert the prompt it was called with+ prompt = oaiclient.chat.completions.create.call_args.kwargs[+ "messages"+ ][1]["content"]+ assert prompt == "Help me create a dataframe"