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
Support for `dict(ChatMessage(...))` (#8091)
vincent d warmerdam772ed649075d
diff --git a/marimo/_ai/_types.py b/marimo/_ai/_types.pyindex d2e9cebe4a..2445c8c678 100644--- a/marimo/_ai/_types.py+++ b/marimo/_ai/_types.py@@ -3,7 +3,8 @@ from __future__ import annotationsimport abcimport mimetypes-from dataclasses import dataclass, is_dataclass+from collections.abc import Iterator+from dataclasses import asdict, dataclass, is_dataclassfrom typing import (TYPE_CHECKING,Any,@@ -174,6 +175,8 @@ class StepStartPart:if TYPE_CHECKING:+ from collections.abc import Iterator+ChatPart = Union[TextPart,ReasoningPart,@@ -251,6 +254,22 @@ class ChatMessage(msgspec.Struct):)return None+ def __iter__(self) -> Iterator[tuple[str, Any]]:+ """Allow dict(message) to build the serialized dict."""+ out: ChatMessageDict = {+ "role": self.role,+ "id": self.id,+ "content": self.content,+ "parts": [cast(ChatPartDict, asdict(part)) for part in self.parts],+ "attachments": [+ cast(ChatAttachmentDict, asdict(a)) for a in self.attachments+ ]+ if self.attachments+ else None,+ "metadata": self.metadata,+ }+ return iter(out.items())+@classmethoddef create(cls,diff --git a/tests/_ai/test_ai_types.py b/tests/_ai/test_ai_types.pyindex eb66ef0011..3e090dad0b 100644--- a/tests/_ai/test_ai_types.py+++ b/tests/_ai/test_ai_types.py@@ -7,6 +7,7 @@ from typing import Any, Literal, castimport pytestfrom marimo._ai._types import (+ ChatAttachment,ChatMessage,ChatPart,FilePart,@@ -514,3 +515,34 @@ class TestChatMessagePostInit:message = ChatMessage(role="user", content="Hello", id="custom-id")assert message.id == "custom-id"+++class TestChatMessageDict:+ """Tests for ChatMessage serialization via dict()."""++ def test_parts_and_attachments_serialized_to_dict(self):+ """Parts and attachments are converted to dicts via asdict."""+ message = ChatMessage(+ role="user",+ content="Hello",+ id="msg-1",+ parts=[TextPart(type="text", text="Part text")],+ attachments=[+ ChatAttachment(url="https://example.com/file.pdf", name="doc"),+ ],+ )+ out = dict[str, Any](message)+ assert out == {+ "role": "user",+ "id": "msg-1",+ "content": "Hello",+ "parts": [{"type": "text", "text": "Part text"}],+ "attachments": [+ {+ "url": "https://example.com/file.pdf",+ "name": "doc",+ "content_type": "application/pdf",+ }+ ],+ "metadata": None,+ }