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.

feat: add tool support to backend providers and mode to AiConfig (#5308)

Joaquin Coromina76b64d9a7b7d
diff --git a/marimo/_ai/_convert.py b/marimo/_ai/_convert.py
index 2140bb880e..1a8cb6deda 100644
--- a/marimo/_ai/_convert.py
+++ b/marimo/_ai/_convert.py
@@ -6,6 +6,7 @@ import json
from typing import TYPE_CHECKING, Any, Literal
from marimo._ai._types import ChatMessage
+from marimo._server.ai.tools import Tool
if TYPE_CHECKING:
from google.genai.types import ( # type: ignore[import-not-found]
@@ -14,6 +15,7 @@ if TYPE_CHECKING:
)
+# Message conversions
def convert_to_openai_messages(
messages: list[ChatMessage],
) -> list[dict[Any, Any]]:
@@ -174,17 +176,95 @@ def _extract_data(url: str) -> str:
def convert_to_ai_sdk_messages(
- content_text: str,
- content_type: Literal["text", "reasoning"],
+ content_text: str | dict[str, Any],
+ content_type: Literal[
+ "text",
+ "reasoning",
+ "tool_call_start",
+ "tool_call_delta",
+ "tool_call_end",
+ "tool_result",
+ "finish_reason",
+ ],
) -> str:
- # Based on https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol
+ """
+ Format text events for the AI SDK stream protocol.
+ See: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol
+ """
TEXT_PREFIX = "0:"
REASON_PREFIX = "g:"
-
- if content_type == "text":
+ TOOL_CALL_START_PREFIX = "b:"
+ TOOL_CALL_DELTA_PREFIX = "c:"
+ TOOL_CALL_PREFIX = "9:"
+ TOOL_RESULT_PREFIX = "a:"
+ FINISH_REASON_PREFIX = "d:"
+
+ # Text events
+ if content_type == "text" and isinstance(content_text, str):
return f"{TEXT_PREFIX}{json.dumps(content_text)}\n"
- elif content_type == "reasoning":
+ elif content_type == "reasoning" and isinstance(content_text, str):
return f"{REASON_PREFIX}{json.dumps(content_text)}\n"
+
+ # Tool use events
+ elif content_type == "tool_call_start" and isinstance(content_text, dict):
+ return f"{TOOL_CALL_START_PREFIX}{json.dumps(content_text)}\n"
+ elif content_type == "tool_call_delta" and isinstance(content_text, dict):
+ return f"{TOOL_CALL_DELTA_PREFIX}{json.dumps(content_text)}\n"
+ elif content_type == "tool_call_end" and isinstance(content_text, dict):
+ return f"{TOOL_CALL_PREFIX}{json.dumps(content_text)}\n"
+ elif content_type == "tool_result" and isinstance(content_text, dict):
+ return f"{TOOL_RESULT_PREFIX}{json.dumps(content_text)}\n"
+
+ # Other events
+ elif content_type == "finish_reason" and content_text in [
+ "tool_calls",
+ "stop",
+ ]:
+ # Emit the finishReason as a JSON object with usage (default 0s)
+ # TODO: Add usage (promptTokens, completionTokens)
+ return f'{FINISH_REASON_PREFIX}{{"finishReason": "{content_text}", "usage": {{"promptTokens": 0, "completionTokens": 0}}}}\n'
+
else:
# Default to text for unknown types
return f"{TEXT_PREFIX}{json.dumps(content_text)}\n"
+
+
+# Tool conversions
+def convert_to_openai_tools(tools: list[Tool]) -> list[dict[str, Any]]:
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": tool.name,
+ "description": tool.description,
+ "parameters": tool.parameters,
+ },
+ }
+ for tool in tools
+ ]
+
+
+def convert_to_anthropic_tools(tools: list[Tool]) -> list[dict[str, Any]]:
+ return [
+ {
+ "name": tool.name,
+ "description": tool.description,
+ "input_schema": tool.parameters,
+ }
+ for tool in tools
+ ]
+
+
+def convert_to_google_tools(tools: list[Tool]) -> list[dict[str, Any]]:
+ return [
+ {
+ "function_declarations": [
+ {
+ "name": tool.name,
+ "description": tool.description,
+ "parameters": tool.parameters,
+ }
+ ]
+ }
+ for tool in tools
+ ]
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index f848f544a8..e03c226dd8 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -219,6 +219,9 @@ class PackageManagementConfig(TypedDict):
manager: Literal["pip", "rye", "uv", "poetry", "pixi"]
+CopilotMode = Literal["ask", "manual"]
+
+
@dataclass
class AiConfig(TypedDict, total=False):
"""Configuration options for AI.
@@ -227,6 +230,7 @@ class AiConfig(TypedDict, total=False):
- `rules`: custom rules to include in all AI completion prompts
- `max_tokens`: the maximum number of tokens to use in AI completions
+ - `mode`: the mode to use for AI completions. Can be one of: `"ask"` or `"manual"`
- `open_ai`: the OpenAI config
- `anthropic`: the Anthropic config
- `google`: the Google AI config
@@ -235,6 +239,7 @@ class AiConfig(TypedDict, total=False):
rules: NotRequired[str]
max_tokens: NotRequired[int]
+ mode: NotRequired[CopilotMode]
open_ai: OpenAiConfig
anthropic: AnthropicConfig
google: GoogleAiConfig
diff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.py
index cc629ac732..a336e45969 100644
--- a/marimo/_server/ai/prompts.py
+++ b/marimo/_server/ai/prompts.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from typing import Optional, Union
+from marimo._config.config import CopilotMode
from marimo._server.models.completion import (
AiCompletionContext,
Language,
@@ -165,16 +166,43 @@ def get_inline_system_prompt(*, language: Language) -> str:
)
+def _get_mode_intro_message(mode: CopilotMode) -> str:
+ base_intro = (
+ "You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.\n"
+ "Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.\n"
+ )
+ if mode == "manual":
+ return (
+ f"{base_intro}"
+ "## Capabilities\n"
+ "- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.\n"
+ "\n"
+ "## Limitations\n"
+ "- You do NOT have access to any external tools, plugins, or APIs.\n"
+ "- You may not perform any actions beyond generating text and code suggestions.\n"
+ )
+ elif mode == "ask":
+ return (
+ f"{base_intro}"
+ "## Capabilities\n"
+ "- You can use a set of read-only tools to gather additional context from the notebook or environment (e.g., searching code, summarizing data, or reading documentation).\n"
+ "- You may use these tools ONLY to gather information, not to modify code or state.\n"
+ "\n"
+ "## Limitations\n"
+ "- All tool use is strictly read-only. You may not perform write, edit, or execution actions.\n"
+ "- You must always explain to the user why you are using a tool before invoking it.\n"
+ )
+
+
def get_chat_system_prompt(
*,
custom_rules: Optional[str],
context: Optional[AiCompletionContext],
include_other_code: str,
+ mode: CopilotMode,
) -> str:
- system_prompt: str = """
-You are an AI assistant integrated into the marimo notebook code editor.
-You are a specialized AI assistant designed to help create data science notebooks using marimo.
-You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+ system_prompt: str = f"""
+{_get_mode_intro_message(mode)}
Your goal is to do one of the following two things:
@@ -269,7 +297,7 @@ y = np.random.rand(n_points.value)
plt.figure(figsize=(8, 6))
plt.scatter(x, y, alpha=0.7)
-plt.title(f"Scatter plot with {n_points.value} points")
+plt.title(f"Scatter plot with {{n_points.value}} points")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.gca() # Return the current axes to display the plot
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index c1af1ba125..096f37dbbc 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -1,10 +1,12 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import json
import os
+import uuid
from abc import ABC, abstractmethod
from collections.abc import Generator, Iterator
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
@@ -12,6 +14,7 @@ from typing import (
Literal,
Optional,
TypeVar,
+ Union,
cast,
)
@@ -21,11 +24,19 @@ from marimo import _loggers
from marimo._ai._convert import (
convert_to_ai_sdk_messages,
convert_to_anthropic_messages,
+ convert_to_anthropic_tools,
convert_to_google_messages,
+ convert_to_google_tools,
convert_to_openai_messages,
+ convert_to_openai_tools,
)
from marimo._ai._types import ChatMessage
-from marimo._config.config import AiConfig, CompletionConfig, MarimoConfig
+from marimo._config.config import (
+ AiConfig,
+ CompletionConfig,
+ CopilotMode,
+ MarimoConfig,
+)
from marimo._dependencies.dependencies import DependencyManager
from marimo._server.api.status import HTTPStatus
@@ -60,10 +71,29 @@ if TYPE_CHECKING:
ChatCompletionChunk,
)
+ from marimo._server.ai.tools import Tool
+
ResponseT = TypeVar("ResponseT")
StreamT = TypeVar("StreamT")
-ExtractedContent = tuple[str, Literal["text", "reasoning"]]
+FinishReason = Literal["tool_calls", "stop"]
+
+# Types for extract_content method return
+DictContent = tuple[
+ dict[str, Any], Literal["tool_call_start", "tool_call_end"]
+]
+TextContent = tuple[str, Literal["text", "reasoning", "tool_call_delta"]]
+ExtractedContent = Union[TextContent, DictContent]
+
+# Types for format_stream method parameter
+FinishContent = tuple[FinishReason, Literal["finish_reason"]]
+# StreamContent
+StreamTextContent = tuple[str, Literal["text", "reasoning"]]
+StreamDictContent = tuple[
+ dict[str, Any],
+ Literal["tool_call_start", "tool_call_end", "tool_call_delta"],
+]
+StreamContent = Union[StreamTextContent, StreamDictContent, FinishContent]
LOGGER = _loggers.marimo_logger()
@@ -73,7 +103,7 @@ DEFAULT_MODEL = "gpt-4o-mini"
@dataclass
class StreamOptions:
- include_reasoning: bool = False
+ text_only: bool = False
format_stream: bool = False
@@ -84,6 +114,7 @@ class AnyProviderConfig:
ssl_verify: Optional[bool] = None
ca_bundle_path: Optional[str] = None
client_pem: Optional[str] = None
+ tools: list[Tool] = field(default_factory=list)
@staticmethod
def for_openai(config: AiConfig) -> AnyProviderConfig:
@@ -99,6 +130,7 @@ class AnyProviderConfig:
ssl_verify=config["open_ai"].get("ssl_verify", True),
ca_bundle_path=config["open_ai"].get("ca_bundle_path", None),
client_pem=config["open_ai"].get("client_pem", None),
+ tools=_get_tools(config.get("mode", "manual")),
)
@staticmethod
@@ -112,6 +144,7 @@ class AnyProviderConfig:
return AnyProviderConfig(
base_url=_get_base_url(config["anthropic"]),
api_key=key,
+ tools=_get_tools(config.get("mode", "manual")),
)
@staticmethod
@@ -125,6 +158,7 @@ class AnyProviderConfig:
return AnyProviderConfig(
base_url=_get_base_url(config["google"]),
api_key=key,
+ tools=_get_tools(config.get("mode", "manual")),
)
@staticmethod
@@ -138,6 +172,7 @@ class AnyProviderConfig:
return AnyProviderConfig(
base_url=_get_base_url(config["bedrock"], "Bedrock"),
api_key=key,
+ tools=_get_tools(config.get("mode", "manual")),
)
@staticmethod
@@ -146,6 +181,7 @@ class AnyProviderConfig:
return AnyProviderConfig(
base_url=_get_base_url(config),
api_key=key,
+ tools=[], # Inline completion never uses tools
)
@staticmethod
@@ -192,6 +228,14 @@ def _get_base_url(config: Any, name: str = "") -> Optional[str]:
return None
+def _get_tools(mode: CopilotMode) -> list[Tool]:
+ if mode == "ask":
+ # TODO: add tools
+ return []
+ else: # manual mode = no tools
+ return []
+
+
class CompletionProvider(Generic[ResponseT, StreamT], ABC):
"""Base class for AI completion providers."""
@@ -210,14 +254,28 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
pass
@abstractmethod
- def extract_content(self, response: ResponseT) -> ExtractedContent | None:
+ def extract_content(
+ self, response: ResponseT, tool_call_id: Optional[str] = None
+ ) -> Optional[ExtractedContent]:
"""Extract content from a response chunk."""
pass
- def format_stream(self, content: ExtractedContent) -> str:
+ @abstractmethod
+ def get_finish_reason(self, response: ResponseT) -> Optional[FinishReason]:
+ """Get the stop reason for a response."""
+ pass
+
+ def format_stream(self, content: StreamContent) -> str:
"""Format a response into stream protocol string."""
content_text, content_type = content
- if content_type in ["text", "reasoning"]:
+ if content_type in [
+ "text",
+ "reasoning",
+ "tool_call_start",
+ "tool_call_delta",
+ "tool_call_end",
+ "finish_reason",
+ ]:
return convert_to_ai_sdk_messages(content_text, content_type)
return ""
@@ -225,6 +283,62 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
"""Collect a stream into a single string."""
return "".join(self.as_stream_response(response))
+ def _content_to_string(
+ self, content_data: Union[str, dict[str, Any]]
+ ) -> str:
+ """Convert content data to string for buffer operations."""
+ return (
+ json.dumps(content_data)
+ if isinstance(content_data, dict)
+ else str(content_data)
+ )
+
+ def _create_stream_content(
+ self, content_data: Union[str, dict[str, Any]], content_type: str
+ ) -> StreamContent:
+ """Create type-safe StreamContent tuple."""
+ # String content types
+ if isinstance(content_data, str):
+ if content_type == "text":
+ return (content_data, "text")
+ elif content_type == "reasoning":
+ return (content_data, "reasoning")
+
+ # Dict content types
+ if isinstance(content_data, dict):
+ if content_type == "tool_call_start":
+ return (content_data, "tool_call_start")
+ elif content_type == "tool_call_end":
+ return (content_data, "tool_call_end")
+ elif content_type == "tool_call_delta":
+ return (content_data, "tool_call_delta")
+
+ # Fallback - convert to string content
+ content_str = self._content_to_string(content_data)
+ return (content_str, "text")
+
+ def validate_tool_call_args(
+ self, tool_call_args: str
+ ) -> Optional[dict[str, Any]]:
+ """Validate tool call arguments."""
+ if not tool_call_args:
+ return None
+ try:
+ result = (
+ json.loads(tool_call_args)
+ if isinstance(tool_call_args, str)
+ else tool_call_args
+ )
+ return result if isinstance(result, dict) else None
+ except Exception as e:
+ LOGGER.error(
+ f"Failed to parse tool call arguments: {tool_call_args} (error: {e})"
+ )
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail=f"Invalid tool call arguments: malformed JSON: {tool_call_args}",
+ ) from e
+
def as_stream_response(
self, response: StreamT, options: Optional[StreamOptions] = None
) -> Generator[str, None, None]:
@@ -233,25 +347,96 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
buffer = ""
options = options or StreamOptions()
+ # Tool info collected from the first chunk
+ tool_call_id: Optional[str] = None
+ tool_call_name: Optional[str] = None
+ # Tool args collected from the tool_call_delta chunks
+ tool_call_args: str = ""
+ # Finish reason collected from the last chunk
+ finish_reason: Optional[FinishReason] = None
+
for chunk in cast(Generator[ResponseT, None, None], response):
- content = self.extract_content(chunk)
+ # Always check for finish reason first, before checking content
+ # Some chunks (like RawMessageDeltaEvent) contain finish reasons but no extractable content
+ # If we check content first, these chunks get skipped and finish reason is never detected
+ finish_reason = self.get_finish_reason(chunk) or finish_reason
+
+ content = self.extract_content(chunk, tool_call_id)
if not content:
continue
- content_text, content_type = content
+ content_data, content_type = content
- if not options.include_reasoning and content_type == "reasoning":
+ if options.text_only and content_type != "text":
continue
+ # Tool handling
+ if content_type == "tool_call_start" and isinstance(
+ content_data, dict
+ ):
+ tool_call_id = content_data.get("toolCallId", None)
+ tool_call_name = content_data.get("toolName", None)
+ # Sometimes GoogleProvider emits the args in the tool_call_start chunk
+ if content_data.get("args"):
+ # don't yield args in tool_call_start chunk
+ # it will throw an error in ai-sdk-ui
+ tool_call_args = content_data.pop("args")
+
+ if content_type == "tool_call_delta" and isinstance(
+ content_data, str
+ ):
+ if isinstance(self, GoogleProvider):
+ # For GoogleProvider, each chunk contains the full (possibly updated) args dict as a JSON string.
+ # Example: first chunk: {"location": "San Francisco"}
+ # second chunk: {"location": "San Francisco", "zip": "94107"}
+ # We overwrite tool_call_args with the latest chunk.
+ tool_call_args = content_data
+ else:
+ # For other providers, tool_call_args is built up incrementally from deltas.
+ tool_call_args += content_data
+ # update tool_call_delta to ai-sdk-ui structure
+ # based on https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#tool-call-delta-part
+ content_data = {
+ "toolCallId": tool_call_id,
+ "argsTextDelta": content_data,
+ }
+
+ content_str = self._content_to_string(content_data)
+
if options.format_stream:
- content_text = self.format_stream(content)
+ stream_content = self._create_stream_content(
+ content_data, content_type
+ )
+ content_str = self.format_stream(stream_content)
- buffer += content_text
- original_content += content_text
+ buffer += content_str
+ original_content += content_str
yield buffer
buffer = ""
+ # Handle tool call end after the stream is complete
+ if tool_call_id and tool_call_name and not options.text_only:
+ content_data = {
+ "toolCallId": tool_call_id,
+ "toolName": tool_call_name,
+ "args": self.validate_tool_call_args(tool_call_args)
+ or {}, # empty object if tool doesnt have args
+ }
+ content_type = "tool_call_end"
+ yield self.format_stream((content_data, content_type))
+ # Reset tool call state for next stream just in case
+ tool_call_id = None
+ tool_call_name = None
+ tool_call_args = ""
+
+ # Add a final finish reason chunk
+ if finish_reason and not options.text_only:
+ finish_content: FinishContent = (finish_reason, "finish_reason")
+ yield self.format_stream(finish_content)
+ # reset finish reason for next stream
+ finish_reason = None
+
LOGGER.debug(f"Completion content: {original_content}")
@@ -380,6 +565,7 @@ class OpenAIProvider(
"max_completion_tokens": max_tokens,
"stream": True,
"timeout": 15,
+ "tools": convert_to_openai_tools(self.config.tools),
}
if self.is_reasoning_model(self.model):
create_params["reasoning_effort"] = self.DEFAULT_REASONING_EFFORT
@@ -389,16 +575,59 @@ class OpenAIProvider(
)
def extract_content(
- self, response: ChatCompletionChunk
- ) -> ExtractedContent | None:
+ self,
+ response: ChatCompletionChunk,
+ _tool_call_id: Optional[str] = None,
+ ) -> Optional[ExtractedContent]:
if (
hasattr(response, "choices")
and response.choices
and response.choices[0].delta
):
- content = response.choices[0].delta.content
+ delta = response.choices[0].delta
+
+ # Text content
+ content = delta.content
if content:
return (content, "text")
+
+ # Tool call:
+ if delta.tool_calls:
+ tool_calls = delta.tool_calls[0]
+
+ # Start of tool call
+ # id is only present for the first tool call chunk
+ if (
+ tool_calls.id
+ and tool_calls.function
+ and tool_calls.function.name
+ ):
+ tool_info = {
+ "toolCallId": tool_calls.id,
+ "toolName": tool_calls.function.name,
+ }
+ return (tool_info, "tool_call_start")
+
+ # Delta of tool call
+ # arguments is only present second chunk onwards
+ if tool_calls.function and tool_calls.function.arguments:
+ return (tool_calls.function.arguments, "tool_call_delta")
+
+ return None
+
+ def get_finish_reason(
+ self, response: ChatCompletionChunk
+ ) -> Optional[FinishReason]:
+ if (
+ hasattr(response, "choices")
+ and response.choices
+ and response.choices[0].finish_reason
+ ):
+ return (
+ "tool_calls"
+ if response.choices[0].finish_reason == "tool_calls"
+ else "stop"
+ )
return None
def _maybe_convert_roles(
@@ -474,6 +703,7 @@ class AnthropicProvider(
Any,
convert_to_anthropic_messages(messages),
),
+ "tools": convert_to_anthropic_tools(self.config.tools),
"system": system_prompt,
"stream": True,
"temperature": self.get_temperature(),
@@ -489,19 +719,26 @@ class AnthropicProvider(
)
def extract_content(
- self, response: RawMessageStreamEvent
- ) -> ExtractedContent | None:
+ self,
+ response: RawMessageStreamEvent,
+ _tool_call_id: Optional[str] = None,
+ ) -> Optional[ExtractedContent]:
from anthropic.types import (
+ InputJSONDelta,
RawContentBlockDeltaEvent,
+ RawContentBlockStartEvent,
TextDelta,
ThinkingDelta,
+ ToolUseBlock,
)
- # For content blocks
- if isinstance(response, TextDelta):
- return (response.text, "text")
- if isinstance(response, ThinkingDelta):
- return (response.thinking, "reasoning")
+ # # For content blocks
+ # if isinstance(response, TextDelta):
+ # return (response.text, "text")
+ # if isinstance(response, ThinkingDelta):
+ # return (response.thinking, "reasoning")
+ # if isinstance(response, InputJSONDelta):
+ # return (response.partial_json, "tool_call_delta")
# For streaming content
if isinstance(response, RawContentBlockDeltaEvent):
@@ -509,6 +746,35 @@ class AnthropicProvider(
return (response.delta.text, "text")
if isinstance(response.delta, ThinkingDelta):
return (response.delta.thinking, "reasoning")
+ if isinstance(response.delta, InputJSONDelta):
+ return (response.delta.partial_json, "tool_call_delta")
+
+ # For the beginning of a tool use block
+ if isinstance(response, RawContentBlockStartEvent):
+ if isinstance(response.content_block, ToolUseBlock):
+ tool_info = {
+ "toolCallId": response.content_block.id,
+ "toolName": response.content_block.name,
+ }
+ return (tool_info, "tool_call_start")
+
+ return None
+
+ def get_finish_reason(
+ self, response: RawMessageStreamEvent
+ ) -> Optional[FinishReason]:
+ from anthropic.types import RawMessageDeltaEvent
+
+ # Check for message_delta events which contain the stop_reason
+ if isinstance(response, RawMessageDeltaEvent):
+ if (
+ hasattr(response, "delta")
+ and hasattr(response.delta, "stop_reason")
+ and response.delta.stop_reason
+ ):
+ stop_reason = response.delta.stop_reason
+ # Anthropic uses "end_turn" for normal completion, "tool_use" for tool calls
+ return "tool_calls" if stop_reason == "tool_use" else "stop"
return None
@@ -535,6 +801,7 @@ class GoogleProvider(
"system_instruction": system_prompt,
"temperature": 0,
"max_output_tokens": max_tokens,
+ "tools": convert_to_google_tools(self.config.tools),
}
if self.is_thinking_model(self.model):
config["thinking_config"] = {
@@ -571,16 +838,66 @@ class GoogleProvider(
),
)
+ def _get_tool_call_id(self, tool_call_id: Optional[str]) -> Optional[str]:
+ # Custom tools don't have an id, so we have to generate a random uuid
+ # https://ai.google.dev/gemini-api/docs/function-calling?example=meeting
+ if not tool_call_id:
+ # generate a random uuid
+ return str(uuid.uuid4())
+ return tool_call_id
+
def extract_content(
- self, response: GenerateContentResponse
- ) -> ExtractedContent | None:
- for part in response.candidates[0].content.parts:
- if not part.text:
- continue
- elif part.thought:
- return (part.text, "reasoning")
+ self,
+ response: GenerateContentResponse,
+ tool_call_id: Optional[str] = None,
+ ) -> Optional[ExtractedContent]:
+ if not response.candidates:
+ return None
+
+ candidate = response.candidates[0]
+ if not candidate or not candidate.content:
+ return None
+
+ if not candidate.content.parts:
+ return None
+
+ for part in candidate.content.parts:
+ # Start of tool call
+ # GoogleProvider may emit the function_call object in every chunk, not just the first.
+ # We use tool_call_id to ensure we only emit one tool_call_start event per tool call.
+ if part.function_call and not tool_call_id:
+ tool_info = {
+ "toolCallId": self._get_tool_call_id(
+ part.function_call.id
+ ),
+ "toolName": part.function_call.name,
+ "args": json.dumps(part.function_call.args),
+ }
+ return (tool_info, "tool_call_start")
+ # Tool call args (not delta)
+ elif part.function_call and part.function_call.args:
+ return (json.dumps(part.function_call.args), "tool_call_delta")
+
+ # Skip non-text content
+ elif part.text:
+ # Reasoning content
+ if part.thought:
+ return (part.text, "reasoning")
+ else:
+ return (part.text, "text")
else:
- return (part.text, "text")
+ continue
+ return None
+
+ def get_finish_reason(
+ self, response: GenerateContentResponse
+ ) -> Optional[FinishReason]:
+ if response.candidates and response.candidates[0].content.parts:
+ for part in response.candidates[0].content.parts:
+ if part.function_call:
+ return "tool_calls"
+ if response.candidates and response.candidates[0].finish_reason:
+ return "stop"
return None
@@ -633,18 +950,64 @@ class BedrockProvider(
max_completion_tokens=max_tokens,
stream=True,
timeout=15,
+ tools=convert_to_openai_tools(self.config.tools),
)
def extract_content(
- self, response: LitellmStreamResponse
- ) -> ExtractedContent | None:
+ self,
+ response: LitellmStreamResponse,
+ _tool_call_id: Optional[str] = None,
+ ) -> Optional[ExtractedContent]:
if (
hasattr(response, "choices")
and response.choices
and response.choices[0].delta
- and response.choices[0].delta.content
):
- return (str(response.choices[0].delta.content), "text")
+ delta = response.choices[0].delta
+
+ # Text content
+ content = delta.content
+ if content:
+ return (str(content), "text")
+
+ # Tool call: LiteLLM follows OpenAI format for tool calls
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
+ tool_calls = delta.tool_calls[0]
+
+ # Start of tool call
+ # id is only present for the first tool call chunk
+ if hasattr(tool_calls, "id") and tool_calls.id:
+ tool_info = {
+ "toolCallId": tool_calls.id,
+ "toolName": tool_calls.function.name,
+ }
+ return (tool_info, "tool_call_start")
+
+ # Delta of tool call
+ # arguments is only present second chunk onwards
+ if (
+ hasattr(tool_calls, "function")
+ and tool_calls.function
+ and hasattr(tool_calls.function, "arguments")
+ and tool_calls.function.arguments
+ ):
+ return (tool_calls.function.arguments, "tool_call_delta")
+
+ return None
+
+ def get_finish_reason(
+ self, response: LitellmStreamResponse
+ ) -> Optional[FinishReason]:
+ if (
+ hasattr(response, "choices")
+ and response.choices
+ and response.choices[0].finish_reason
+ ):
+ return (
+ "tool_calls"
+ if response.choices[0].finish_reason == "tool_calls"
+ else "stop"
+ )
return None
diff --git a/marimo/_server/ai/tools.py b/marimo/_server/ai/tools.py
new file mode 100644
index 0000000000..e0f15f7c30
--- /dev/null
+++ b/marimo/_server/ai/tools.py
@@ -0,0 +1,23 @@
+from dataclasses import dataclass
+from typing import Any, Literal
+
+from marimo._config.config import CopilotMode
+
+ToolSource = Literal["mcp", "local"]
+
+
+@dataclass
+class Tool:
+ name: str
+ description: str
+ parameters: dict[str, Any]
+ source: ToolSource # special handling for mcp tools
+ mode: list[
+ CopilotMode
+ ] # tools can be made available in more than one mode
+
+
+# TODO: Add ToolRegistry class to manage tool registration and retrieval
+# TODO: Add ToolManager class to interact with tool registry,
+# tool invoker, and expose tools to providers.py
+# TODO: Add ToolInvoker class to handle calling tools
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index 4d6593bb5d..0f4f2128cd 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -113,7 +113,9 @@ async def ai_completion(
return StreamingResponse(
content=without_wrapping_backticks(
- provider.as_stream_response(response)
+ provider.as_stream_response(
+ response, StreamOptions(text_only=True)
+ )
),
media_type="application/json",
)
@@ -149,6 +151,7 @@ async def ai_chat(
custom_rules=custom_rules,
context=body.context,
include_other_code=body.include_other_code,
+ mode=ai_config.get("mode", "manual"),
)
max_tokens = get_max_tokens(config)
@@ -166,7 +169,7 @@ async def ai_chat(
return StreamingResponse(
content=provider.as_stream_response(
- response, StreamOptions(include_reasoning=True, format_stream=True)
+ response, StreamOptions(format_stream=True)
),
media_type="application/json",
)
diff --git a/openapi/api.yaml b/openapi/api.yaml
index cb082c1d24..74b12bd36e 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1348,6 +1348,11 @@ components:
type: object
max_tokens:
type: integer
+ mode:
+ enum:
+ - ask
+ - manual
+ type: string
open_ai:
properties:
api_key:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 9465f6be31..e3f07bb874 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -3026,6 +3026,8 @@ export interface components {
api_key?: string;
};
max_tokens?: number;
+ /** @enum {string} */
+ mode?: "ask" | "manual";
open_ai?: {
api_key?: string;
base_url?: string;
diff --git a/tests/_ai/test_chat_convert.py b/tests/_ai/test_chat_convert.py
index b198186bd7..e8490cd0b5 100644
--- a/tests/_ai/test_chat_convert.py
+++ b/tests/_ai/test_chat_convert.py
@@ -5,16 +5,21 @@ import base64
import pytest
from marimo._ai._convert import (
+ convert_to_ai_sdk_messages,
convert_to_anthropic_messages,
+ convert_to_anthropic_tools,
convert_to_google_messages,
+ convert_to_google_tools,
convert_to_groq_messages,
convert_to_openai_messages,
+ convert_to_openai_tools,
)
from marimo._ai._types import (
ChatAttachment,
ChatMessage,
)
from marimo._plugins.ui._impl.chat.utils import from_chat_message_dict
+from marimo._server.ai.tools import Tool
@pytest.fixture
@@ -238,3 +243,108 @@ def test_from_chat_message_dict():
result_existing = from_chat_message_dict(existing_chat_message)
assert result_existing is existing_chat_message
+
+
+def sample_tools():
+ return [
+ Tool(
+ name="test_tool",
+ description="A test tool",
+ parameters={
+ "type": "object",
+ "properties": {"x": {"type": "integer"}},
+ },
+ source="mcp",
+ mode=["manual"],
+ )
+ ]
+
+
+def test_convert_to_openai_tools(sample_tools):
+ result = convert_to_openai_tools(sample_tools)
+ assert len(result) == 1
+ assert result[0]["type"] == "function"
+ assert result[0]["function"]["name"] == "test_tool"
+ assert result[0]["function"]["description"] == "A test tool"
+ assert result[0]["function"]["parameters"] == {
+ "type": "object",
+ "properties": {"x": {"type": "integer"}},
+ }
+
+
+def test_convert_to_anthropic_tools(sample_tools):
+ result = convert_to_anthropic_tools(sample_tools)
+ assert len(result) == 1
+ assert result[0]["name"] == "test_tool"
+ assert result[0]["description"] == "A test tool"
+ assert result[0]["input_schema"] == {
+ "type": "object",
+ "properties": {"x": {"type": "integer"}},
+ }
+
+
+def test_convert_to_google_tools(sample_tools):
+ result = convert_to_google_tools(sample_tools)
+ assert len(result) == 1
+ assert "function_declarations" in result[0]
+ assert result[0]["function_declarations"][0]["name"] == "test_tool"
+ assert (
+ result[0]["function_declarations"][0]["description"] == "A test tool"
+ )
+ assert result[0]["function_declarations"][0]["parameters"] == {
+ "type": "object",
+ "properties": {"x": {"type": "integer"}},
+ }
+
+
+def test_convert_to_ai_sdk_messages():
+ import json
+
+ # Test text type
+ text = "hello world"
+ result = convert_to_ai_sdk_messages(text, "text")
+ assert result == f"0:{json.dumps(text)}\n"
+
+ # Test reasoning type
+ reasoning = "step by step"
+ result = convert_to_ai_sdk_messages(reasoning, "reasoning")
+ assert result == f"g:{json.dumps(reasoning)}\n"
+
+ # Test tool_call_start type
+ tool_call_start = {"toolCallId": "123", "toolName": "test_tool"}
+ result = convert_to_ai_sdk_messages(tool_call_start, "tool_call_start")
+ assert result == f"b:{json.dumps(tool_call_start)}\n"
+
+ # Test tool_call_delta type
+ tool_call_delta = {"toolCallId": "123", "argsTextDelta": "partial args"}
+ result = convert_to_ai_sdk_messages(tool_call_delta, "tool_call_delta")
+ assert result == f"c:{json.dumps(tool_call_delta)}\n"
+
+ # Test tool_call_end type
+ tool_call_end = {
+ "toolCallId": "123",
+ "toolName": "test_tool",
+ "args": {"param": "value"},
+ }
+ result = convert_to_ai_sdk_messages(tool_call_end, "tool_call_end")
+ assert result == f"9:{json.dumps(tool_call_end)}\n"
+
+ # Test tool_result type
+ tool_result = {"toolCallId": "123", "result": "success"}
+ result = convert_to_ai_sdk_messages(tool_result, "tool_result")
+ assert result == f"a:{json.dumps(tool_result)}\n"
+
+ # Test finish_reason type with "tool_calls"
+ result = convert_to_ai_sdk_messages("tool_calls", "finish_reason")
+ expected = 'd:{"finishReason": "tool_calls", "usage": {"promptTokens": 0, "completionTokens": 0}}\n'
+ assert result == expected
+
+ # Test finish_reason type with "stop"
+ result = convert_to_ai_sdk_messages("stop", "finish_reason")
+ expected = 'd:{"finishReason": "stop", "usage": {"promptTokens": 0, "completionTokens": 0}}\n'
+ assert result == expected
+
+ # Test unknown type defaults to text
+ result = convert_to_ai_sdk_messages("fallback", "unknown")
+ assert result == f"0:{json.dumps('fallback')}\n"
diff --git a/tests/_server/ai/snapshots/chat_system_prompts.txt b/tests/_server/ai/snapshots/chat_system_prompts.txt
index 3370280d28..aaa1ec7efc 100644
--- a/tests/_server/ai/snapshots/chat_system_prompts.txt
+++ b/tests/_server/ai/snapshots/chat_system_prompts.txt
@@ -3,9 +3,15 @@
==================== no custom rules ====================
-You are an AI assistant integrated into the marimo notebook code editor.
-You are a specialized AI assistant designed to help create data science notebooks using marimo.
-You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.
+Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.
+## Capabilities
+- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.
+
+## Limitations
+- You do NOT have access to any external tools, plugins, or APIs.
+- You may not perform any actions beyond generating text and code suggestions.
+
Your goal is to do one of the following two things:
@@ -121,9 +127,15 @@ plt.gca() # Return the current axes to display the plot
==================== with custom rules ====================
-You are an AI assistant integrated into the marimo notebook code editor.
-You are a specialized AI assistant designed to help create data science notebooks using marimo.
-You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.
+Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.
+## Capabilities
+- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.
+
+## Limitations
+- You do NOT have access to any external tools, plugins, or APIs.
+- You may not perform any actions beyond generating text and code suggestions.
+
Your goal is to do one of the following two things:
@@ -242,9 +254,15 @@ Always be polite.
==================== with variables ====================
-You are an AI assistant integrated into the marimo notebook code editor.
-You are a specialized AI assistant designed to help create data science notebooks using marimo.
-You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.
+Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.
+## Capabilities
+- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.
+
+## Limitations
+- You do NOT have access to any external tools, plugins, or APIs.
+- You may not perform any actions beyond generating text and code suggestions.
+
Your goal is to do one of the following two things:
@@ -363,9 +381,15 @@ plt.gca() # Return the current axes to display the plot
==================== with VariableContext objects ====================
-You are an AI assistant integrated into the marimo notebook code editor.
-You are a specialized AI assistant designed to help create data science notebooks using marimo.
-You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.
+Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.
+## Capabilities
+- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.
+
+## Limitations
+- You do NOT have access to any external tools, plugins, or APIs.
+- You may not perform any actions beyond generating text and code suggestions.
+
Your goal is to do one of the following two things:
@@ -490,9 +514,15 @@ plt.gca() # Return the current axes to display the plot
==================== with context ====================
-You are an AI assistant integrated into the marimo notebook code editor.
-You are a specialized AI assistant designed to help create data science notebooks using marimo.
-You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.
+Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.
+## Capabilities
+- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.
+
+## Limitations
+- You do NOT have access to any external tools, plugins, or APIs.
+- You may not perform any actions beyond generating text and code suggestions.
+
Your goal is to do one of the following two things:
@@ -625,9 +655,15 @@ plt.gca() # Return the current axes to display the plot
==================== with other code ====================
-You are an AI assistant integrated into the marimo notebook code editor.
-You are a specialized AI assistant designed to help create data science notebooks using marimo.
-You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.
+Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.
+## Capabilities
+- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.
+
+## Limitations
+- You do NOT have access to any external tools, plugins, or APIs.
+- You may not perform any actions beyond generating text and code suggestions.
+
Your goal is to do one of the following two things:
@@ -748,9 +784,15 @@ import numpy as np
==================== kitchen sink ====================
-You are an AI assistant integrated into the marimo notebook code editor.
-You are a specialized AI assistant designed to help create data science notebooks using marimo.
-You focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.
+You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.
+Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.
+## Capabilities
+- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.
+
+## Limitations
+- You do NOT have access to any external tools, plugins, or APIs.
+- You may not perform any actions beyond generating text and code suggestions.
+
Your goal is to do one of the following two things:
diff --git a/tests/_server/ai/test_prompts.py b/tests/_server/ai/test_prompts.py
index 1b7fe7c932..5d1ffe9d40 100644
--- a/tests/_server/ai/test_prompts.py
+++ b/tests/_server/ai/test_prompts.py
@@ -182,9 +182,7 @@ def test_chat_system_prompts():
result: str = ""
result += _header("no custom rules")
result += get_chat_system_prompt(
- custom_rules=None,
- include_other_code="",
- context=None,
+ custom_rules=None, include_other_code="", context=None, mode="manual"
)
result += _header("with custom rules")
@@ -192,6 +190,7 @@ def test_chat_system_prompts():
custom_rules="Always be polite.",
include_other_code="",
context=None,
+ mode="manual",
)
result += _header("with variables")
@@ -201,6 +200,7 @@ def test_chat_system_prompts():
context=AiCompletionContext(
variables=["var1", "var2"],
),
+ mode="manual",
)
result += _header("with VariableContext objects")
@@ -221,6 +221,7 @@ def test_chat_system_prompts():
),
]
),
+ mode="manual",
)
result += _header("with context")
@@ -255,6 +256,7 @@ def test_chat_system_prompts():
),
],
),
+ mode="manual",
)
result += _header("with other code")
@@ -262,6 +264,7 @@ def test_chat_system_prompts():
custom_rules=None,
include_other_code="import pandas as pd\nimport numpy as np\n",
context=None,
+ mode="manual",
)
result += _header("kitchen sink")
@@ -286,6 +289,7 @@ def test_chat_system_prompts():
),
],
),
+ mode="manual",
)
snapshot("chat_system_prompts.txt", result)
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index 8874171390..cc8593ba27 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import unittest
from contextlib import contextmanager
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Optional
from unittest.mock import MagicMock, Mock, patch
import pytest
@@ -13,6 +13,7 @@ from marimo._config.manager import UserConfigManager
from marimo._dependencies.dependencies import DependencyManager
from marimo._server.ai.prompts import FILL_ME_TAG
from marimo._server.ai.providers import (
+ AnyProviderConfig,
OpenAIProvider,
without_wrapping_backticks,
)
@@ -55,6 +56,7 @@ class Delta:
@dataclass
class Choice:
delta: Delta
+ finish_reason: Optional[str] = None
# OpenAI
@@ -782,7 +784,8 @@ def test_chat_with_code(client: TestClient) -> None:
class TestGetContent(unittest.TestCase):
def test_extract_content_with_none_delta(self) -> None:
- provider = OpenAIProvider(model="gpt-4o", config={})
+ config = AnyProviderConfig(base_url=None, api_key="test-key")
+ provider = OpenAIProvider(model="gpt-4o", config=config)
# Create a mock response with choices but delta is None
mock_response = Mock()
mock_response.choices = [Mock()]
@@ -805,7 +808,8 @@ class TestGetContent(unittest.TestCase):
mock_response.choices[0].delta.content = "Test content"
# Call get_content with the mock response
- provider = OpenAIProvider(model="gpt-4o", config={})
+ config = AnyProviderConfig(base_url=None, api_key="test-key")
+ provider = OpenAIProvider(model="gpt-4o", config=config)
result_text, result_type = provider.extract_content(mock_response)
# Assert that the result is the expected content
@@ -813,6 +817,77 @@ class TestGetContent(unittest.TestCase):
assert result_type == "text"
+class TestGetFinishReason(unittest.TestCase):
+ def test_get_finish_reason_with_no_choices(self) -> None:
+ config = AnyProviderConfig(base_url=None, api_key="test-key")
+ provider = OpenAIProvider(model="gpt-4o", config=config)
+ # Create a mock response with no choices
+ mock_response = Mock()
+ mock_response.choices = []
+
+ # Call get_finish_reason with the mock response
+ result = provider.get_finish_reason(mock_response)
+
+ # Assert that the result is None
+ assert result is None
+
+ def test_get_finish_reason_with_none_finish_reason(self) -> None:
+ config = AnyProviderConfig(base_url=None, api_key="test-key")
+ provider = OpenAIProvider(model="gpt-4o", config=config)
+ # Create a mock response with choices but finish_reason is None
+ mock_response = Mock()
+ mock_response.choices = [Mock()]
+ mock_response.choices[0].finish_reason = None
+
+ # Call get_finish_reason with the mock response
+ result = provider.get_finish_reason(mock_response)
+
+ # Assert that the result is None
+ assert result is None
+
+ def test_get_finish_reason_with_tool_calls(self) -> None:
+ config = AnyProviderConfig(base_url=None, api_key="test-key")
+ provider = OpenAIProvider(model="gpt-4o", config=config)
+ # Create a mock response with choices and finish_reason = "tool_calls"
+ mock_response = Mock()
+ mock_response.choices = [Mock()]
+ mock_response.choices[0].finish_reason = "tool_calls"
+
+ # Call get_finish_reason with the mock response
+ result = provider.get_finish_reason(mock_response)
+
+ # Assert that the result is "tool_calls"
+ assert result == "tool_calls"
+
+ def test_get_finish_reason_with_stop(self) -> None:
+ config = AnyProviderConfig(base_url=None, api_key="test-key")
+ provider = OpenAIProvider(model="gpt-4o", config=config)
+ # Create a mock response with choices and finish_reason = "stop"
+ mock_response = Mock()
+ mock_response.choices = [Mock()]
+ mock_response.choices[0].finish_reason = "stop"
+
+ # Call get_finish_reason with the mock response
+ result = provider.get_finish_reason(mock_response)
+
+ # Assert that the result is "stop"
+ assert result == "stop"
+
+ def test_get_finish_reason_with_other_reason(self) -> None:
+ config = AnyProviderConfig(base_url=None, api_key="test-key")
+ provider = OpenAIProvider(model="gpt-4o", config=config)
+ # Create a mock response with choices and finish_reason = "length"
+ mock_response = Mock()
+ mock_response.choices = [Mock()]
+ mock_response.choices[0].finish_reason = "length"
+
+ # Call get_finish_reason with the mock response
+ result = provider.get_finish_reason(mock_response)
+
+ # Assert that the result is "stop" (fallback for non-tool_calls reasons)
+ assert result == "stop"
+
+
@pytest.mark.parametrize(
("chunks", "expected"),
[