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: persist chat messages (#3878)

Shahmir Varqha794e4098049a
diff --git a/frontend/src/plugins/impl/chat/ChatPlugin.tsx b/frontend/src/plugins/impl/chat/ChatPlugin.tsx
index 7556b8f66d..4ff72ea104 100644
--- a/frontend/src/plugins/impl/chat/ChatPlugin.tsx
+++ b/frontend/src/plugins/impl/chat/ChatPlugin.tsx
@@ -8,8 +8,10 @@ import type { ChatMessage, SendMessageRequest } from "./types";
import { Arrays } from "@/utils/arrays";
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
-type PluginFunctions = {
- get_chat_history: () => Promise<{ messages: ChatMessage[] }>;
+export type PluginFunctions = {
+ get_chat_history: (req: {}) => Promise<{ messages: ChatMessage[] }>;
+ delete_chat_history: (req: {}) => Promise<null>;
+ delete_chat_message: (req: { index: number }) => Promise<null>;
send_prompt: (req: SendMessageRequest) => Promise<string>;
};
@@ -43,6 +45,10 @@ export const ChatPlugin = createPlugin<{ messages: ChatMessage[] }>(
),
}),
),
+ delete_chat_history: rpc.input(z.object({})).output(z.null()),
+ delete_chat_message: rpc
+ .input(z.object({ index: z.number() }))
+ .output(z.null()),
send_prompt: rpc
.input(
z.object({
@@ -81,7 +87,10 @@ export const ChatPlugin = createPlugin<{ messages: ChatMessage[] }>(
maxHeight={props.data.maxHeight}
allowAttachments={props.data.allowAttachments}
config={props.data.config}
- sendPrompt={props.functions.send_prompt}
+ get_chat_history={props.functions.get_chat_history}
+ delete_chat_history={props.functions.delete_chat_history}
+ delete_chat_message={props.functions.delete_chat_message}
+ send_prompt={props.functions.send_prompt}
value={props.value?.messages || Arrays.EMPTY}
setValue={(messages) => props.setValue({ messages })}
/>
diff --git a/frontend/src/plugins/impl/chat/chat-ui.tsx b/frontend/src/plugins/impl/chat/chat-ui.tsx
index 5a77990877..701413fa00 100644
--- a/frontend/src/plugins/impl/chat/chat-ui.tsx
+++ b/frontend/src/plugins/impl/chat/chat-ui.tsx
@@ -6,7 +6,6 @@ import React, { useEffect, useRef } from "react";
import type {
ChatMessage,
ChatConfig,
- SendMessageRequest,
ChatAttachment,
ChatRole,
} from "./types";
@@ -54,14 +53,15 @@ import {
import type { ReactCodeMirrorRef } from "@uiw/react-codemirror";
import { useTheme } from "@/theme/useTheme";
import { moveToEndOfEditor } from "@/core/codemirror/utils";
+import type { PluginFunctions } from "./ChatPlugin";
+import { useAsyncData } from "@/hooks/useAsyncData";
-interface Props {
+interface Props extends PluginFunctions {
prompts: string[];
config: ChatConfig;
showConfigurationControls: boolean;
maxHeight: number | undefined;
allowAttachments: boolean | string[];
- sendPrompt(req: SendMessageRequest): Promise<string>;
value: ChatMessage[];
setValue: (messages: ChatMessage[]) => void;
}
@@ -75,6 +75,17 @@ export const Chatbot: React.FC<Props> = (props) => {
const scrollContainerRef = useRef<HTMLDivElement>(null);
const { theme } = useTheme();
+ const { data: initialMessages } = useAsyncData(async () => {
+ const chatMessages = await props.get_chat_history({});
+ const messages: Message[] = chatMessages.messages.map((message, idx) => ({
+ id: idx.toString(),
+ role: message.role,
+ content: message.content,
+ experimental_attachments: message.attachments,
+ }));
+ return messages;
+ }, []);
+
const {
messages,
setMessages,
@@ -93,7 +104,7 @@ export const Chatbot: React.FC<Props> = (props) => {
messages: Message[];
};
try {
- const response = await props.sendPrompt({
+ const response = await props.send_prompt({
messages: body.messages.map((m) => ({
role: m.role as ChatRole,
content: m.content,
@@ -118,6 +129,7 @@ export const Chatbot: React.FC<Props> = (props) => {
return new Response(strippedError, { status: 400 });
}
},
+ initialMessages: initialMessages,
onFinish: (message, { usage, finishReason }) => {
setFiles(undefined);
@@ -137,7 +149,11 @@ export const Chatbot: React.FC<Props> = (props) => {
});
const handleDelete = (id: string) => {
- setMessages(messages.filter((message) => message.id !== id));
+ const index = messages.findIndex((message) => message.id === id);
+ if (index !== -1) {
+ props.delete_chat_message({ index });
+ setMessages((prev) => prev.filter((message) => message.id !== id));
+ }
};
const renderAttachment = (attachment: ChatAttachment) => {
@@ -238,6 +254,7 @@ export const Chatbot: React.FC<Props> = (props) => {
onClick={() => {
setMessages([]);
props.setValue([]);
+ props.delete_chat_history({});
}}
>
<Trash2Icon className="h-3 w-3" />
diff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.py
index 4169cd979c..6578d96045 100644
--- a/marimo/_plugins/ui/_impl/chat/chat.py
+++ b/marimo/_plugins/ui/_impl/chat/chat.py
@@ -33,6 +33,11 @@ class GetChatHistoryResponse:
messages: List[ChatMessage]
+@dataclass
+class DeleteChatMessageRequest:
+ index: int
+
+
@mddoc
class chat(UIElement[Dict[str, Any], List[ChatMessage]]):
"""A chatbot UI element for interactive conversations.
@@ -157,6 +162,16 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):
arg_cls=EmptyArgs,
function=self._get_chat_history,
),
+ Function(
+ name="delete_chat_history",
+ arg_cls=EmptyArgs,
+ function=self._delete_chat_history,
+ ),
+ Function(
+ name="delete_chat_message",
+ arg_cls=DeleteChatMessageRequest,
+ function=self._delete_chat_message,
+ ),
Function(
name="send_prompt",
arg_cls=SendMessageRequest,
@@ -168,6 +183,17 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):
def _get_chat_history(self, _args: EmptyArgs) -> GetChatHistoryResponse:
return GetChatHistoryResponse(messages=self._chat_history)
+ def _delete_chat_history(self, _args: EmptyArgs) -> None:
+ self._value = self._chat_history = []
+
+ def _delete_chat_message(self, args: DeleteChatMessageRequest) -> None:
+ index = args.index
+ if index < 0 or index >= len(self._chat_history):
+ raise ValueError("Invalid message index")
+
+ del self._chat_history[index]
+ self._value = self._chat_history
+
async def _send_prompt(self, args: SendMessageRequest) -> str:
messages = args.messages
diff --git a/tests/_plugins/ui/_impl/chat/test_chat.py b/tests/_plugins/ui/_impl/chat/test_chat.py
index 26b4c980fd..32d7465592 100644
--- a/tests/_plugins/ui/_impl/chat/test_chat.py
+++ b/tests/_plugins/ui/_impl/chat/test_chat.py
@@ -13,7 +13,10 @@ from marimo._ai._types import (
)
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.chat import (
+ DeleteChatMessageRequest,
+ SendMessageRequest,
+)
from marimo._runtime.functions import EmptyArgs
from marimo._runtime.requests import SetUIElementValueRequest
from marimo._runtime.runtime import Kernel
@@ -136,6 +139,9 @@ def test_chat_get_history():
return "Mock response"
chat = ui.chat(mock_model)
+ history = chat._get_chat_history(EmptyArgs())
+ assert history.messages == []
+
chat._chat_history = [
ChatMessage(role="user", content="Hello"),
ChatMessage(role="assistant", content="Hi there!"),
@@ -149,6 +155,51 @@ def test_chat_get_history():
assert history.messages[1].content == "Hi there!"
+def test_chat_delete_history():
+ def mock_model(
+ messages: List[ChatMessage], config: ChatModelConfig
+ ) -> str:
+ del messages, config
+ return "Mock response"
+
+ chat = ui.chat(mock_model)
+ chat._delete_chat_history(EmptyArgs())
+ assert chat._chat_history == []
+ assert chat.value == []
+
+ chat._chat_history = [
+ ChatMessage(role="user", content="Hello"),
+ ChatMessage(role="assistant", content="Hi there!"),
+ ]
+
+ chat._delete_chat_history(EmptyArgs())
+ assert chat._chat_history == []
+ assert chat.value == []
+
+
+def test_chat_delete_message():
+ def mock_model(
+ messages: List[ChatMessage], config: ChatModelConfig
+ ) -> str:
+ del messages, config
+ return "Mock response"
+
+ chat = ui.chat(mock_model)
+
+ with pytest.raises(ValueError, match="Invalid message index"):
+ chat._delete_chat_message(DeleteChatMessageRequest(index=0))
+
+ chat._chat_history = [
+ ChatMessage(role="user", content="Hello"),
+ ChatMessage(role="assistant", content="Hi there!"),
+ ]
+
+ chat._delete_chat_message(DeleteChatMessageRequest(index=0))
+ assert len(chat._chat_history) == 1
+ assert chat._chat_history[0].role == "assistant"
+ assert chat._chat_history[0].content == "Hi there!"
+
+
def test_chat_convert_value():
def mock_model(
messages: List[ChatMessage], config: ChatModelConfig