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
feat: attachment support in mo.ui.chat (#2493)
Myles Scolnickf711398e1112
diff --git a/docs/api/inputs/chat.md b/docs/api/inputs/chat.mdindex 203019d8c6..a5ed5a9eac 100644--- a/docs/api/inputs/chat.md+++ b/docs/api/inputs/chat.md@@ -81,7 +81,7 @@ chat.value```This returns a list of [`ChatMessage`](#marimo.ai.ChatMessage) objects, each-containing `role` and `content` attributes.+containing `role`, `content`, and optional `attachments` attributes.```{eval-rst}.. autoclass:: ChatMessage@@ -111,6 +111,38 @@ mo.ui.chat(rag_model)This example demonstrates how you can implement a Retrieval-AugmentedGeneration (RAG) model within the chat interface.+## Templated Prompts++You can pass sample prompts to `mo.ui.chat` to allow users to select from a+list of predefined prompts. By including a `{{var}}` in the prompt, you can+dynamically insert values into the prompt; a form will be generated to allow+users to fill in the variables.++```python+mo.ui.chat(+ mo.ai.llm.openai("gpt-4o"),+ prompts=[+ "What is the capital of France?",+ "What is the capital of Germany?",+ "What is the capital of {{country}}?",+ ],+)+```++## Including Attachments++You can allow users to upload attachments to their messages by passing an+`allow_attachments` parameter to `mo.ui.chat`.++```python+mo.ui.chat(+ rag_model,+ allow_attachments=["image/png", "image/jpeg"],+ # or True for any attachment type+ # allow_attachments=True,+)+```+## Built-in Modelsmarimo provides several built-in AI models that you can use with the chat UIdiff --git a/examples/ai/chat/anthropic_example.py b/examples/ai/chat/anthropic_example.pyindex 3e9f056295..b1bff6fc77 100644--- a/examples/ai/chat/anthropic_example.py+++ b/examples/ai/chat/anthropic_example.py@@ -58,6 +58,10 @@ def __(key, mo):system_message="You are a helpful assistant.",api_key=key,),+ allow_attachments=[+ "image/png",+ "image/jpeg"+ ],prompts=["Hello","How are you?",diff --git a/examples/ai/chat/openai_example.py b/examples/ai/chat/openai_example.pyindex 8a590142a3..3f1d113888 100644--- a/examples/ai/chat/openai_example.py+++ b/examples/ai/chat/openai_example.py@@ -57,6 +57,10 @@ def __(mo, openai_key):"gpt-4o",system_message="You are a helpful assistant.",api_key=openai_key,+ allow_attachments=[+ "image/png",+ "image/jpeg"+ ],),prompts=["Hello",diff --git a/frontend/src/plugins/impl/chat/ChatPlugin.tsx b/frontend/src/plugins/impl/chat/ChatPlugin.tsxindex a4ba1335fe..99e942892b 100644--- a/frontend/src/plugins/impl/chat/ChatPlugin.tsx+++ b/frontend/src/plugins/impl/chat/ChatPlugin.tsx@@ -26,6 +26,7 @@ export const ChatPlugin = createPlugin<ChatMessage[]>("marimo-chatbot")frequencyPenalty: z.number().default(0),presencePenalty: z.number().default(0),}),+ allowAttachments: z.union([z.boolean(), z.string().array()]),}),).withFunctions<PluginFunctions>({@@ -46,6 +47,15 @@ export const ChatPlugin = createPlugin<ChatMessage[]>("marimo-chatbot")z.object({role: z.enum(["system", "user", "assistant"]),content: z.string(),+ attachments: z+ .array(+ z.object({+ name: z.string().optional(),+ contentType: z.string().optional(),+ url: z.string(),+ }),+ )+ .optional(),}),),config: z.object({@@ -65,6 +75,7 @@ export const ChatPlugin = createPlugin<ChatMessage[]>("marimo-chatbot")<Chatbotprompts={props.data.prompts}showConfigurationControls={props.data.showConfigurationControls}+ allowAttachments={props.data.allowAttachments}config={props.data.config}sendPrompt={props.functions.send_prompt}value={props.value || Arrays.EMPTY}diff --git a/frontend/src/plugins/impl/chat/chat-ui.tsx b/frontend/src/plugins/impl/chat/chat-ui.tsxindex e884605b6d..1a89f4bce0 100644--- a/frontend/src/plugins/impl/chat/chat-ui.tsx+++ b/frontend/src/plugins/impl/chat/chat-ui.tsx@@ -2,16 +2,25 @@import { Spinner } from "@/components/icons/spinner";import { Logger } from "@/utils/Logger";import { type Message, useChat } from "ai/react";-import React, { useEffect } from "react";-import type { ChatMessage, ChatConfig, SendMessageRequest } from "./types";+import React, { useEffect, useRef } from "react";+import type {+ ChatMessage,+ ChatConfig,+ SendMessageRequest,+ ChatAttachment,+ ChatRole,+} from "./types";import { ErrorBanner } from "../common/error-banner";-import { Button } from "@/components/ui/button";+import { Button, buttonVariants } from "@/components/ui/button";import {BotMessageSquareIcon,ClipboardIcon,HelpCircleIcon,SendIcon,Trash2Icon,+ DownloadIcon,+ PaperclipIcon,+ X,} from "lucide-react";import { cn } from "@/utils/cn";import { toast } from "@/components/ui/use-toast";@@ -42,6 +51,7 @@ interface Props {prompts: string[];config: ChatConfig;showConfigurationControls: boolean;+ allowAttachments: boolean | string[];sendPrompt(req: SendMessageRequest): Promise<string>;value: ChatMessage[];setValue: (messages: ChatMessage[]) => void;@@ -50,6 +60,8 @@ interface Props {export const Chatbot: React.FC<Props> = (props) => {const inputRef = React.useRef<HTMLInputElement>(null);const [config, setConfig] = useState<ChatConfig>(props.config);+ const [files, setFiles] = useState<FileList | undefined>(undefined);+ const fileInputRef = useRef<HTMLInputElement>(null);const {messages,@@ -67,11 +79,15 @@ export const Chatbot: React.FC<Props> = (props) => {streamProtocol: "text",fetch: async (_url, request) => {const body = JSON.parse(request?.body as string) as {- messages: ChatMessage[];+ messages: Message[];};try {const response = await props.sendPrompt({- ...body,+ messages: body.messages.map((m) => ({+ role: m.role as ChatRole,+ content: m.content,+ attachments: m.experimental_attachments,+ })),config: {max_tokens: config.maxTokens,temperature: config.temperature,@@ -92,6 +108,11 @@ export const Chatbot: React.FC<Props> = (props) => {}},onFinish: (message, { usage, finishReason }) => {+ setFiles(undefined);++ if (fileInputRef.current) {+ fileInputRef.current.value = "";+ }Logger.debug("Finished streaming message:", message);Logger.debug("Token usage:", usage);Logger.debug("Finish reason:", finishReason);@@ -108,12 +129,70 @@ export const Chatbot: React.FC<Props> = (props) => {setMessages(messages.filter((message) => message.id !== id));};+ const renderAttachment = (attachment: ChatAttachment) => {+ if (attachment.contentType?.startsWith("image")) {+ return (+ <img+ src={attachment.url}+ alt={attachment.name || "Attachment"}+ className="object-contain rounded-sm"+ width={100}+ height={100}+ />+ );+ }++ return (+ <a+ href={attachment.url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-link hover:underline"+ >+ {attachment.name || "Attachment"}+ </a>+ );+ };+const renderMessage = (message: Message) => {- return message.role === "assistant"- ? renderHTML({ html: message.content })- : message.content;+ const content =+ message.role === "assistant"+ ? renderHTML({ html: message.content })+ : message.content;++ const attachments = message.experimental_attachments;++ return (+ <>+ {content}+ {attachments && attachments.length > 0 && (+ <div className="mt-2">+ {attachments.map((attachment, index) => (+ <div key={index} className="flex items-baseline gap-2 ">+ {renderAttachment(attachment)}+ <a+ className={buttonVariants({+ variant: "text",+ size: "icon",+ })}+ href={attachment.url}+ download={attachment.name}+ >+ <DownloadIcon className="size-3" />+ </a>+ </div>+ ))}+ </div>+ )}+ </>+ );};+ const shouldShowAttachments =+ (Array.isArray(props.allowAttachments) &&+ props.allowAttachments.length > 0) ||+ props.allowAttachments === true;+return (<div className="flex flex-col h-full bg-[var(--slate-1)] rounded-lg shadow border border-[var(--slate-6)]"><div className="flex justify-end p-1">@@ -197,8 +276,12 @@ export const Chatbot: React.FC<Props> = (props) => {)}<form- onSubmit={handleSubmit}- className="flex w-full border-t border-[var(--slate-6)] px-2 py-1"+ onSubmit={(evt) => {+ handleSubmit(evt, {+ experimental_attachments: files,+ });+ }}+ className="flex w-full border-t border-[var(--slate-6)] px-2 py-1 items-center">{props.showConfigurationControls && (<ConfigPopup config={config} onChange={setConfig} />@@ -223,9 +306,69 @@ export const Chatbot: React.FC<Props> = (props) => {ref={inputRef}value={input}onChange={handleInputChange}- className="flex w-full outline-none bg-transparent ml-2 text-[var(--slate-12)]"+ className="flex w-full outline-none bg-transparent ml-2 text-[var(--slate-12)] mr-2"placeholder="Type your message..."/>+ {files && files.length === 1 && (+ <span+ title={files[0].name}+ className="text-sm text-[var(--slate-11)] truncate flex-shrink-0 w-24"+ >+ {files[0].name}+ </span>+ )}+ {files && files.length > 1 && (+ <span+ title={[...files].map((f) => f.name).join("\n")}+ className="text-sm text-[var(--slate-11)] truncate flex-shrink-0"+ >+ {files.length} files+ </span>+ )}+ {files && files.length > 0 && (+ <Button+ type="button"+ variant="text"+ size="sm"+ onClick={() => {+ setFiles(undefined);++ if (fileInputRef.current) {+ fileInputRef.current.value = "";+ }+ }}+ >+ <X className="size-3" />+ </Button>+ )}+ {shouldShowAttachments && (+ <>+ <Button+ type="button"+ variant="text"+ size="sm"+ onClick={() => fileInputRef.current?.click()}+ >+ <PaperclipIcon className="h-4" />+ </Button>+ <input+ type="file"+ ref={fileInputRef}+ className="hidden"+ multiple={true}+ accept={+ Array.isArray(props.allowAttachments)+ ? props.allowAttachments.join(",")+ : undefined+ }+ onChange={(event) => {+ if (event.target.files) {+ setFiles(event.target.files);+ }+ }}+ />+ </>+ )}<Buttontype="submit"disabled={isLoading || !input}diff --git a/frontend/src/plugins/impl/chat/types.ts b/frontend/src/plugins/impl/chat/types.tsindex eb8f53f93f..d953691af8 100644--- a/frontend/src/plugins/impl/chat/types.ts+++ b/frontend/src/plugins/impl/chat/types.ts@@ -1,7 +1,16 @@/* Copyright 2024 Marimo. All rights reserved. */+export type ChatRole = "system" | "user" | "assistant";+export interface ChatMessage {- role: "system" | "user" | "assistant";+ role: ChatRole;content: string;+ attachments?: ChatAttachment[];+}++export interface ChatAttachment {+ name?: string;+ contentType?: string;+ url: string;}export interface SendMessageRequest {diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pyindex 6bef6dee45..b6de2fbd84 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/file_path.py@@ -53,6 +53,9 @@ class LocalFileReader(FileReader):return not is_url(name)def read(self, name: str) -> Tuple[str, str]:+ # Is directory+ if os.path.isdir(name):+ return "", os.path.basename(name)with open(name, "r") as f:content = f.read()return content, os.path.basename(name)diff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.pyindex d489745831..78e21c1c9b 100644--- a/marimo/_plugins/ui/_impl/chat/chat.py+++ b/marimo/_plugins/ui/_impl/chat/chat.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport inspectfrom dataclasses import dataclass-from typing import Any, Callable, Dict, Final, List, Optional, cast+from typing import Any, Callable, Dict, Final, List, Optional, Union, castfrom marimo._output.formatting import as_htmlfrom marimo._output.rich_help import mddoc@@ -93,6 +93,17 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):)```+ You can also allow the user to include attachments in their messages.++ ```python+ chat = mo.ui.chat(+ mo.ai.llm.openai(+ "gpt-4o",+ ),+ allow_attachments=["image/png", "image/jpeg"],+ )+ ```+**Attributes.**- `value`: the current chat history, a list of `ChatMessage` objects.@@ -112,6 +123,8 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):- `top_k`- `frequency_penalty`- `presence_penalty`+ - `allow_attachments`: (bool | List[str]) allow attachments. True for any+ attachments types, or pass a list of mime types"""_name: Final[str] = "marimo-chatbot"@@ -124,6 +137,7 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):on_message: Optional[Callable[[List[ChatMessage]], None]] = None,show_configuration_controls: bool = False,config: Optional[ChatModelConfigDict] = None,+ allow_attachments: Union[bool, List[str]] = False,) -> None:self._model = modelself._chat_history: List[ChatMessage] = []@@ -137,6 +151,7 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):"prompts": prompts,"show-configuration-controls": show_configuration_controls,"config": cast(JSONType, config or {}),+ "allow-attachments": allow_attachments,},functions=(Function(diff --git a/marimo/_plugins/ui/_impl/chat/convert.py b/marimo/_plugins/ui/_impl/chat/convert.pyindex 2a5c709954..5580462b1e 100644--- a/marimo/_plugins/ui/_impl/chat/convert.py+++ b/marimo/_plugins/ui/_impl/chat/convert.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Dict, List+import base64+from typing import Any, Dict, List, TypedDictfrom marimo._plugins.ui._impl.chat.types import ChatMessage@@ -18,16 +19,23 @@ def convert_to_openai_messages(if message.attachments:for attachment in message.attachments:- if attachment.content_type.startswith("image"):+ content_type = attachment.content_type or "text/plain"++ if content_type.startswith("image"):parts.append({"type": "image_url","image_url": {"url": attachment.url},})-- elif attachment.content_type.startswith("text"):- parts.append({"type": "text", "text": attachment.url})+ elif content_type.startswith("text"):+ parts.append(+ {"type": "text", "text": _extract_text(attachment.url)}+ )+ else:+ raise ValueError(+ f"Unsupported content type {content_type}"+ )openai_messages.append({"role": message.role, "content": parts})@@ -46,41 +54,81 @@ def convert_to_anthropic_messages(if message.attachments:for attachment in message.attachments:- if attachment.content_type.startswith("image"):+ content_type = attachment.content_type or "text/plain"+ if content_type.startswith("image"):parts.append({- "type": "image_url",- "image_url": {"url": attachment.url},+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": content_type,+ "data": _extract_data(attachment.url),+ },})- elif attachment.content_type.startswith("text"):- parts.append({"type": "text", "text": attachment.url})+ elif content_type.startswith("text"):+ parts.append(+ {"type": "text", "text": _extract_text(attachment.url)}+ )++ else:+ raise ValueError(+ f"Unsupported content type {content_type}"+ )anthropic_messages.append({"role": message.role, "content": parts})return anthropic_messages+# Matches from google.generativeai.types import content_types+class BlobDict(TypedDict):+ mime_type: str+ data: bytes++def convert_to_google_messages(messages: List[ChatMessage],) -> List[Dict[Any, Any]]:google_messages: List[Dict[Any, Any]] = []for message in messages:- content = message.content+ parts: List[str | BlobDict] = [message.content]if message.attachments:for attachment in message.attachments:- if attachment.content_type.startswith("image"):- content += f"\n[Image: {attachment.url}]"- elif attachment.content_type.startswith("text"):- content += f"\n[Text: {attachment.url}]"+ content_type = attachment.content_type or "text/plain"++ parts.append(+ {+ "mime_type": content_type,+ "data": base64.b64decode(+ _extract_data(attachment.url)+ ),+ }+ )google_messages.append({"role": "user" if message.role == "user" else "model",- "parts": [content],+ "parts": parts,})return google_messages+++def _extract_text(url: str) -> str:+ if url.startswith("data:"):+ # extract base64 encoding from url+ data = url.split(",")[1]+ return base64.b64decode(data).decode("utf-8")+ else:+ return url+++def _extract_data(url: str) -> str:+ if url.startswith("data:"):+ return url.split(",")[1]+ else:+ return urldiff --git a/marimo/_plugins/ui/_impl/chat/types.py b/marimo/_plugins/ui/_impl/chat/types.pyindex 0ae4a3e26b..faa5612fb7 100644--- a/marimo/_plugins/ui/_impl/chat/types.py+++ b/marimo/_plugins/ui/_impl/chat/types.py@@ -2,14 +2,15 @@from __future__ import annotationsimport abc+import mimetypesfrom dataclasses import dataclassfrom typing import List, Literal, Optional, TypedDictclass ChatAttachmentDict(TypedDict):- name: str- content_type: strurl: str+ content_type: Optional[str]+ name: Optional[str]class ChatMessageDict(TypedDict):@@ -33,16 +34,20 @@ class ChatModelConfigDict(TypedDict, total=False):@dataclassclass ChatAttachment:+ # The URL of the attachment. It can either be a URL to a hosted file or a+ # [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs).+ url: str+# The name of the attachment, usually the file name.- name: str+ name: str = "attachment"# A string indicating the [media type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).# By default, it's extracted from the pathname's extension.- content_type: str+ content_type: Optional[str] = None- # The URL of the attachment. It can either be a URL to a hosted file or a- # [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs).- url: str+ def __post_init__(self) -> None:+ if self.content_type is None:+ self.content_type = mimetypes.guess_type(self.url)[0]@dataclassdiff --git a/marimo/_plugins/ui/_impl/chat/utils.py b/marimo/_plugins/ui/_impl/chat/utils.pyindex ffe1fd8d40..f7532b289b 100644--- a/marimo/_plugins/ui/_impl/chat/utils.py+++ b/marimo/_plugins/ui/_impl/chat/utils.py@@ -19,7 +19,7 @@ def from_chat_message_dict(d: ChatMessageDict) -> ChatMessage:if attachments_dict is not None:attachments = [ChatAttachment(- name=attachment["name"],+ name=attachment["name"] or "attachment",content_type=attachment["content_type"],url=attachment["url"],)diff --git a/tests/_plugins/ui/_impl/chat/test_chat_convert.py b/tests/_plugins/ui/_impl/chat/test_chat_convert.pyindex a650b1d35d..8f23d5d9e4 100644--- a/tests/_plugins/ui/_impl/chat/test_chat_convert.py+++ b/tests/_plugins/ui/_impl/chat/test_chat_convert.py@@ -1,5 +1,6 @@from __future__ import annotations+import base64from typing import Listimport pytest@@ -26,12 +27,12 @@ def sample_messages() -> List[ChatMessage]:ChatAttachment(name="image.png",content_type="image/png",- url="http://example.com/image.png",+ url=f"data:image/png;base64,{base64.b64encode('hello'.encode())}",),ChatAttachment(name="text.txt",content_type="text/plain",- url="http://example.com/text.txt",+ url="data:text/csv;base64,QQoxCjIKMwo=",),],),@@ -57,11 +58,11 @@ def test_convert_to_openai_messages(sample_messages: List[ChatMessage]):}assert result[0]["content"][1] == {"type": "image_url",- "image_url": {"url": "http://example.com/image.png"},+ "image_url": {"url": "data:image/png;base64,b'aGVsbG8='"},}assert result[0]["content"][2] == {"type": "text",- "text": "http://example.com/text.txt",+ "text": "A\n1\n2\n3\n",}# Check assistant message@@ -86,12 +87,16 @@ def test_convert_to_anthropic_messages(sample_messages: List[ChatMessage]):"text": "Hello, I have a question.",}assert result[0]["content"][1] == {- "type": "image_url",- "image_url": {"url": "http://example.com/image.png"},+ "type": "image",+ "source": {+ "data": "b'aGVsbG8='",+ "media_type": "image/png",+ "type": "base64",+ },}assert result[0]["content"][2] == {"type": "text",- "text": "http://example.com/text.txt",+ "text": "A\n1\n2\n3\n",}# Check assistant message@@ -111,9 +116,15 @@ def test_convert_to_google_messages(sample_messages: List[ChatMessage]):# Check user messageassert result[0]["role"] == "user"assert result[0]["parts"] == [- "Hello, I have a question.\n"- "[Image: http://example.com/image.png]\n"- "[Text: http://example.com/text.txt]"+ "Hello, I have a question.",+ {+ "data": b"m\xa1\x95\xb1\xb1\xbc",+ "mime_type": "image/png",+ },+ {+ "data": b"A\n1\n2\n3\n",+ "mime_type": "text/plain",+ },]# Check assistant message