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.

chore: upgrade ai backend from google-generativeai (deprecated) -> google-genai (#5226)

Joaquin Coromina5f3adac1da88
diff --git a/marimo/_ai/_convert.py b/marimo/_ai/_convert.py
index 0f6c9e9765..2140bb880e 100644
--- a/marimo/_ai/_convert.py
+++ b/marimo/_ai/_convert.py
@@ -8,9 +8,9 @@ from typing import TYPE_CHECKING, Any, Literal
from marimo._ai._types import ChatMessage
if TYPE_CHECKING:
- from google.generativeai.types import ( # type: ignore[import-not-found]
- ContentDict,
- PartType,
+ from google.genai.types import ( # type: ignore[import-not-found]
+ Content,
+ Part,
)
@@ -127,21 +127,23 @@ def convert_to_groq_messages(
def convert_to_google_messages(
messages: list[ChatMessage],
-) -> list[ContentDict]:
- google_messages: list[ContentDict] = []
+) -> list[Content]:
+ google_messages: list[Content] = []
for message in messages:
- parts: list[PartType] = [str(message.content)]
+ parts: list[Part] = [{"text": str(message.content)}]
if message.attachments:
for attachment in message.attachments:
content_type = attachment.content_type or "text/plain"
parts.append(
{
- "mime_type": content_type,
- "data": base64.b64decode(
- _extract_data(attachment.url)
- ),
+ "inline_data": {
+ "mime_type": content_type,
+ "data": base64.b64decode(
+ _extract_data(attachment.url)
+ ),
+ },
}
)
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 3dd48415a3..b4a8077cc5 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -191,7 +191,10 @@ class DependencyManager:
geopandas = Dependency("geopandas")
opentelemetry = Dependency("opentelemetry")
anthropic = Dependency("anthropic")
+ # mo.ui.chat uses google.generativeai
google_ai = Dependency("google.generativeai")
+ # Backend uses google.genai
+ google_ai_new = Dependency("google.genai")
groq = Dependency("groq")
panel = Dependency("panel")
sqlalchemy = Dependency("sqlalchemy")
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index 97b7e5f360..59bff5fda8 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -37,10 +37,11 @@ if TYPE_CHECKING:
from anthropic.types import ( # type: ignore[import-not-found]
RawMessageStreamEvent,
)
- from google.generativeai import ( # type: ignore[import-not-found]
- GenerativeModel,
+ from google.genai.client import ( # type: ignore[import-not-found]
+ Client as GoogleClient,
)
- from google.generativeai.types import ( # type: ignore[import-not-found]
+ from google.genai.types import ( # type: ignore[import-not-found]
+ GenerateContentConfig,
GenerateContentResponse,
)
@@ -496,47 +497,71 @@ class AnthropicProvider(
class GoogleProvider(
CompletionProvider["GenerateContentResponse", "GenerateContentResponse"]
):
- def get_client(
- self, config: AnyProviderConfig, model: str, system_prompt: str
- ) -> GenerativeModel:
+ # Based on the docs:
+ # https://cloud.google.com/vertex-ai/generative-ai/docs/thinking
+ THINKING_MODEL_PREFIXES = [
+ "gemini-2.5-pro",
+ "gemini-2.5-flash",
+ ]
+
+ def is_thinking_model(self, model: str) -> bool:
+ return any(
+ model.startswith(prefix) for prefix in self.THINKING_MODEL_PREFIXES
+ )
+
+ def get_config(
+ self, system_prompt: str, max_tokens: int
+ ) -> GenerateContentConfig:
+ config = {
+ "system_instruction": system_prompt,
+ "temperature": 0,
+ "max_output_tokens": max_tokens,
+ }
+ if self.is_thinking_model(self.model):
+ config["thinking_config"] = {
+ "include_thoughts": True,
+ }
+ return cast("GenerateContentConfig", config)
+
+ def get_client(self, config: AnyProviderConfig) -> GoogleClient:
try:
- import google.generativeai as genai
+ from google import genai
except ImportError:
- DependencyManager.google_ai.require(
+ DependencyManager.google_ai_new.require(
why="for AI assistance with Google AI"
)
- import google.generativeai as genai # type: ignore
-
- genai.configure(api_key=config.api_key)
- return genai.GenerativeModel(
- model_name=model,
- system_instruction=system_prompt,
- generation_config=genai.GenerationConfig(
- max_output_tokens=DEFAULT_MAX_TOKENS,
- temperature=0,
- ),
- )
+ from google import genai # type: ignore
+
+ return genai.Client(api_key=config.api_key)
def stream_completion(
self,
messages: list[ChatMessage],
system_prompt: str,
max_tokens: int,
- ) -> GenerateContentResponse:
- client = self.get_client(self.config, self.model, system_prompt)
- return client.generate_content(
- contents=convert_to_google_messages(messages),
- stream=True,
- generation_config={
- "max_output_tokens": max_tokens,
- },
+ ) -> Iterator[GenerateContentResponse]:
+ client = self.get_client(self.config)
+ return cast(
+ "Iterator[GenerateContentResponse]",
+ client.models.generate_content_stream(
+ model=self.model,
+ contents=convert_to_google_messages(messages),
+ config=self.get_config(
+ system_prompt=system_prompt, max_tokens=max_tokens
+ ),
+ ),
)
def extract_content(
self, response: GenerateContentResponse
) -> ExtractedContent | None:
- if hasattr(response, "text"):
- return (response.text, "text")
+ for part in response.candidates[0].content.parts:
+ if not part.text:
+ continue
+ elif part.thought:
+ return (part.text, "reasoning")
+ else:
+ return (part.text, "text")
return None
diff --git a/pyproject.toml b/pyproject.toml
index caf8642e72..3cf8cf96ae 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -282,6 +282,7 @@ extra-dependencies = [
"openai>=1.55.3",
"anthropic==0.52.2; python_version > '3.9'",
"google-generativeai==0.8.5",
+ "google-genai>=0.2.0",
"boto3>=1.38.25",
"litellm>=1.70.0",
# exporting as ipynb
diff --git a/tests/_ai/test_chat_convert.py b/tests/_ai/test_chat_convert.py
index fa96b83839..b198186bd7 100644
--- a/tests/_ai/test_chat_convert.py
+++ b/tests/_ai/test_chat_convert.py
@@ -114,21 +114,25 @@ def test_convert_to_google_messages(sample_messages: list[ChatMessage]):
# Check user message
assert result[0]["role"] == "user"
assert result[0]["parts"] == [
- "Hello, I have a question.",
+ {"text": "Hello, I have a question."},
{
- "data": b"m\xa1\x95\xb1\xb1\xbc",
- "mime_type": "image/png",
+ "inline_data": {
+ "data": b"m\xa1\x95\xb1\xb1\xbc",
+ "mime_type": "image/png",
+ }
},
{
- "data": b"A\n1\n2\n3\n",
- "mime_type": "text/plain",
+ "inline_data": {
+ "data": b"A\n1\n2\n3\n",
+ "mime_type": "text/plain",
+ }
},
]
# Check assistant message
assert result[1]["role"] == "model"
assert result[1]["parts"] == [
- "Sure, I'd be happy to help. What's your question?"
+ {"text": "Sure, I'd be happy to help. What's your question?"}
]
@@ -177,7 +181,7 @@ def test_message_without_attachments():
google_result = convert_to_google_messages(messages)
assert len(google_result) == 1
assert google_result[0]["role"] == "user"
- assert google_result[0]["parts"] == ["Just a simple message"]
+ assert google_result[0]["parts"] == [{"text": "Just a simple message"}]
groq_result = convert_to_groq_messages(messages)
assert len(groq_result) == 1
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index 540443776f..8874171390 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -432,7 +432,7 @@ class TestAnthropicAiEndpoints:
class TestGoogleAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("google.generativeai.GenerativeModel")
+ @patch("google.genai.Client")
def test_google_ai_completion_with_code(
client: TestClient, google_ai_mock: Any
) -> None:
@@ -441,9 +441,12 @@ class TestGoogleAiEndpoints:
google_client = MagicMock()
google_ai_mock.return_value = google_client
- google_client.predict.return_value = MagicMock(
- text="import pandas as pd"
- )
+ google_client.models.generate_content_stream.return_value = [
+ MagicMock(
+ text="import pandas as pd",
+ thought=None,
+ )
+ ]
with google_ai_config(user_config_manager):
response = client.post(
@@ -457,14 +460,18 @@ class TestGoogleAiEndpoints:
)
assert response.status_code == 200, response.text
# Assert the prompt it was called with
- prompt = google_client.generate_content.call_args.kwargs[
- "contents"
- ]
- assert prompt[0]["parts"][0] == "Help me create a dataframe"
+ prompt = (
+ google_client.models.generate_content_stream.call_args.kwargs[
+ "contents"
+ ]
+ )
+ assert (
+ prompt[0]["parts"][0]["text"] == "Help me create a dataframe"
+ )
@staticmethod
@with_session(SESSION_ID)
- @patch("google.generativeai.GenerativeModel")
+ @patch("google.genai.Client")
def test_google_ai_completion_without_token(
client: TestClient, google_ai_mock: Any
) -> None:
@@ -488,7 +495,7 @@ class TestGoogleAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("google.generativeai.GenerativeModel")
+ @patch("google.genai.Client")
def test_google_ai_inline_completion(
client: TestClient, google_ai_mock: Any
) -> None:
@@ -497,9 +504,12 @@ class TestGoogleAiEndpoints:
google_client = MagicMock()
google_ai_mock.return_value = google_client
- google_client.predict.return_value = MagicMock(
- text="df = pd.DataFrame()"
- )
+ google_client.models.generate_content_stream.return_value = [
+ MagicMock(
+ text="df = pd.DataFrame()",
+ thought=None,
+ )
+ ]
with google_ai_config(user_config_manager):
response = client.post(
@@ -513,11 +523,13 @@ class TestGoogleAiEndpoints:
)
assert response.status_code == 200, response.text
# Assert the prompt it was called with
- prompt = google_client.generate_content.call_args.kwargs[
- "contents"
- ]
+ prompt = (
+ google_client.models.generate_content_stream.call_args.kwargs[
+ "contents"
+ ]
+ )
assert (
- prompt[0]["parts"][0]
+ prompt[0]["parts"][0]["text"]
== f"import pandas as pd\n{FILL_ME_TAG}\ndf.head()"
)