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: add tool-chaining, send back signature (anthropic), add tool ui in chat-panel (#5469)
Joaquin Coromina81773d5c5f39
diff --git a/frontend/src/__tests__/chat-utils.test.ts b/frontend/src/__tests__/chat-utils.test.tsnew file mode 100644index 0000000000..ee08c588c3--- /dev/null+++ b/frontend/src/__tests__/chat-utils.test.ts@@ -0,0 +1,234 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { addMessageToChat } from "../core/ai/chat-utils";+import type { ChatState } from "../core/ai/state";++describe("addMessageToChat", () => {+ const mockChatState: ChatState = {+ chats: [+ {+ id: "chat-1",+ title: "Test Chat 1",+ messages: [+ {+ id: "msg-1",+ role: "user",+ content: "Hello",+ timestamp: 1000,+ },+ {+ id: "msg-2",+ role: "assistant",+ content: "Hi there!",+ timestamp: 2000,+ },+ ],+ createdAt: 1000,+ updatedAt: 2000,+ },+ {+ id: "chat-2",+ title: "Test Chat 2",+ messages: [+ {+ id: "msg-3",+ role: "user",+ content: "How are you?",+ timestamp: 3000,+ },+ ],+ createdAt: 3000,+ updatedAt: 3000,+ },+ ],+ activeChatId: "chat-1",+ };++ it("should add a new message to an existing chat", () => {+ const result = addMessageToChat(+ mockChatState,+ "chat-1",+ "msg-4",+ "user",+ "New message",+ );++ expect(result.chats).toHaveLength(2);+ const updatedChat = result.chats.find((chat) => chat.id === "chat-1");+ expect(updatedChat?.messages).toHaveLength(3);+ expect(updatedChat?.messages[2]).toEqual({+ id: "msg-4",+ role: "user",+ content: "New message",+ timestamp: expect.any(Number),+ });+ expect(updatedChat?.updatedAt).toBeGreaterThan(+ mockChatState.chats[0].updatedAt,+ );+ });++ it("should update an existing message", () => {+ const result = addMessageToChat(+ mockChatState,+ "chat-1",+ "msg-1",+ "user",+ "Updated content",+ );++ expect(result.chats).toHaveLength(2);+ const updatedChat = result.chats.find((chat) => chat.id === "chat-1");+ expect(updatedChat?.messages).toHaveLength(2);+ expect(updatedChat?.messages[0]).toEqual({+ id: "msg-1",+ role: "user",+ content: "Updated content",+ timestamp: 1000,+ });+ expect(updatedChat?.updatedAt).toBeGreaterThan(+ mockChatState.chats[0].updatedAt,+ );+ });++ it("should handle message parts", () => {+ const parts = [{ type: "text" as const, text: "Part content" }];+ const result = addMessageToChat(+ mockChatState,+ "chat-1",+ "msg-5",+ "assistant",+ "Message with parts",+ parts,+ );++ const updatedChat = result.chats.find((chat) => chat.id === "chat-1");+ expect(updatedChat?.messages[2].parts).toEqual(parts);+ });++ it("should update message parts", () => {+ const originalParts = [{ type: "text" as const, text: "Original" }];+ const updatedParts = [{ type: "text" as const, text: "Updated" }];++ const stateWithParts: ChatState = {+ ...mockChatState,+ chats: [+ {+ ...mockChatState.chats[0],+ messages: [+ {+ ...mockChatState.chats[0].messages[0],+ parts: originalParts,+ },+ mockChatState.chats[0].messages[1],+ ],+ },+ mockChatState.chats[1],+ ],+ };++ const result = addMessageToChat(+ stateWithParts,+ "chat-1",+ "msg-1",+ "user",+ "Updated content",+ updatedParts,+ );++ const updatedChat = result.chats.find((chat) => chat.id === "chat-1");+ expect(updatedChat?.messages[0].parts).toEqual(updatedParts);+ });++ it("should return unchanged state when chatId is null", () => {+ const result = addMessageToChat(+ mockChatState,+ null,+ "msg-4",+ "user",+ "New message",+ );++ expect(result).toEqual(mockChatState);+ });++ it("should return unchanged state when chatId does not exist", () => {+ const result = addMessageToChat(+ mockChatState,+ "non-existent-chat",+ "msg-4",+ "user",+ "New message",+ );++ expect(result).toEqual(mockChatState);+ });++ it("should not modify other chats when updating a specific chat", () => {+ const result = addMessageToChat(+ mockChatState,+ "chat-1",+ "msg-4",+ "user",+ "New message",+ );++ const unchangedChat = result.chats.find((chat) => chat.id === "chat-2");+ expect(unchangedChat).toEqual(mockChatState.chats[1]);+ });++ it("should preserve message order when adding new messages", () => {+ const result = addMessageToChat(+ mockChatState,+ "chat-1",+ "msg-4",+ "user",+ "New message",+ );++ const updatedChat = result.chats.find((chat) => chat.id === "chat-1");+ expect(updatedChat?.messages[0].id).toBe("msg-1");+ expect(updatedChat?.messages[1].id).toBe("msg-2");+ expect(updatedChat?.messages[2].id).toBe("msg-4");+ });++ it("should handle empty chat messages array", () => {+ const emptyChatState: ChatState = {+ chats: [+ {+ id: "empty-chat",+ title: "Empty Chat",+ messages: [],+ createdAt: 1000,+ updatedAt: 1000,+ },+ ],+ activeChatId: "empty-chat",+ };++ const result = addMessageToChat(+ emptyChatState,+ "empty-chat",+ "msg-1",+ "user",+ "First message",+ );++ const updatedChat = result.chats.find((chat) => chat.id === "empty-chat");+ expect(updatedChat?.messages).toHaveLength(1);+ expect(updatedChat?.messages[0].content).toBe("First message");+ });++ it("should handle different message roles", () => {+ const result = addMessageToChat(+ mockChatState,+ "chat-1",+ "msg-4",+ "assistant",+ "Assistant response",+ );++ const updatedChat = result.chats.find((chat) => chat.id === "chat-1");+ expect(updatedChat?.messages[2].role).toBe("assistant");+ });+});diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsxindex be1c422871..004bf87707 100644--- a/frontend/src/components/chat/chat-panel.tsx+++ b/frontend/src/components/chat/chat-panel.tsx@@ -18,7 +18,6 @@ import {memo,type SetStateAction,useEffect,- useMemo,useRef,useState,} from "react";@@ -63,6 +62,7 @@ import { CopyClipboardIcon } from "../icons/copy-icon";import { Tooltip, TooltipProvider } from "../ui/tooltip";import { MarkdownRenderer } from "./markdown-renderer";import { ReasoningAccordion } from "./reasoning-accordion";+import { ToolCallAccordion } from "./tool-call-accordion";interface ChatHeaderProps {onNewChat: () => void;@@ -125,6 +125,7 @@ const ChatHeader: React.FC<ChatHeaderProps> = ({onClick={() => {setActiveChat(chat.id);}}+ type="button"><div className="font-medium">{chat.title}</div><div className="text-sm text-muted-foreground">@@ -182,7 +183,7 @@ const ChatMessage: React.FC<ChatMessageProps> = memo(/></div>) : (- <div className="w-[95%]">+ <div className="w-[95%] break-words"><div className="absolute right-1 top-1 opacity-0 group-hover:opacity-100 transition-opacity"><CopyClipboardIcon className="h-3 w-3" value={message.content} /></div>@@ -198,11 +199,29 @@ const ChatMessage: React.FC<ChatMessageProps> = memo(key={i}index={i}isStreaming={- index === totalMessages - 1 && isStreamingReasoning+ index === totalMessages - 1 &&+ isStreamingReasoning &&+ // If there are multiple reasoning parts, only show the last one+ i === (message.parts?.length || 0) - 1}/>);+ case "tool-invocation":+ return (+ <ToolCallAccordion+ key={i}+ index={i}+ toolName={part.toolInvocation.toolName}+ result={+ part.toolInvocation.state === "result"+ ? part.toolInvocation.result+ : null+ }+ state={part.toolInvocation.state}+ />+ );+/* handle other part types … */default:return null;@@ -283,11 +302,15 @@ const ChatInputFooter: React.FC<ChatInputFooterProps> = memo(</SelectTrigger><SelectContent>{modeOptions.map((option) => (- <SelectItem+ <SelectItemkey={option.value}- value={option.value}- className="text-xs"- subtitle={<div className="text-muted-foreground text-xs pl-2">{option.subtitle}</div>}+ value={option.value}+ className="text-xs"+ subtitle={+ <div className="text-muted-foreground text-xs pl-2">+ {option.subtitle}+ </div>+ }>{option.label}</SelectItem>@@ -429,16 +452,7 @@ const ChatPanelBody = () => {} = useChat({id: activeChat?.id,maxSteps: 10,- initialMessages: useMemo(() => {- return activeChat- ? activeChat.messages.map(({ role, content, timestamp, parts }) => ({- role,- content,- id: timestamp.toString(),- parts,- }))- : [];- }, [activeChat]),+ initialMessages: activeChat?.messages || [],keepLastMessageOnError: true,// Throttle the messages and data updates to 100ms// experimental_throttle: 100,@@ -454,15 +468,16 @@ const ChatPanelBody = () => {};},onFinish: (message) => {- setChatState((prev) =>- addMessageToChat(+ setChatState((prev) => {+ return addMessageToChat(prev,prev.activeChatId,+ message.id,"assistant",message.content,message.parts,- ),- );+ );+ });},onToolCall: async ({ toolCall }) => {try {@@ -488,6 +503,51 @@ const ChatPanelBody = () => {const isLoading = status === "submitted" || status === "streaming";+ // Sync user messages from useChat to storage when they become available+ useEffect(() => {+ if (!chatState.activeChatId || messages.length === 0) {+ return;+ }++ // Only sync if the last message is from a user+ const lastMessage = messages[messages.length - 1];+ if (lastMessage?.role !== "user") {+ return;+ }++ const currentChat = chatState.chats.find(+ (c) => c.id === chatState.activeChatId,+ );+ if (!currentChat) {+ return;+ }++ const storedMessageIds = new Set(currentChat.messages.map((m) => m.id));++ // Find user messages from useChat that aren't in storage yet+ const missingUserMessages = messages.filter(+ (m) => m.role === "user" && !storedMessageIds.has(m.id),+ );++ if (missingUserMessages.length > 0) {+ setChatState((prev) => {+ let result = prev;++ for (const userMessage of missingUserMessages) {+ result = addMessageToChat(+ result,+ prev.activeChatId,+ userMessage.id,+ "user",+ userMessage.content,+ );+ }++ return result;+ });+ }+ }, [messages, chatState.activeChatId, chatState.chats, setChatState]);+const isLastMessageReasoning = (messages: Message[]): boolean => {if (messages.length === 0) {return false;@@ -529,6 +589,7 @@ const ChatPanelBody = () => {}, [chatState.activeChatId]);const createNewThread = (initialMessage: string) => {+ const CURRENT_TIME = Date.now();const newChat: Chat = {id: generateUUID(),title:@@ -536,20 +597,28 @@ const ChatPanelBody = () => {? `${initialMessage.slice(0, 50)}...`: initialMessage,messages: [], // Don't pre-populate - let useChat handle it and sync back- createdAt: Date.now(),- updatedAt: Date.now(),+ createdAt: CURRENT_TIME,+ updatedAt: CURRENT_TIME,};- setChatState((prev) => ({- chats: [...prev.chats, newChat],- activeChatId: newChat.id,- }));+ // Create new chat and set as active+ setChatState((prev) => {+ const newState = {+ ...prev,+ chats: [...prev.chats, newChat],+ activeChatId: newChat.id,+ };+ return newState;+ });- setInput("");+ // Trigger AI conversation with append+ const MESSAGE_ID = generateUUID();append({+ id: MESSAGE_ID,role: "user",content: initialMessage,});+ setInput("");};const handleNewChat = () => {@@ -576,16 +645,10 @@ const ChatPanelBody = () => {}));}- // Add user message to useChat and storageappend({role: "user",content: newValue,});- if (chatState.activeChatId) {- setChatState((prev) =>- addMessageToChat(prev, chatState.activeChatId, "user", newValue),- );- }};const handleChatInputSubmit = (@@ -596,11 +659,6 @@ const ChatPanelBody = () => {return;}handleSubmit(e);- if (chatState.activeChatId) {- setChatState((prev) =>- addMessageToChat(prev, chatState.activeChatId, "user", newValue),- );- }};const handleReload = () => {diff --git a/frontend/src/components/chat/tool-call-accordion.tsx b/frontend/src/components/chat/tool-call-accordion.tsxnew file mode 100644index 0000000000..7bfb73ee5c--- /dev/null+++ b/frontend/src/components/chat/tool-call-accordion.tsx@@ -0,0 +1,118 @@+/* Copyright 2024 Marimo. All rights reserved. */++import {+ CheckCircleIcon,+ Loader2,+ WrenchIcon,+ XCircleIcon,+} from "lucide-react";+import React from "react";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/ui/accordion";+import { cn } from "@/utils/cn";++interface ToolCallAccordionProps {+ toolName: string;+ result?: string | null;+ error?: string;+ index?: number;+ state?: "partial-call" | "call" | "result";+}++export const ToolCallAccordion: React.FC<ToolCallAccordionProps> = ({+ toolName,+ result,+ error,+ index = 0,+ state,+}) => {+ const hasResult = state === "result" && (result || error);+ const status = error ? "error" : hasResult ? "success" : "loading";++ const getStatusIcon = () => {+ switch (status) {+ case "loading":+ return <Loader2 className="h-3 w-3 animate-spin" />;+ case "error":+ return <XCircleIcon className="h-3 w-3 text-destructive" />;+ case "success":+ return <CheckCircleIcon className="h-3 w-3 text-green-600" />;+ default:+ return <WrenchIcon className="h-3 w-3" />;+ }+ };++ const getStatusText = () => {+ if (status === "loading") {+ return "Running: ";+ }+ if (error) {+ return "Failed: ";+ }+ if (hasResult) {+ return "Done: ";+ }+ return "Tool call";+ };++ return (+ <Accordion+ key={`tool-${index}`}+ type="single"+ collapsible={true}+ className="w-full my-4"+ >+ <AccordionItem value="tool-call" className="border-0">+ <AccordionTrigger+ className={cn(+ "h-6 text-xs border-border !shadow-none !ring-0 bg-muted hover:bg-muted/30 py-0 px-2 gap-1 rounded-sm [&[data-state=open]>svg]:rotate-180",+ status === "error" && "text-destructive/80",+ status === "success" && "text-green-600/80",+ )}+ >+ <span className="flex items-center gap-1">+ {getStatusIcon()}+ {getStatusText()}:{" "}+ <code className="font-mono text-xs">{toolName}</code>+ </span>+ </AccordionTrigger>+ <AccordionContent className="pb-2 px-2">+ {/* Only show content when tool is complete */}+ {hasResult && (+ <div className="space-y-3">+ {/* Result */}+ {result && (+ <div>+ <div className="text-xs font-medium text-muted-foreground mt-2 mb-1">+ Result:+ </div>+ <div className="text-xs font-medium text-muted-foreground mb-1">+ {typeof result === "string"+ ? result+ : JSON.stringify(result, null, 2)}+ </div>+ </div>+ )}++ {/* Error */}+ {error && (+ <div>+ <div className="text-xs font-medium text-destructive mb-1">+ Error:+ </div>+ <div className="bg-destructive/10 border border-destructive/20 rounded-md p-3 text-sm text-destructive">+ {error}+ </div>+ </div>+ )}+ </div>+ )}+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ );+};diff --git a/frontend/src/core/ai/chat-utils.ts b/frontend/src/core/ai/chat-utils.tsindex c89e9e69a6..28f978c2a3 100644--- a/frontend/src/core/ai/chat-utils.ts+++ b/frontend/src/core/ai/chat-utils.ts@@ -7,6 +7,7 @@ import type { ChatState } from "./state";export const addMessageToChat = (chatState: ChatState,chatId: string | null,+ messageId: string,role: "user" | "assistant",content: string,parts?: AIMessage["parts"],@@ -15,24 +16,56 @@ export const addMessageToChat = (Logger.warn("No active chat");return chatState;}+ const activeChatIndex = chatState.chats.findIndex(+ (chat) => chat.id === chatId,+ );+ if (activeChatIndex === -1) {+ Logger.warn("No active chat");+ return chatState;+ }++ const chat = chatState.chats[activeChatIndex];+ const messageIndex = chat.messages.findIndex(+ (message) => message.id === messageId,+ );++ // Create copy of chats to modify+ const newChats = [...chatState.chats];+ const CURRENT_TIMESTAMP = Date.now();++ if (messageIndex === -1) {+ // Handle new message+ newChats[activeChatIndex] = {+ ...chat,+ messages: [+ ...chat.messages,+ {+ id: messageId,+ role,+ content,+ timestamp: CURRENT_TIMESTAMP,+ parts,+ },+ ],+ updatedAt: CURRENT_TIMESTAMP,+ };+ } else {+ // Handle update message+ const newMessages = [...chat.messages];+ newMessages[messageIndex] = {+ ...newMessages[messageIndex],+ content,+ parts,+ };+ newChats[activeChatIndex] = {+ ...chat,+ messages: newMessages,+ updatedAt: CURRENT_TIMESTAMP,+ };+ }+return {...chatState,- chats: chatState.chats.map((chat) =>- chat.id === chatId- ? {- ...chat,- messages: [- ...chat.messages,- {- role,- content,- timestamp: Date.now(),- parts,- },- ],- updatedAt: Date.now(),- }- : chat,- ),+ chats: newChats,};};diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.tsindex 2c15286767..8784b09994 100644--- a/frontend/src/core/ai/state.ts+++ b/frontend/src/core/ai/state.ts@@ -5,7 +5,7 @@ import { atom } from "jotai";import { atomWithStorage } from "jotai/utils";import type { CellId } from "../cells/ids";-const KEY = "marimo:ai:chatState:v2";+const KEY = "marimo:ai:chatState:v3";export const aiCompletionCellAtom = atom<{cellId: CellId;@@ -14,6 +14,7 @@ export const aiCompletionCellAtom = atom<{export const includeOtherCellsAtom = atom<boolean>(false);export interface Message {+ id: string;role: "user" | "assistant" | "data" | "system";content: string;timestamp: number;diff --git a/marimo/_ai/_convert.py b/marimo/_ai/_convert.pyindex 1a8cb6deda..154501c28b 100644--- a/marimo/_ai/_convert.py+++ b/marimo/_ai/_convert.py@@ -3,34 +3,96 @@ from __future__ import annotationsimport base64import json-from typing import TYPE_CHECKING, Any, Literal--from marimo._ai._types import ChatMessage+from typing import TYPE_CHECKING, Any, Literal, Union, cast++from marimo._ai._types import (+ ChatMessage,+ ReasoningPart,+ TextPart,+ ToolInvocationPart,+)from marimo._server.ai.tools import Toolif TYPE_CHECKING:+ from anthropic.types.message_param import ( # type: ignore[import-not-found]+ MessageParam,+ )from google.genai.types import ( # type: ignore[import-not-found]Content,Part,)+ from openai.types.chat import ( # type: ignore[import-not-found]+ ChatCompletionMessageParam,+ )# Message conversions+def get_openai_messages_from_parts(+ role: Literal["system", "user", "assistant"],+ parts: list[Union[TextPart, ReasoningPart, ToolInvocationPart]],+) -> list[dict[str, Any]]:+ messages: list[dict[str, Any]] = []+ for part in parts:+ if isinstance(part, TextPart):+ message = {"role": role, "content": part.text}+ messages.append(message)+ elif isinstance(part, ToolInvocationPart):+ # Create two messages for the tool result+ assistant_message = {+ "role": role,+ "content": None,+ "tool_calls": [+ {+ "id": part.tool_invocation.tool_call_id,+ "type": "function",+ "function": {+ "name": part.tool_invocation.tool_name,+ "arguments": str(part.tool_invocation.args)+ if part.tool_invocation.args+ else "{}",+ },+ }+ ],+ }+ messages.append(assistant_message)+ tool_result_message = {+ "role": "tool",+ "tool_call_id": part.tool_invocation.tool_call_id,+ "name": part.tool_invocation.tool_name,+ "content": str(part.tool_invocation.result),+ }+ messages.append(tool_result_message)+ return messages++def convert_to_openai_messages(messages: list[ChatMessage],-) -> list[dict[Any, Any]]:+) -> list[ChatCompletionMessageParam]:openai_messages: list[dict[Any, Any]] = []for message in messages:+ # Handle message without attachmentsif not message.attachments:- openai_messages.append(- {"role": message.role, "content": message.content}- )+ if not message.parts or len(message.parts) == 0:+ openai_messages.append(+ {"role": message.role, "content": message.content}+ )+ else:+ parts_messages = get_openai_messages_from_parts(+ message.role, message.parts+ )+ openai_messages.extend(parts_messages)continue# Handle attachmentsparts: list[dict[Any, Any]] = []- parts.append({"type": "text", "text": message.content})+ if not message.parts or len(message.parts) == 0:+ parts.append({"type": "text", "text": message.content})+ else:+ parts.extend(+ get_openai_messages_from_parts(message.role, message.parts)+ )+for attachment in message.attachments:content_type = attachment.content_type or "text/plain"@@ -50,24 +112,106 @@ def convert_to_openai_messages(openai_messages.append({"role": message.role, "content": parts})- return openai_messages+ return cast("list[ChatCompletionMessageParam]", openai_messages)+++def get_anthropic_messages_from_parts(+ role: Literal["system", "user", "assistant"],+ parts: list[Union[TextPart, ReasoningPart, ToolInvocationPart]],+) -> list[dict[Any, Any]]:+ messages: list[dict[Any, Any]] = []+ content_parts: list[dict[str, Any]] = []++ for part in parts:+ if isinstance(part, TextPart):+ content_parts.append({"type": "text", "text": part.text})+ elif isinstance(part, ReasoningPart):+ # Handle reasoning parts with proper Anthropic thinking type+ signature = ""+ if part.details and len(part.details) > 0:+ signature = part.details[0].signature or ""++ content_parts.append(+ {+ "type": "thinking",+ "thinking": part.reasoning,+ "signature": signature, # This should be the encrypted signature from Claude's response+ }+ )+ elif isinstance(part, ToolInvocationPart):+ # Add tool use to current message content+ content_parts.append(+ {+ "type": "tool_use",+ "id": part.tool_invocation.tool_call_id,+ "name": part.tool_invocation.tool_name,+ "input": part.tool_invocation.args,+ }+ )++ # Create the message with current content (including tool use)+ if content_parts:+ message_content = (+ content_parts[0]["text"]+ if len(content_parts) == 1+ and content_parts[0]["type"] == "text"+ else content_parts+ )+ messages.append({"role": role, "content": message_content})+ content_parts = [] # Reset for next message++ # Create separate tool result message+ tool_result_message = {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": part.tool_invocation.tool_call_id,+ "content": str(part.tool_invocation.result),+ }+ ],+ }+ messages.append(tool_result_message)++ # Add remaining content parts as a single message if any+ if content_parts:+ # If only one text part, use string format; otherwise use array format+ if len(content_parts) == 1 and content_parts[0]["type"] == "text":+ message_content = content_parts[0]["text"]+ else:+ message_content = content_parts++ messages.append({"role": role, "content": message_content})++ return messagesdef convert_to_anthropic_messages(messages: list[ChatMessage],-) -> list[dict[Any, Any]]:+) -> list[MessageParam]:anthropic_messages: list[dict[Any, Any]] = []for message in messages:if not message.attachments:- anthropic_messages.append(- {"role": message.role, "content": message.content}- )+ if not message.parts or len(message.parts) == 0:+ anthropic_messages.append(+ {"role": message.role, "content": message.content}+ )+ else:+ parts_messages = get_anthropic_messages_from_parts(+ message.role, message.parts+ )+ anthropic_messages.extend(parts_messages)continue# Handle attachmentsparts: list[dict[Any, Any]] = []- parts.append({"type": "text", "text": message.content})+ if not message.parts or len(message.parts) == 0:+ parts.append({"type": "text", "text": message.content})+ else:+ parts.extend(+ get_anthropic_messages_from_parts(message.role, message.parts)+ )for attachment in message.attachments:content_type = attachment.content_type or "text/plain"if content_type.startswith("image"):@@ -92,7 +236,7 @@ def convert_to_anthropic_messages(anthropic_messages.append({"role": message.role, "content": parts})- return anthropic_messages+ return cast("list[MessageParam]", anthropic_messages)def convert_to_groq_messages(@@ -127,17 +271,110 @@ def convert_to_groq_messages(return groq_messages+def get_google_messages_from_parts(+ role: Literal["system", "user", "assistant"],+ parts: list[Union[TextPart, ReasoningPart, ToolInvocationPart]],+) -> list[Content]:+ messages: list[Content] = []++ for part in parts:+ if isinstance(part, TextPart):+ # Create a message with text content+ text_message: Content = {+ "role": "user" if role == "user" else "model",+ "parts": [{"text": part.text}],+ }+ messages.append(text_message)+ elif isinstance(part, ReasoningPart):+ # Google uses the "thought" field for reasoning content+ # According to Google's thinking models documentation+ reasoning_message: Content = {+ "role": "user" if role == "user" else "model",+ "parts": [{"text": part.reasoning, "thought": True}],+ }+ messages.append(reasoning_message)+ elif isinstance(part, ToolInvocationPart):+ # Create function call message for Google+ function_call_message: Content = {+ "role": "model",+ "parts": [+ {+ "function_call": {+ "name": part.tool_invocation.tool_name,+ "args": part.tool_invocation.args or {},+ }+ }+ ],+ }+ messages.append(function_call_message)++ # Create function response message+ function_response_message: Content = {+ "role": "user",+ "parts": [+ {+ "function_response": {+ "name": part.tool_invocation.tool_name,+ "response": {+ "result": str(part.tool_invocation.result)+ },+ }+ }+ ],+ }+ messages.append(function_response_message)++ return messages++def convert_to_google_messages(messages: list[ChatMessage],) -> list[Content]:google_messages: list[Content] = []for message in messages:- parts: list[Part] = [{"text": str(message.content)}]- if message.attachments:- for attachment in message.attachments:- content_type = attachment.content_type or "text/plain"+ # Handle message without attachments+ if not message.attachments:+ if not message.parts or len(message.parts) == 0:+ google_messages.append(+ {+ "role": "user" if message.role == "user" else "model",+ "parts": [{"text": str(message.content)}],+ }+ )+ else:+ parts_messages = get_google_messages_from_parts(+ message.role, message.parts+ )+ google_messages.extend(parts_messages)+ continue++ # Handle attachments+ parts: list[Part] = []+ if not message.parts or len(message.parts) == 0:+ parts.append({"text": str(message.content)})+ else:+ # Convert internal parts to Google parts format+ for parts_message in get_google_messages_from_parts(+ message.role, message.parts+ ):+ parts.extend(parts_message["parts"])+ for attachment in message.attachments:+ content_type = attachment.content_type or "text/plain"++ if content_type.startswith("image"):+ parts.append(+ {+ "inline_data": {+ "mime_type": content_type,+ "data": base64.b64decode(+ _extract_data(attachment.url)+ ),+ },+ }+ )+ elif content_type.startswith("text"):parts.append({"inline_data": {@@ -148,6 +385,8 @@ def convert_to_google_messages(},})+ else:+ raise ValueError(f"Unsupported content type {content_type}")google_messages.append({@@ -176,10 +415,11 @@ def _extract_data(url: str) -> str:def convert_to_ai_sdk_messages(- content_text: str | dict[str, Any],+ content_text: Union[str, dict[str, Any]],content_type: Literal["text","reasoning",+ "reasoning_signature","tool_call_start","tool_call_delta","tool_call_end",@@ -193,6 +433,7 @@ def convert_to_ai_sdk_messages("""TEXT_PREFIX = "0:"REASON_PREFIX = "g:"+ REASON_SIGNATURE_PREFIX = "j:"TOOL_CALL_START_PREFIX = "b:"TOOL_CALL_DELTA_PREFIX = "c:"TOOL_CALL_PREFIX = "9:"@@ -224,6 +465,11 @@ def convert_to_ai_sdk_messages(# TODO: Add usage (promptTokens, completionTokens)return f'{FINISH_REASON_PREFIX}{{"finishReason": "{content_text}", "usage": {{"promptTokens": 0, "completionTokens": 0}}}}\n'+ elif content_type == "reasoning_signature" and isinstance(+ content_text, dict+ ):+ return f"{REASON_SIGNATURE_PREFIX}{json.dumps(content_text)}\n"+else:# Default to text for unknown typesreturn f"{TEXT_PREFIX}{json.dumps(content_text)}\n"diff --git a/marimo/_ai/_types.py b/marimo/_ai/_types.pyindex 9250fc2f4b..2dea099675 100644--- a/marimo/_ai/_types.py+++ b/marimo/_ai/_types.py@@ -21,6 +21,13 @@ class TextPartDict(TypedDict):class ReasoningPartDict(TypedDict):type: Literal["reasoning"]reasoning: str+ details: list[ReasoningDetailsDict]+++class ReasoningDetailsDict(TypedDict):+ type: Literal["text"]+ text: str+ signature: Optional[str]class ToolInvocationResultDict(TypedDict):@@ -92,6 +99,14 @@ class ReasoningPart:type: Literal["reasoning"]reasoning: str+ details: list[ReasoningDetails]+++@dataclass+class ReasoningDetails:+ type: Literal["text"]+ text: str+ signature: Optional[str] = None@dataclassdiff --git a/marimo/_ai/llm/_impl.py b/marimo/_ai/llm/_impl.pyindex f9d3141571..cd23b47214 100644--- a/marimo/_ai/llm/_impl.py+++ b/marimo/_ai/llm/_impl.py@@ -108,9 +108,6 @@ class openai(ChatModel):AzureOpenAI,OpenAI,)- from openai.types.chat import ( # type: ignore[import-not-found]- ChatCompletionMessageParam,- )# Azure OpenAI clients are instantiated slightly differently# To check if we're using Azure, we check the base_url for the format@@ -140,7 +137,7 @@ class openai(ChatModel):)response = client.chat.completions.create(model=self.model,- messages=cast(list[ChatCompletionMessageParam], openai_messages),+ messages=openai_messages,max_completion_tokens=config.max_tokens,temperature=config.temperature,top_p=config.top_p,@@ -218,9 +215,6 @@ class anthropic(ChatModel):NOT_GIVEN,Anthropic,)- from anthropic.types.message_param import ( # type: ignore[import-not-found]- MessageParam,- )client = Anthropic(api_key=self._require_api_key,@@ -232,7 +226,7 @@ class anthropic(ChatModel):model=self.model,system=self.system_message,max_tokens=config.max_tokens or 4096,- messages=cast(list[MessageParam], anthropic_messages),+ messages=anthropic_messages,top_p=config.top_p if config.top_p is not None else NOT_GIVEN,top_k=config.top_k if config.top_k is not None else NOT_GIVEN,stream=False,diff --git a/marimo/_plugins/ui/_impl/chat/utils.py b/marimo/_plugins/ui/_impl/chat/utils.pyindex 1b84f17211..6debd4a2e1 100644--- a/marimo/_plugins/ui/_impl/chat/utils.py+++ b/marimo/_plugins/ui/_impl/chat/utils.py@@ -7,6 +7,7 @@ from marimo._ai._types import (ChatAttachment,ChatMessage,ChatMessageDict,+ ReasoningDetails,ReasoningPart,TextPart,ToolInvocationPart,@@ -43,9 +44,34 @@ def from_chat_message_dict(d: ChatMessageDict) -> ChatMessage:if part_dict["type"] == "text":parts.append(TextPart(type="text", text=part_dict["text"]))elif part_dict["type"] == "reasoning":+ # Handle ReasoningDetails if present+ details_list = part_dict.get("details", [])+ details = []++ if details_list:+ for details_dict in details_list:+ details.append(+ ReasoningDetails(+ type=details_dict["type"],+ text=details_dict["text"],+ signature=details_dict.get("signature"),+ )+ )+ else:+ # Fallback for backward compatibility+ details = [+ ReasoningDetails(+ type="text",+ text=part_dict["reasoning"],+ signature=None,+ )+ ]+parts.append(ReasoningPart(- type="reasoning", reasoning=part_dict["reasoning"]+ type="reasoning",+ reasoning=part_dict["reasoning"],+ details=details,))elif part_dict["type"] == "tool-invocation":diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.pyindex fb05d43e8a..5101209867 100644--- a/marimo/_server/ai/providers.py+++ b/marimo/_server/ai/providers.py@@ -79,7 +79,8 @@ FinishReason = Literal["tool_calls", "stop"]# Types for extract_content method returnDictContent = tuple[- dict[str, Any], Literal["tool_call_start", "tool_call_end"]+ dict[str, Any],+ Literal["tool_call_start", "tool_call_end", "reasoning_signature"],]TextContent = tuple[str, Literal["text", "reasoning", "tool_call_delta"]]ExtractedContent = Union[TextContent, DictContent]@@ -90,7 +91,12 @@ FinishContent = tuple[FinishReason, Literal["finish_reason"]]StreamTextContent = tuple[str, Literal["text", "reasoning"]]StreamDictContent = tuple[dict[str, Any],- Literal["tool_call_start", "tool_call_end", "tool_call_delta"],+ Literal[+ "tool_call_start",+ "tool_call_end",+ "tool_call_delta",+ "reasoning_signature",+ ],]StreamContent = Union[StreamTextContent, StreamDictContent, FinishContent]@@ -276,6 +282,7 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):if content_type in ["text","reasoning",+ "reasoning_signature","tool_call_start","tool_call_delta","tool_call_end",@@ -317,6 +324,8 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):return (content_data, "tool_call_end")elif content_type == "tool_call_delta":return (content_data, "tool_call_delta")+ elif content_type == "reasoning_signature":+ return (content_data, "reasoning_signature")# Fallback - convert to string contentcontent_str = self._content_to_string(content_data)@@ -732,6 +741,7 @@ class AnthropicProvider(InputJSONDelta,RawContentBlockDeltaEvent,RawContentBlockStartEvent,+ SignatureDelta,TextDelta,ThinkingDelta,ToolUseBlock,@@ -745,6 +755,11 @@ class AnthropicProvider(return (response.delta.thinking, "reasoning")if isinstance(response.delta, InputJSONDelta):return (response.delta.partial_json, "tool_call_delta")+ if isinstance(response.delta, SignatureDelta):+ return (+ {"signature": response.delta.signature},+ "reasoning_signature",+ )# For the beginning of a tool use blockif isinstance(response, RawContentBlockStartEvent):diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex b6e1045e3c..a8d54f8445 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -366,15 +366,15 @@ async def takeover_endpoint() -> JSONResponse:"""responses:- 200:- description: Successfully closed existing sessions- content:- application/json:- schema:- type: object- properties:- status:- type: string+ 200:+ description: Successfully closed existing sessions+ content:+ application/json:+ schema:+ type: object+ properties:+ status:+ type: string"""app_state = AppState(request)diff --git a/openapi/api.yaml b/openapi/api.yamlindex 19a56937f3..5c04ddbbf7 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -246,6 +246,23 @@ components:- texttype: object- properties:+ details:+ items:+ properties:+ signature:+ nullable: true+ type: string+ text:+ type: string+ type:+ enum:+ - text+ type: string+ required:+ - type+ - text+ type: object+ type: arrayreasoning:type: stringtype:@@ -255,6 +272,7 @@ components:required:- type- reasoning+ - detailstype: object- properties:toolInvocation:@@ -2701,7 +2719,7 @@ components:type: objectinfo:title: marimo API- version: 0.14.7+ version: 0.14.8openapi: 3.1.0paths:/@file/{filename_and_length}:@@ -3407,16 +3425,16 @@ paths:description: Sync cell ids/api/kernel/takeover:post:- responses: null- 200:- content:- application/json:- schema:- properties:- status:- type: string- type: object- description: Successfully closed existing sessions+ responses:+ 200:+ content:+ application/json:+ schema:+ properties:+ status:+ type: string+ type: object+ description: Successfully closed existing sessions/api/packages/add:post:requestBody:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 7b36b259c4..881412356e 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2033,7 +2033,19 @@ export interface paths {cookie?: never;};requestBody?: never;- responses: never;+ responses: {+ /** @description Successfully closed existing sessions */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": {+ status?: string;+ };+ };+ };+ };};delete?: never;options?: never;@@ -2643,6 +2655,12 @@ export interface components {type: "text";}| {+ details: {+ signature?: string | null;+ text: string;+ /** @enum {string} */+ type: "text";+ }[];reasoning: string;/** @enum {string} */type: "reasoning";diff --git a/tests/_ai/test_chat_convert.py b/tests/_ai/test_chat_convert.pyindex 548b35ca23..ae3a476afa 100644--- a/tests/_ai/test_chat_convert.py+++ b/tests/_ai/test_chat_convert.py@@ -1,6 +1,7 @@from __future__ import annotationsimport base64+import jsonimport pytest@@ -13,10 +14,18 @@ from marimo._ai._convert import (convert_to_groq_messages,convert_to_openai_messages,convert_to_openai_tools,+ get_anthropic_messages_from_parts,+ get_google_messages_from_parts,+ get_openai_messages_from_parts,)from marimo._ai._types import (ChatAttachment,ChatMessage,+ ReasoningDetails,+ ReasoningPart,+ TextPart,+ ToolInvocationPart,+ ToolInvocationResult,)from marimo._plugins.ui._impl.chat.utils import from_chat_message_dictfrom marimo._server.ai.tools import Tool@@ -392,8 +401,6 @@ def test_convert_to_google_tools(sample_tools):def test_convert_to_ai_sdk_messages():- import json-# Test text typetext = "hello world"result = convert_to_ai_sdk_messages(text, "text")@@ -404,6 +411,13 @@ def test_convert_to_ai_sdk_messages():result = convert_to_ai_sdk_messages(reasoning, "reasoning")assert result == f"g:{json.dumps(reasoning)}\n"+ # Test reasoning_signature type+ reasoning_signature = {"signature": "encrypted_signature_string"}+ result = convert_to_ai_sdk_messages(+ reasoning_signature, "reasoning_signature"+ )+ assert result == f"j:{json.dumps(reasoning_signature)}\n"+# Test tool_call_start typetool_call_start = {"toolCallId": "123", "toolName": "test_tool"}result = convert_to_ai_sdk_messages(tool_call_start, "tool_call_start")@@ -441,3 +455,345 @@ def test_convert_to_ai_sdk_messages():# Test unknown type defaults to textresult = convert_to_ai_sdk_messages("fallback", "unknown")assert result == f"0:{json.dumps('fallback')}\n"+++# Tests for helper functions that convert parts to provider-specific formats+def test_get_openai_messages_from_parts_text_only():+ """Test converting TextPart to OpenAI format."""+ parts = [+ TextPart(type="text", text="Hello"),+ TextPart(type="text", text="World"),+ ]++ result = get_openai_messages_from_parts("user", parts)++ assert len(result) == 2+ assert result[0] == {"role": "user", "content": "Hello"}+ assert result[1] == {"role": "user", "content": "World"}+++def test_get_openai_messages_from_parts_with_tool_invocation():+ """Test converting ToolInvocationPart to OpenAI format."""+ tool_invocation = ToolInvocationResult(+ state="result",+ tool_call_id="call_123",+ tool_name="weather_tool",+ step=1,+ args={"location": "New York"},+ result={"temperature": "72°F", "condition": "sunny"},+ )++ parts = [+ TextPart(type="text", text="Let me check the weather"),+ ToolInvocationPart(+ type="tool-invocation", tool_invocation=tool_invocation+ ),+ ]++ result = get_openai_messages_from_parts("assistant", parts)++ assert len(result) == 3 # text message, assistant tool call, tool result++ # Check text message+ assert result[0] == {+ "role": "assistant",+ "content": "Let me check the weather",+ }++ # Check assistant tool call message+ assert result[1]["role"] == "assistant"+ assert result[1]["content"] is None+ assert len(result[1]["tool_calls"]) == 1+ tool_call = result[1]["tool_calls"][0]+ assert tool_call["id"] == "call_123"+ assert tool_call["type"] == "function"+ assert tool_call["function"]["name"] == "weather_tool"+ assert tool_call["function"]["arguments"] == str({"location": "New York"})++ # Check tool result message+ assert result[2]["role"] == "tool"+ assert result[2]["tool_call_id"] == "call_123"+ assert result[2]["name"] == "weather_tool"+ assert result[2]["content"] == str(+ {"temperature": "72°F", "condition": "sunny"}+ )+++def test_get_openai_messages_from_parts_empty():+ """Test converting empty parts list."""+ result = get_openai_messages_from_parts("user", [])+ assert result == []+++def test_get_anthropic_messages_from_parts_text_only():+ """Test converting TextPart to Anthropic format."""+ parts = [+ TextPart(type="text", text="Hello"),+ TextPart(type="text", text="World"),+ ]++ result = get_anthropic_messages_from_parts("user", parts)++ assert len(result) == 1+ assert result[0]["role"] == "user"+ assert result[0]["content"] == [+ {"type": "text", "text": "Hello"},+ {"type": "text", "text": "World"},+ ]+++def test_get_anthropic_messages_from_parts_with_reasoning():+ """Test converting ReasoningPart to Anthropic thinking format."""+ reasoning_details = [+ ReasoningDetails(+ type="text", text="Step 1: Analyze", signature="sig123"+ )+ ]++ parts = [+ TextPart(type="text", text="Let me think about this"),+ ReasoningPart(+ type="reasoning",+ reasoning="My thinking process here",+ details=reasoning_details,+ ),+ ]++ result = get_anthropic_messages_from_parts("assistant", parts)++ assert len(result) == 1+ assert result[0]["role"] == "assistant"+ assert result[0]["content"] == [+ {"type": "text", "text": "Let me think about this"},+ {+ "type": "thinking",+ "thinking": "My thinking process here",+ "signature": "sig123",+ },+ ]+++def test_get_anthropic_messages_from_parts_reasoning_no_signature():+ """Test converting ReasoningPart without signature to Anthropic format."""+ reasoning_details = [+ ReasoningDetails(type="text", text="Step 1", signature=None)+ ]++ parts = [+ ReasoningPart(+ type="reasoning",+ reasoning="Basic reasoning",+ details=reasoning_details,+ ),+ ]++ result = get_anthropic_messages_from_parts("assistant", parts)++ assert len(result) == 1+ assert result[0]["role"] == "assistant"+ assert result[0]["content"] == [+ {+ "type": "thinking",+ "thinking": "Basic reasoning",+ "signature": "", # Should be empty string when no signature+ },+ ]+++def test_get_anthropic_messages_from_parts_reasoning_empty_details():+ """Test converting ReasoningPart with empty details list."""+ parts = [+ ReasoningPart(+ type="reasoning",+ reasoning="Some reasoning",+ details=[], # Empty details+ ),+ ]++ result = get_anthropic_messages_from_parts("assistant", parts)++ assert len(result) == 1+ assert result[0]["role"] == "assistant"+ assert result[0]["content"] == [+ {+ "type": "thinking",+ "thinking": "Some reasoning",+ "signature": "", # Should be empty when no details+ },+ ]+++def test_get_anthropic_messages_from_parts_with_tool_invocation():+ """Test converting ToolInvocationPart to Anthropic format."""+ tool_invocation = ToolInvocationResult(+ state="result",+ tool_call_id="call_123",+ tool_name="search_tool",+ step=1,+ args={"query": "Python tutorials"},+ result={"results": ["tutorial1", "tutorial2"]},+ )++ parts = [+ TextPart(type="text", text="I'll search for you"),+ ToolInvocationPart(+ type="tool-invocation", tool_invocation=tool_invocation+ ),+ ]++ result = get_anthropic_messages_from_parts("assistant", parts)++ assert (+ len(result) == 2+ ) # One message with tool use, one tool result message++ # Check first message with tool use+ assert result[0]["role"] == "assistant"+ expected_content = [+ {"type": "text", "text": "I'll search for you"},+ {+ "type": "tool_use",+ "id": "call_123",+ "name": "search_tool",+ "input": {"query": "Python tutorials"},+ },+ ]+ assert result[0]["content"] == expected_content++ # Check tool result message+ assert result[1]["role"] == "user"+ assert result[1]["content"] == [+ {+ "type": "tool_result",+ "tool_use_id": "call_123",+ "content": str({"results": ["tutorial1", "tutorial2"]}),+ }+ ]+++def test_get_anthropic_messages_from_parts_single_text():+ """Test converting single TextPart uses string format instead of array."""+ parts = [TextPart(type="text", text="Single message")]++ result = get_anthropic_messages_from_parts("user", parts)++ assert len(result) == 1+ assert result[0]["role"] == "user"+ assert (+ result[0]["content"] == "Single message"+ ) # Should be string, not array+++def test_get_google_messages_from_parts_text_only():+ """Test converting TextPart to Google format."""+ parts = [+ TextPart(type="text", text="Hello"),+ TextPart(type="text", text="Google"),+ ]++ result = get_google_messages_from_parts("user", parts)++ assert len(result) == 2+ assert result[0] == {+ "role": "user",+ "parts": [{"text": "Hello"}],+ }+ assert result[1] == {+ "role": "user",+ "parts": [{"text": "Google"}],+ }+++def test_get_google_messages_from_parts_with_reasoning():+ """Test converting ReasoningPart to Google thinking format."""+ reasoning_details = [+ ReasoningDetails(type="text", text="Analysis", signature=None)+ ]++ parts = [+ TextPart(type="text", text="Regular text"),+ ReasoningPart(+ type="reasoning",+ reasoning="Deep thinking process",+ details=reasoning_details,+ ),+ ]++ result = get_google_messages_from_parts("assistant", parts)++ assert len(result) == 2++ # Check text message+ assert result[0] == {+ "role": "model",+ "parts": [{"text": "Regular text"}],+ }++ # Check reasoning message with thought flag+ assert result[1] == {+ "role": "model",+ "parts": [{"text": "Deep thinking process", "thought": True}],+ }+++def test_get_google_messages_from_parts_with_tool_invocation():+ """Test converting ToolInvocationPart to Google function call format."""+ tool_invocation = ToolInvocationResult(+ state="result",+ tool_call_id="call_456",+ tool_name="calculator",+ step=1,+ args={"expression": "2 + 2"},+ result={"answer": 4},+ )++ parts = [+ ToolInvocationPart(+ type="tool-invocation", tool_invocation=tool_invocation+ ),+ ]++ result = get_google_messages_from_parts("assistant", parts)++ assert (+ len(result) == 2+ ) # Function call message + function response message++ # Check function call message+ assert result[0]["role"] == "model"+ assert result[0]["parts"] == [+ {+ "function_call": {+ "name": "calculator",+ "args": {"expression": "2 + 2"},+ }+ }+ ]++ # Check function response message+ assert result[1]["role"] == "user"+ assert result[1]["parts"] == [+ {+ "function_response": {+ "name": "calculator",+ "response": {"result": "{'answer': 4}"},+ }+ }+ ]+++def test_get_google_messages_from_parts_role_mapping():+ """Test that roles are correctly mapped for Google (user -> user, assistant -> model)."""+ parts = [TextPart(type="text", text="Test message")]++ user_result = get_google_messages_from_parts("user", parts)+ assert user_result[0]["role"] == "user"++ assistant_result = get_google_messages_from_parts("assistant", parts)+ assert assistant_result[0]["role"] == "model"+++def test_get_google_messages_from_parts_empty():+ """Test converting empty parts list."""+ result = get_google_messages_from_parts("user", [])+ assert result == []