Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: reactive ui.chat, add examples (#2482)

Akshay Agrawale70c106f1591
diff --git a/docs/api/inputs/chat.md b/docs/api/inputs/chat.md
index 86deae6cd2..746e30347c 100644
--- a/docs/api/inputs/chat.md
+++ b/docs/api/inputs/chat.md
@@ -1,5 +1,12 @@
# Chat
+```{admonition} Looking for example notebooks?
+:class: tip
+
+For example notebooks, check out [`examples/ai/chat` on our
+GitHub](https://github.com/marimo-team/marimo/tree/main/examples/ai/chat).
+```
+
```{eval-rst}
.. marimo-embed::
:size: large
@@ -17,7 +24,9 @@
return
```
-The chat UI element provides an interactive chatbot interface for conversations. It can be customized with different models, including built-in AI models or custom functions.
+The chat UI element provides an interactive chatbot interface for
+conversations. It can be customized with different models, including built-in
+AI models from popular providers or custom functions.
```{eval-rst}
.. autoclass:: marimo.ui.chat
@@ -40,6 +49,12 @@ chat = mo.ui.chat(echo_model, prompts=["Hello", "How are you?"])
chat
```
+Here, `messages` is a list of [`ChatMessage`](#marimo.ui.ChatMessage) objects,
+which has `role` (`"user"`, `"assistant"`, or `"system"`) and `content` (the
+message string) attributes; `config` is a
+[`ChatModelConfig`](#marimo.ai.ChatModelConfig) object with various
+configuration parameters, which you are free to ignore.
+
## Using a Built-in AI Model
You can use marimo's built-in AI models, such as OpenAI's GPT:
@@ -48,7 +63,7 @@ You can use marimo's built-in AI models, such as OpenAI's GPT:
import marimo as mo
chat = mo.ui.chat(
- mo.ai.openai(
+ mo.ai.llm.openai(
"gpt-4",
system_message="You are a helpful assistant.",
),
@@ -65,7 +80,8 @@ You can access the chat history using the `value` attribute:
chat.value
```
-This returns a list of `ChatMessage` objects, each containing `role` and `content` attributes.
+This returns a list of [`ChatMessage`](#marimo.ai.ChatMessage) objects, each
+containing `role` and `content` attributes.
```{eval-rst}
.. autoclass:: ChatMessage
@@ -92,11 +108,13 @@ def rag_model(messages, config):
mo.ui.chat(rag_model)
```
-This example demonstrates how you can implement a Retrieval-Augmented Generation (RAG) model within the chat interface.
+This example demonstrates how you can implement a Retrieval-Augmented
+Generation (RAG) model within the chat interface.
## Built-in Models
-marimo provides several built-in AI models that you can use with the chat UI element.
+marimo provides several built-in AI models that you can use with the chat UI
+element.
### OpenAI
@@ -157,9 +175,19 @@ mo.ui.chat(
)
```
+## Types
+
+Chatbots can be implemented with a function that receives a list of
+[`ChatMessage`](#marimo.ai.ChatMessage) objects and a
+[`ChatModelConfig`](#marimo.ai.ChatModelConfig).
+
```{eval-rst}
-.. autoclass:: marimo.ai.llm.google
- :members:
+.. autoclass:: marimo.ai.ChatMessage
+```
- .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.google
+```{eval-rst}
+.. autoclass:: marimo.ai.ChatModelConfig
```
+
+[`mo.ui.chat`](#marimo.ui.chat) can be instantiated with an initial
+configuration with a dictionary conforming to the config.
diff --git a/examples/README.md b/examples/README.md
index 6278c2594d..4d65e0e3a9 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -10,14 +10,14 @@ This folder contains example marimo notebooks.
- ☁️ [`cloud/`](cloud/): using various cloud providers
- ✨ [`misc/`](misc/): miscellenous topical examples
+> [!TIP]
+> New to marimo? Run `marimo tutorial ui` at the command line first!
+
> [!NOTE]
> Submit a
> [pull request](https://github.com/marimo-team/marimo/pulls) to add an example!
> We especially welcome library developers to add examples to `third_party/`.
-> [!Tip]
-> marimo ships with tutorials to help you get started: start with
-> `marimo tutorial intro` at the command line.
## Running examples
diff --git a/examples/ai/README.md b/examples/ai/README.md
index f1d6aead9a..a8cf356bcb 100644
--- a/examples/ai/README.md
+++ b/examples/ai/README.md
@@ -2,6 +2,10 @@
These examples showcase a few simple applications of AI.
+- 💬 [`chat/`](chat/): creating chatbots with marimo, using [`mo.ui.chat`](https://docs.marimo.io/api/inputs/chat.html#marimo.ui.chat)
+- 🛢️ [`data/`](data/): making data labeling and model comparison tools
+- 🍿 [`misc/`](misc/): miscellaneous AI examples
+
> [!TIP]
> Submit a
> [pull request](https://github.com/marimo-team/marimo/pulls) to add an example!
diff --git a/examples/ai/chat/README.md b/examples/ai/chat/README.md
new file mode 100644
index 0000000000..bc868ef282
--- /dev/null
+++ b/examples/ai/chat/README.md
@@ -0,0 +1,30 @@
+# Chat 💬
+
+These examples show how to make chatbots with marimo, using [`mo.ui.chat`](https://docs.marimo.io/api/inputs/chat.html#marimo.ui.chat).
+
+- `custom.py` shows how to make a custom chatbot
+- `openai.py` shows how to make a chatbot powered by OpenAI models
+- `anthropic.py` shows how to make a chatbot powered by Anthropic models
+- `google.py` shows how to make a chatbot powered by Google models like Gemini
+
+Chatbot's in marimo are _reactive_: when the chatbot responds with a message,
+all other cells referencing the chatbot are automatically run or marked
+stale, with the chatbot's response stored in the object's `value` attribute.
+You can use this to make notebooks that respond to the chatbot's response
+in arbitrary ways. For example, you can make agentic notebooks!
+
+## Running examples
+
+The requirements of each notebook are serialized in them as a top-level
+comment. Here are the steps to open an example notebook:
+
+1. [Install marimo](https://docs.marimo.io/getting_started/index.html#installation)
+2. [Install `uv`](https://github.com/astral-sh/uv/?tab=readme-ov-file#installation)
+3. Open an example with `marimo edit --sandbox <notebook.py>`.
+
+> [!TIP]
+> The [`--sandbox` flag](https://docs.marimo.io/guides/editor_features/package_management.html) opens the notebook in an isolated virtual environment,
+> automatically installing the notebook's dependencies 📦
+
+You can also open notebooks without `uv`, with just `marimo edit <notebook.py>`;
+however, you'll need to install the requirements yourself.
diff --git a/examples/ai/chat/anthropic.py b/examples/ai/chat/anthropic.py
new file mode 100644
index 0000000000..8d73258bc3
--- /dev/null
+++ b/examples/ai/chat/anthropic.py
@@ -0,0 +1,85 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "marimo",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.8.22"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Using Anthropic
+
+ This example shows how to use [`mo.ui.chat`](https://docs.marimo.io/api/inputs/chat.html#marimo.ui.chat) to make a chatbot backed by Anthropic.
+ """
+ )
+ return
+
+
+def __(mo):
+ import os
+
+ os_key = os.environ.get("ANTHROPIC_API_KEY")
+ input_key = mo.ui.text(label="Anthropic API key", kind="password")
+ input_key if not os_key else None
+ return input_key, os, os_key
+
+
+def __(input_key, mo, os_key):
+ key = os_key or input_key.value
+
+ mo.stop(
+ not key,
+ mo.md("Please provide your Anthropic API key in the input field."),
+ )
+ return (key,)
+
+
+def __(key, mo):
+ chatbot = mo.ui.chat(
+ mo.ai.llm.anthropic(
+ "claude-3-5-sonnet-20240602",
+ system_message="You are a helpful assistant.",
+ api_key=key,
+ ),
+ prompts=[
+ "Hello",
+ "How are you?",
+ "I'm doing great, how about you?",
+ ],
+ )
+ chatbot
+ return (chatbot,)
+
+
+def __(mo):
+ mo.md("""Access the chatbot's historical messages with `chatbot.value`.""")
+ return
+
+
+def __(chatbot):
+ # chatbot.value is the list of chat messages
+ chatbot.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/ai/chat/custom.py b/examples/ai/chat/custom.py
new file mode 100644
index 0000000000..69ce0090a4
--- /dev/null
+++ b/examples/ai/chat/custom.py
@@ -0,0 +1,61 @@
+import marimo
+
+__generated_with = "0.8.22"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ """
+ # Custom chatbot
+
+ This example shows how to make a custom chatbot: just supply a function that takes two arguments,
+ `messages` and `config`, and returns the chatbot's response. This response can be any object; it
+ doesn't have to be a string!
+ """
+ )
+ return
+
+
+def __(mo):
+ def simple_echo_model(messages, config):
+ """This chatbot echoes what the user says."""
+ # messages is a list of chatbot messages
+ message = messages[-1]
+ # Each message has two fields:
+ # message.role, which may be "user", "assistant", or "system"
+ # message.content: the content of the message
+ return f"You said: {messages[-1].content}!"
+
+ chatbot = mo.ui.chat(
+ simple_echo_model,
+ prompts=["Hello", "How are you?"],
+ show_configuration_controls=False
+ )
+ chatbot
+ return chatbot, simple_echo_model
+
+
+def __(mo):
+ mo.md("""Access the chatbot's historical messages with `chatbot.value`.""")
+ return
+
+
+def __(chatbot):
+ # chatbot.value is the list of chat messages
+ chatbot.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/ai/chat/gemini.py b/examples/ai/chat/gemini.py
new file mode 100644
index 0000000000..be54a2b93d
--- /dev/null
+++ b/examples/ai/chat/gemini.py
@@ -0,0 +1,86 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "marimo",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.8.22"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Using Gemini
+
+ This example shows how to use [`mo.ui.chat`](https://docs.marimo.io/api/inputs/chat.html#marimo.ui.chat) to make a chatbot backed by Gemini.
+ """
+ )
+ return
+
+
+def __(mo):
+ import os
+
+ os_key = os.environ.get("GOOGLE_AI_API_KEY")
+ input_key = mo.ui.text(label="Google AI API key", kind="password")
+ input_key if not os_key else None
+ return input_key, os, os_key
+
+
+def __(input_key, mo, os_key):
+ key = os_key or input_key.value
+
+ mo.stop(
+ not key,
+ mo.md("Please provide your Google AI API key in the input field."),
+ )
+
+ return (key,)
+
+
+def __(key, mo):
+ chatbot = mo.ui.chat(
+ mo.ai.llm.google(
+ "gemini-1.5-pro-latest",
+ system_message="You are a helpful assistant.",
+ api_key=key,
+ ),
+ prompts=[
+ "Hello",
+ "How are you?",
+ "I'm doing great, how about you?",
+ ],
+ )
+ chatbot
+ return (chatbot,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md("""Access the chatbot's historical messages with `chatbot.value`.""")
+ return
+
+
+def __(chatbot):
+ # chatbot.value is the list of chat messages
+ chatbot.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/ai/chat/openai.py b/examples/ai/chat/openai.py
new file mode 100644
index 0000000000..acafb5db6a
--- /dev/null
+++ b/examples/ai/chat/openai.py
@@ -0,0 +1,85 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "marimo",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.8.22"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Using OpenAI
+
+ This example shows how to use [`mo.ui.chat`](https://docs.marimo.io/api/inputs/chat.html#marimo.ui.chat) to make a chatbot backed by OpenAI.
+ """
+ )
+ return
+
+
+def __(mo):
+ import os
+
+ os_key = os.environ.get("OPENAI_API_KEY")
+ input_key = mo.ui.text(label="OpenAI API key", kind="password")
+ input_key if not os_key else None
+ return input_key, os, os_key
+
+
+def __(input_key, mo, os_key):
+ openai_key = os_key or input_key.value
+
+ mo.stop(
+ not openai_key,
+ mo.md("Please set the OPENAI_API_KEY environment variable or provide it in the input field"),
+ )
+ return (openai_key,)
+
+
+def __(mo, openai_key):
+ chatbot = mo.ui.chat(
+ mo.ai.llm.openai(
+ "gpt-4o",
+ system_message="You are a helpful assistant.",
+ api_key=openai_key,
+ ),
+ prompts=[
+ "Hello",
+ "How are you?",
+ "I'm doing great, how about you?",
+ ],
+ )
+ chatbot
+ return (chatbot,)
+
+
+def __(mo):
+ mo.md("""Access the chatbot's historical messages with `chatbot.value`.""")
+ return
+
+
+def __(chatbot):
+ # chatbot.value is the list of chat messages
+ chatbot.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/ai/data_labeler.py b/examples/ai/data/data_labeler.py
similarity index 100%
rename from examples/ai/data_labeler.py
rename to examples/ai/data/data_labeler.py
diff --git a/examples/ai/model_comparison.py b/examples/ai/data/model_comparison.py
similarity index 100%
rename from examples/ai/model_comparison.py
rename to examples/ai/data/model_comparison.py
diff --git a/examples/ai/build_a_superhero.py b/examples/ai/misc/build_a_superhero.py
similarity index 100%
rename from examples/ai/build_a_superhero.py
rename to examples/ai/misc/build_a_superhero.py
diff --git a/examples/ai/micrograd_mlp.py b/examples/ai/misc/micrograd_mlp.py
similarity index 100%
rename from examples/ai/micrograd_mlp.py
rename to examples/ai/misc/micrograd_mlp.py
diff --git a/examples/ai/pdf_question_answer.py b/examples/ai/misc/pdf_question_answer.py
similarity index 100%
rename from examples/ai/pdf_question_answer.py
rename to examples/ai/misc/pdf_question_answer.py
diff --git a/examples/ai/simple_chatbot.py b/examples/ai/simple_chatbot.py
deleted file mode 100644
index 8b18df080c..0000000000
--- a/examples/ai/simple_chatbot.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# /// script
-# requires-python = ">=3.11"
-# dependencies = [
-# "ell-ai==0.0.12",
-# "marimo",
-# "openai==1.50.1",
-# ]
-# ///
-
-import marimo
-
-__generated_with = "0.8.20"
-app = marimo.App(width="medium")
-
-
[email protected](hide_code=True)
-def __(mo):
- mo.md(r"""# Simple chatbot 🤖""")
- return
-
-
[email protected](hide_code=True)
-def __(mo):
- import os
-
- os_key = os.environ.get("OPENAI_API_KEY")
- input_key = mo.ui.text(label="OpenAI API key", kind="password")
- input_key if not os_key else None
- return input_key, os, os_key
-
-
[email protected](hide_code=True)
-def __(input_key, mo, os_key):
- # Initialize a client
- openai_key = os_key or input_key.value
-
- mo.stop(
- not openai_key,
- "Please set the OPENAI_API_KEY environment variable or provide it in the input field",
- )
-
- import ell
- import openai
-
- # Create an openai client
- client = openai.Client(api_key=openai_key)
- return client, ell, openai, openai_key
-
-
-def __(client, ell, mo):
- @ell.simple("gpt-4o-mini-2024-07-18", client=client)
- def _my_model(prompt):
- """You are an annoying little brother, whatever I say, be sassy with your response"""
- return prompt
-
-
- mo.ui.chat(
- mo.ai.llm.simple(_my_model),
- prompts=[
- "Hello",
- "How are you?",
- "I'm doing great, how about you?",
- ],
- )
- return
-
-
-def __():
- import marimo as mo
- return (mo,)
-
-
-if __name__ == "__main__":
- app.run()
diff --git a/examples/ui/README.md b/examples/ui/README.md
index ee55784528..e8c2df4ef3 100644
--- a/examples/ui/README.md
+++ b/examples/ui/README.md
@@ -6,6 +6,9 @@ These examples showcase how to use marimo's built-in UI elements.
> New to marimo? Run `marimo tutorial intro` and `marimo tutorial ui`
> at the command line first!
+_Looking for examples on making chatbots? Check out the [`ai/chat`](../ai/chat)
+examples folder_.
+
## Running examples
The requirements of each notebook are serialized in them as a top-level
diff --git a/marimo/_plugins/ai/__init__.py b/marimo/_plugins/ai/__init__.py
index 1371b8dd98..357404cb5b 100644
--- a/marimo/_plugins/ai/__init__.py
+++ b/marimo/_plugins/ai/__init__.py
@@ -4,7 +4,10 @@
from __future__ import annotations
__all__ = [
+ "ChatMessage",
+ "ChatModelConfig",
"llm",
]
from marimo._plugins.ui._impl.chat import llm
+from marimo._plugins.ui._impl.chat.types import ChatMessage, ChatModelConfig
diff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.py
index 94534c1656..cfb4a18c3b 100644
--- a/marimo/_plugins/ui/_impl/chat/chat.py
+++ b/marimo/_plugins/ui/_impl/chat/chat.py
@@ -15,7 +15,10 @@ from marimo._plugins.ui._impl.chat.types import (
ChatModelConfigDict,
)
from marimo._plugins.ui._impl.chat.utils import from_chat_message_dict
+from marimo._runtime.context.kernel_context import KernelRuntimeContext
+from marimo._runtime.context.types import ContextNotInitializedError
from marimo._runtime.functions import EmptyArgs, Function
+from marimo._runtime.requests import SetUIElementValueRequest
@dataclass
@@ -34,15 +37,17 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):
"""
A chatbot UI element for interactive conversations.
- **Example - Using a custom model.**
+ **Example: Using a custom model.**
- You can define a custom chat model Callable that takes in
- the history of messages and configuration.
-
- The response can be an object, a marimo UI element, or plain text.
+ Define a chatbot by implementing a function that takes a list of
+ `ChatMessage`s and a config object as input, and returns the chat response.
+ The response can be any object, including text, plots, or marimo UI
+ elements.
```python
def my_rag_model(messages, config):
+ # Each message has a `content` attribute, as well as a `role`
+ # attribute ("user", "system", "assistant");
question = messages[-1].content
docs = find_docs(question)
prompt = template(question, docs, messages)
@@ -55,13 +60,14 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):
chat = mo.ui.chat(my_rag_model)
```
- **Example - Using a built-in model.**
+ **Example: Using a built-in model.**
- You can use a built-in model from the `mo.ai` module.
+ Instead of defining a chatbot function, you can use a built-in model from
+ the `mo.ai.llm` module.
```python
chat = mo.ui.chat(
- mo.ai.openai(
+ mo.ai.llm.openai(
"gpt-4o",
system_message="You are a helpful assistant.",
),
@@ -70,17 +76,17 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):
**Attributes.**
- - `value`: the current chat history
+ - `value`: the current chat history, a list of `ChatMessage` objects.
**Initialization Args.**
- - `model`: (Callable[[List[ChatMessage], ChatModelConfig], object]) a
+ - `model`: `(Callable[[List[ChatMessage], ChatModelConfig], object])` a
callable that takes in the chat history and returns a response
- - `prompts`: optional list of prompts to start the conversation
+ - `prompts`: optional list of initial prompts to present to the user
- `on_message`: optional callback function to handle new messages
- `show_configuration_controls`: whether to show the configuration controls
- - `config`: optional ChatModelConfigDict to override the default
- configuration keys include:
+ - `config`: optional `ChatModelConfigDict` to override the default
+ configuration. Keys include:
- `max_tokens`
- `temperature`
- `top_p`
@@ -154,9 +160,25 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):
ChatMessage(role="assistant", content=content)
]
- self._value = self._chat_history
- if self._on_change:
- self._on_change(self._value)
+ from marimo._runtime.context import get_context
+
+ # The frontend doesn't manage state, so we have to manually enqueue
+ # a control request.
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ # For testing ... this should never happen in real usage.
+ self._value = self._chat_history
+ if self._on_change is not None:
+ self._on_change(self._value)
+ else:
+ if isinstance(ctx, KernelRuntimeContext):
+ ctx._kernel.enqueue_control_request(
+ SetUIElementValueRequest(
+ object_ids=[self._id],
+ values=[{"messages": self._chat_history}],
+ )
+ )
return content
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 01242e5ec2..253730d6a7 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -328,6 +328,11 @@ def _launch_pyodide_kernel(
stdin = PyodideStdin(stream) if is_edit_mode else None
debugger = MarimoPdb(stdout=stdout, stdin=stdin) if is_edit_mode else None
+ def _enqueue_control_request(req: ControlRequest) -> None:
+ control_queue.put_nowait(req)
+ if isinstance(req, SetUIElementValueRequest):
+ set_ui_element_queue.put_nowait(req)
+
kernel = Kernel(
cell_configs=configs,
app_metadata=app_metadata,
@@ -338,7 +343,7 @@ def _launch_pyodide_kernel(
module=patches.patch_main_module(
file=app_metadata.filename, input_override=input_override
),
- enqueue_control_request=lambda req: control_queue.put_nowait(req),
+ enqueue_control_request=_enqueue_control_request,
debugger_override=debugger,
user_config=user_config,
)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index dd1279292d..dc161c6adb 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -1960,6 +1960,11 @@ def launch_kernel(
user_config = user_config.copy()
user_config["runtime"]["on_cell_change"] = "autorun"
+ def _enqueue_control_request(req: ControlRequest) -> None:
+ control_queue.put_nowait(req)
+ if isinstance(req, SetUIElementValueRequest):
+ set_ui_element_queue.put_nowait(req)
+
kernel = Kernel(
cell_configs=configs,
app_metadata=app_metadata,
@@ -1972,7 +1977,7 @@ def launch_kernel(
),
debugger_override=debugger,
user_config=user_config,
- enqueue_control_request=lambda req: control_queue.put_nowait(req),
+ enqueue_control_request=_enqueue_control_request,
)
initialize_kernel_context(
kernel=kernel,
diff --git a/tests/_plugins/ui/_impl/chat/test_chat.py b/tests/_plugins/ui/_impl/chat/test_chat.py
index 9b55030fe3..e7f960971d 100644
--- a/tests/_plugins/ui/_impl/chat/test_chat.py
+++ b/tests/_plugins/ui/_impl/chat/test_chat.py
@@ -13,6 +13,9 @@ from marimo._plugins.ui._impl.chat.types import (
ChatModelConfigDict,
)
from marimo._runtime.functions import EmptyArgs
+from marimo._runtime.requests import SetUIElementValueRequest
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
def test_chat_init():
@@ -164,3 +167,37 @@ def test_chat_with_show_configuration_controls():
chat = ui.chat(mock_model, show_configuration_controls=True)
assert chat._component_args["show-configuration-controls"] is True
+
+
+async def test_chat_send_message_enqueues_ui_element_request(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ # assert that the RPC which updates the chatbot history triggers
+ # a SetUIElementValueRequest
+
+ control_requests = []
+ # the RPC uses enqueue_control_request() to trigger the UI Element update
+ k.enqueue_control_request = lambda r: control_requests.append(r)
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ def f(messages, config):
+ return "response"
+
+ chatbot = mo.ui.chat(f)
+ """
+ ),
+ ]
+ )
+
+ assert not control_requests
+ chatbot = k.globals["chatbot"]
+ request = SendMessageRequest(
+ messages=[ChatMessage(role="user", content="Hello")],
+ config=ChatModelConfig(),
+ )
+ chatbot._send_prompt(request)
+ assert len(control_requests) == 1
+ assert isinstance(control_requests[0], SetUIElementValueRequest)