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
chore(google): updated mo.ui.chat to use google-genai instead of google-generativeai (#5258)
Joaquin Corominaece248a1dfa6
diff --git a/docs/guides/editor_features/ai_completion.md b/docs/guides/editor_features/ai_completion.mdindex 1b6b9834ce..89a54989e5 100644--- a/docs/guides/editor_features/ai_completion.md+++ b/docs/guides/editor_features/ai_completion.md@@ -208,12 +208,12 @@ If you're using an AWS named profile different from your default, specify the prTo use Google AI with marimo:1. Sign up for an account at [Google AI Studio](https://aistudio.google.com/app/apikey) and obtain your API key.-2. Install the Google AI Python client: `pip install google-generativeai`+2. Install the Google AI Python client: `pip install google-genai`3. Add the following to your `marimo.toml` (or configure in the UI settings in the editor):```toml title="marimo.toml"[ai.open_ai]-model = "gemini-1.5-flash"+model = "gemini-2.5-flash-preview-05-20"# or any model from https://ai.google.dev/gemini-api/docs/models/gemini[ai.google]diff --git a/marimo/_ai/llm/_impl.py b/marimo/_ai/llm/_impl.pyindex 877cfb14fd..f9d3141571 100644--- a/marimo/_ai/llm/_impl.py+++ b/marimo/_ai/llm/_impl.py@@ -305,26 +305,26 @@ class google(ChatModel):self, messages: list[ChatMessage], config: ChatModelConfig) -> object:DependencyManager.google_ai.require(- "chat model requires google. `pip install google-generativeai`"- )- import google.generativeai as genai # type: ignore[import-not-found]-- genai.configure(api_key=self._require_api_key)- client = genai.GenerativeModel(- model_name=self.model,- system_instruction=self.system_message,- generation_config=genai.GenerationConfig(- max_output_tokens=config.max_tokens,- temperature=config.temperature,- top_p=config.top_p,- top_k=config.top_k,- frequency_penalty=config.frequency_penalty,- presence_penalty=config.presence_penalty,- ),+ "chat model requires google. `pip install google-genai`")+ from google import genai # type: ignore[import-not-found]++ client = genai.Client(api_key=self._require_api_key)google_messages = convert_to_google_messages(messages)- response = client.generate_content(google_messages)+ response = client.models.generate_content(+ model=self.model,+ contents=google_messages,+ config={+ "system_instruction": self.system_message,+ "max_output_tokens": config.max_tokens,+ "temperature": config.temperature,+ "top_p": config.top_p,+ "top_k": config.top_k,+ "frequency_penalty": config.frequency_penalty,+ "presence_penalty": config.presence_penalty,+ },+ )content = response.textreturn content or ""diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex b4a8077cc5..92a36fa33e 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -191,10 +191,7 @@ 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")+ google_ai = Dependency("google.genai")groq = Dependency("groq")panel = Dependency("panel")sqlalchemy = Dependency("sqlalchemy")diff --git a/marimo/_output/formatters/ai_formatters.py b/marimo/_output/formatters/ai_formatters.pyindex bf52060fc3..825ffbcf00 100644--- a/marimo/_output/formatters/ai_formatters.py+++ b/marimo/_output/formatters/ai_formatters.py@@ -1,6 +1,11 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from collections.abc import Iterator+from marimo import _loggersfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output import md@@ -18,17 +23,22 @@ class GoogleAiFormatter(FormatterFactory):def register(self) -> None:try:- import google.generativeai as genai # type: ignore+ from google.genai.types import ( # type: ignore[import-not-found]+ GenerateContentResponse,+ )except (ImportError, ModuleNotFoundError):returnfrom marimo._output import formatting- @formatting.formatter(genai.types.GenerateContentResponse)+ @formatting.formatter(GenerateContentResponse)def _show_response(- response: genai.types.GenerateContentResponse,+ # Based on the return values of generate_content and generate_content_stream+ # https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentResponse+ response: GenerateContentResponse+ | Iterator[GenerateContentResponse],) -> tuple[KnownMimeType, str]:- if hasattr(response, "_iterator") and response._iterator is None:+ if isinstance(response, GenerateContentResponse):return md.md(response.text)._mime_()# Streaming responsediff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.pyindex f0005d700b..c1af1ba125 100644--- a/marimo/_server/ai/providers.py+++ b/marimo/_server/ai/providers.py@@ -546,7 +546,7 @@ class GoogleProvider(try:from google import genaiexcept ImportError:- DependencyManager.google_ai_new.require(+ DependencyManager.google_ai.require(why="for AI assistance with Google AI")from google import genai # type: ignorediff --git a/marimo/_smoke_tests/ai/gemini_responses.py b/marimo/_smoke_tests/ai/gemini_responses.pyindex bc5d8c82c8..c3e766dcff 100644--- a/marimo/_smoke_tests/ai/gemini_responses.py+++ b/marimo/_smoke_tests/ai/gemini_responses.py@@ -52,19 +52,11 @@ def _(mo):@app.cell-def _(api_token, tools):- import google.generativeai as genai+def _(api_token):+ from google import genai- genai.configure(api_key=api_token.value)- model = genai.GenerativeModel(- model_name="gemini-2.0-flash-exp", tools=tools.value- )-- model.generate_content(- "Create a function that takes a list of numbers and returns the sum of all the numbers in the list.",- stream=True,- )- return genai, model+ client = genai.Client(api_key=api_token.value)+ return genai, client@app.cell(hide_code=True)@@ -74,9 +66,13 @@ def _(mo):@app.cell-def _(model):- model.generate_content(- "Create a function that takes a list of numbers and returns the sum of all the numbers in the list."+def _(client, tools):+ client.models.generate_content_stream(+ model="gemini-2.5-flash-preview-05-20",+ contents="Create a function that takes a list of numbers and returns the sum of all the numbers in the list.",+ config={+ "tools": tools.value,+ })returndiff --git a/pyproject.toml b/pyproject.tomlindex 3cf8cf96ae..88d64b99a5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -281,7 +281,6 @@ extra-dependencies = [# testing gen ai"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",diff --git a/tests/_ai/llm/test_impl.py b/tests/_ai/llm/test_impl.pyindex 2d38b440ef..3a91f0fd39 100644--- a/tests/_ai/llm/test_impl.py+++ b/tests/_ai/llm/test_impl.py@@ -78,14 +78,14 @@ def mock_anthropic_client():@pytest.fixturedef mock_google_client():"""Fixture for mocking the Google client."""- with patch("google.generativeai.GenerativeModel") as mock_google_class:+ with patch("google.genai.Client") as mock_google_class:mock_client = MagicMock()mock_google_class.return_value = mock_client# Setup the response structuremock_response = MagicMock()mock_response.text = "Test response"- mock_client.generate_content.return_value = mock_response+ mock_client.models.generate_content.return_value = mock_responseyield mock_client, mock_google_class@@ -207,7 +207,7 @@ def test_anthropic_require() -> None:)def test_google_require() -> None:"""Test that google.require raises ModuleNotFoundError."""- model = google("gemini-pro")+ model = google("gemini-2.5-flash-preview-05-20")messages = [ChatMessage(role="user", content="Test prompt")]config = ChatModelConfig()with pytest.raises(ModuleNotFoundError):@@ -674,38 +674,36 @@ class TestGroq:class TestGoogle:def test_init(self) -> None:"""Test initialization of the google class."""- model = google("gemini-pro")- assert model.model == "gemini-pro"+ model = google("gemini-2.5-flash-preview-05-20")+ assert model.model == "gemini-2.5-flash-preview-05-20"assert model.system_message == DEFAULT_SYSTEM_MESSAGEassert model.api_key is Nonemodel = google(- "gemini-pro",+ "gemini-2.5-flash-preview-05-20",system_message="Custom system message",api_key="test-key",)- assert model.model == "gemini-pro"+ assert model.model == "gemini-2.5-flash-preview-05-20"assert model.system_message == "Custom system message"assert model.api_key == "test-key"@patch.object(google, "_require_api_key")- @patch("google.generativeai.configure")- @patch("google.generativeai.GenerativeModel")+ @patch("google.genai.Client")def test_call(self,- mock_generative_model: MagicMock,- mock_configure: MagicMock,+ mock_genai_client_class: MagicMock,mock_require_api_key: MagicMock,) -> None:"""Test calling the google class."""mock_require_api_key.return_value = "test-key"mock_client = MagicMock()- mock_generative_model.return_value = mock_client+ mock_genai_client_class.return_value = mock_clientmock_response = MagicMock()mock_response.text = "Test response"- mock_client.generate_content.return_value = mock_response+ mock_client.models.generate_content.return_value = mock_response- model = google("gemini-pro")+ model = google("gemini-2.5-flash-preview-05-20")# Patch the _require_api_key property to return the test key directlywith patch.object(model, "_require_api_key", "test-key"):messages = [ChatMessage(role="user", content="Test prompt")]@@ -721,24 +719,24 @@ class TestGoogle:result = model(messages, config)assert result == "Test response"- mock_configure.assert_called_once_with(api_key="test-key")- mock_generative_model.assert_called_once()- call_args = mock_generative_model.call_args[1]- assert call_args["model_name"] == "gemini-pro"- generation_config = call_args["generation_config"]- assert generation_config.max_output_tokens == 100- assert generation_config.temperature == 0.7- assert generation_config.top_p == 0.9- assert generation_config.top_k == 10- assert generation_config.frequency_penalty == 0.5- assert generation_config.presence_penalty == 0.5+ mock_genai_client_class.assert_called_once_with(api_key="test-key")- mock_client.generate_content.assert_called_once()+ mock_client.models.generate_content.assert_called_once()+ call_args = mock_client.models.generate_content.call_args[1]+ assert call_args["model"] == "gemini-2.5-flash-preview-05-20"+ config_arg = call_args["config"]+ assert config_arg["system_instruction"] == DEFAULT_SYSTEM_MESSAGE+ assert config_arg["max_output_tokens"] == 100+ assert config_arg["temperature"] == 0.7+ assert config_arg["top_p"] == 0.9+ assert config_arg["top_k"] == 10+ assert config_arg["frequency_penalty"] == 0.5+ assert config_arg["presence_penalty"] == 0.5@patch.dict(os.environ, {"GOOGLE_AI_API_KEY": "env-key"})def test_require_api_key_env(self) -> None:"""Test _require_api_key with environment variable."""- model = google("gemini-pro")+ model = google("gemini-2.5-flash-preview-05-20")assert model._require_api_key == "env-key"@patch.dict(os.environ, {}, clear=True)@@ -751,7 +749,7 @@ class TestGoogle:}mock_get_context.return_value = mock_context- model = google("gemini-pro")+ model = google("gemini-2.5-flash-preview-05-20")assert model._require_api_key == "config-key"@patch.dict(os.environ, {}, clear=True)@@ -764,7 +762,7 @@ class TestGoogle:mock_context.marimo_config = {"ai": {"google": {"api_key": ""}}}mock_get_context.return_value = mock_context- model = google("gemini-pro")+ model = google("gemini-2.5-flash-preview-05-20")with pytest.raises(ValueError):_ = model._require_api_keydiff --git a/tests/_output/formatters/test_ai_formatters.py b/tests/_output/formatters/test_ai_formatters.pyindex c4e994f1a8..83b257121b 100644--- a/tests/_output/formatters/test_ai_formatters.py+++ b/tests/_output/formatters/test_ai_formatters.py@@ -23,16 +23,13 @@ from marimo._output.hypertext import Html)def test_register_with_dummy_google(mock_md: MagicMock):GoogleAiFormatter().register()- import google.generativeai as genai+ from google.genai.types import GenerateContentResponsemock_md.side_effect = lambda x: Html(f"<md>{x}</md>")- mock_response = MagicMock(genai.types.GenerateContentResponse)+ # Test direct GenerateContentResponse+ mock_response = MagicMock(spec=GenerateContentResponse)mock_response.text = "# Hello"- mock_response._iterator = None- mock_response.candidates = [- MagicMock(content="# Hello", index=0, finish_reason="STOP")- ]formatter = get_formatter(mock_response)assert formatter is not Noneresult = formatter(mock_response)@@ -43,28 +40,24 @@ def test_register_with_dummy_google(mock_md: MagicMock):# Verify md.md was called with the normal response textmock_md.assert_called_with("# Hello")- # Streaming response- mock_response._iterator = iter(- [- MagicMock(- text="```python\ndef foo():\n",- index=0,- finish_reason="INCOMPLETE",- ),- MagicMock(text=" pass\n```", index=1, finish_reason="STOP"),- ]- )- mock_response.__iter__ = lambda self: iter(self._iterator)+ # Test streaming response (iterator)+ mock_chunk1 = MagicMock(spec=GenerateContentResponse)+ mock_chunk1.text = "```python\ndef foo():\n"+ mock_chunk2 = MagicMock(spec=GenerateContentResponse)+ mock_chunk2.text = " pass\n```"++ # Create an iterator that is NOT a GenerateContentResponse+ mock_iterator = iter([mock_chunk1, mock_chunk2])# Reset the mock before the streaming callmock_md.reset_mock()- result = formatter(mock_response)- # Check that md.md was called 3 times+ result = formatter(mock_iterator)+ # Check that md.md was called 3 times (once for each chunk, then final)assert mock_md.call_count == 3assert mock_md.call_args_list == [- call("```python\ndef foo():\n\n```"), # First chunk- call("```python\ndef foo():\n pass\n```"), # First + second chunk- call("```python\ndef foo():\n pass\n```"), # End result+ call("```python\ndef foo():\n\n```"), # First chunk with closing fence+ call("```python\ndef foo():\n pass\n```"), # Accumulated chunks+ call("```python\ndef foo():\n pass\n```"), # Final result]