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
improvement: more lenient AI config, and more descriptive error (#6096)
Myles Scolnickc8d5513ddd75
diff --git a/marimo/_server/ai/config.py b/marimo/_server/ai/config.pyindex c34964920d..b621907394 100644--- a/marimo/_server/ai/config.py+++ b/marimo/_server/ai/config.py@@ -56,13 +56,13 @@ class AnyProviderConfig:@classmethoddef for_ollama(cls, config: AiConfig) -> AnyProviderConfig:+ default_base_url = "http://127.0.0.1:11434/v1"return cls._for_openai_like(config,"ollama","Ollama",fallback_key="ollama-placeholder",- # Default base URL for Ollama- fallback_base_url="http://127.0.0.1:11434/v1",+ fallback_base_url=default_base_url,)@classmethod@@ -87,7 +87,7 @@ class AnyProviderConfig:fallback_key: Optional[str] = None,fallback_base_url: Optional[str] = None,) -> AnyProviderConfig:- ai_config = _get_ai_config(config, key, name)+ ai_config = _get_ai_config(config, key)key = _get_key(ai_config, name, fallback_key=fallback_key)kwargs: dict[str, Any] = {@@ -109,11 +109,12 @@ class AnyProviderConfig:@classmethoddef for_anthropic(cls, config: AiConfig) -> AnyProviderConfig:- ai_config = _get_ai_config(config, "anthropic", "Anthropic")+ ai_config = _get_ai_config(config, "anthropic")+ fallback_key = cls.os_key("ANTHROPIC_API_KEY")key = _get_key(ai_config,"Anthropic",- fallback_key=cls.os_key("ANTHROPIC_API_KEY"),+ fallback_key=fallback_key,)return cls(base_url=_get_base_url(ai_config),@@ -126,7 +127,7 @@ class AnyProviderConfig:fallback_key = cls.os_key("GEMINI_API_KEY") or cls.os_key("GOOGLE_API_KEY")- ai_config = _get_ai_config(config, "google", "Google AI")+ ai_config = _get_ai_config(config, "google")key = _get_key(ai_config,"Google AI",@@ -140,7 +141,7 @@ class AnyProviderConfig:@classmethoddef for_bedrock(cls, config: AiConfig) -> AnyProviderConfig:- ai_config = _get_ai_config(config, "bedrock", "Bedrock")+ ai_config = _get_ai_config(config, "bedrock")key = _get_key(ai_config, "Bedrock")return cls(base_url=_get_base_url(ai_config),@@ -186,12 +187,9 @@ def _get_tools(mode: CopilotMode) -> list[Tool]:return tool_manager.get_tools_for_mode(mode)-def _get_ai_config(config: AiConfig, key: str, name: str) -> dict[str, Any]:+def _get_ai_config(config: AiConfig, key: str) -> dict[str, Any]:if key not in config:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail=f"{name} config not found",- )+ return {}return cast(dict[str, Any], config.get(key, {}))@@ -242,7 +240,7 @@ def _get_key(if not isinstance(config, dict):raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,- detail="Invalid config",+ detail=f"Invalid config for {name}. Go to Settings > AI to configure.",)config = cast(dict[str, Any], config)@@ -273,17 +271,23 @@ def _get_key(raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,- detail=f"{name} API key not configured",+ detail=f"{name} API key not configured. Go to Settings > AI to configure.",)def _get_base_url(config: Any, name: str = "") -> Optional[str]:"""Get the base URL for a given provider."""if not isinstance(config, dict):- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Invalid config",- )+ if name:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail=f"{name} is not configured. Go to Settings > AI to configure.",+ )+ else:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Invalid config. Go to Settings > AI to configure.",+ )if name == "Bedrock":if "region_name" in config:diff --git a/tests/_server/ai/test_ai_config.py b/tests/_server/ai/test_ai_config.pyindex 944f745497..4c86b85818 100644--- a/tests/_server/ai/test_ai_config.py+++ b/tests/_server/ai/test_ai_config.py@@ -110,6 +110,13 @@ class TestAnyProviderConfig:assert provider_config.api_key == "test-ollama-key"assert provider_config.base_url == "http://localhost:11434"+ def test_for_ollama_empty(self):+ config: AiConfig = {}+ provider_config = AnyProviderConfig.for_ollama(config)+ assert isinstance(provider_config, AnyProviderConfig)+ assert provider_config.api_key == "ollama-placeholder"+ assert provider_config.base_url == "http://127.0.0.1:11434/v1"+def test_for_ollama_placeholder_key(self):"""Test Ollama configuration with default URL gets placeholder key."""config: AiConfig = {@@ -344,6 +351,13 @@ class TestProviderConfigWithFallback:assert provider_config.api_key == "env-openai-key"+ @patch.dict(os.environ, {"OPENAI_API_KEY": "env-openai-key"})+ def test_for_openai_empty(self) -> None:+ """Test OpenAI config uses fallback key when config is missing api_key and config is empty."""+ config: AiConfig = {}+ provider_config = AnyProviderConfig.for_openai(config)+ assert provider_config.api_key == "env-openai-key"+@patch.dict(os.environ, {"OPENAI_API_KEY": "env-openai-key"})def test_for_openai_config_key_takes_precedence(self) -> None:"""Test OpenAI config key takes precedence over environment variable."""@@ -723,19 +737,17 @@ class TestGetAiConfig:"""Test successful retrieval of AI config."""config: AiConfig = {"open_ai": {"api_key": "test-key"}}- result = _get_ai_config(config, "open_ai", "OpenAI")+ result = _get_ai_config(config, "open_ai")assert result == {"api_key": "test-key"}def test_get_ai_config_missing_key(self):- """Test error when AI config key is missing."""+ """Test that _get_ai_config returns empty dict when AI config key is missing."""config: AiConfig = {}- with pytest.raises(HTTPException) as exc_info:- _get_ai_config(config, "open_ai", "OpenAI")+ result = _get_ai_config(config, "open_ai")- assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "OpenAI config not found" in str(exc_info.value.detail)+ assert result == {}class TestUtilityFunctions:@@ -921,7 +933,7 @@ class TestEdgeCases:AnyProviderConfig.for_openai(config)assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "OpenAI config not found" in str(exc_info.value.detail)+ assert "OpenAI API key not configured" in str(exc_info.value.detail)def test_anthropic_config_missing(self):"""Test error when Anthropic config is missing."""@@ -931,7 +943,7 @@ class TestEdgeCases:AnyProviderConfig.for_anthropic(config)assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "Anthropic config not found" in str(exc_info.value.detail)+ assert "Anthropic API key not configured" in str(exc_info.value.detail)def test_google_config_missing(self):"""Test error when Google config is missing."""@@ -941,17 +953,17 @@ class TestEdgeCases:AnyProviderConfig.for_google(config)assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "Google AI config not found" in str(exc_info.value.detail)+ assert "Google AI API key not configured" in str(exc_info.value.detail)def test_bedrock_config_missing(self):- """Test error when Bedrock config is missing."""+ """Test when Bedrock config is missing, should not error since could use environment variables."""config: AiConfig = {}- with pytest.raises(HTTPException) as exc_info:- AnyProviderConfig.for_bedrock(config)-- assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "Bedrock config not found" in str(exc_info.value.detail)+ provider_config = AnyProviderConfig.for_bedrock(config)+ assert provider_config == AnyProviderConfig(+ base_url=None,+ api_key="",+ )def test_azure_config_missing(self):"""Test error when Azure config is missing."""@@ -961,17 +973,20 @@ class TestEdgeCases:AnyProviderConfig.for_azure(config)assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "Azure OpenAI config not found" in str(exc_info.value.detail)+ assert "Azure OpenAI API key not configured" in str(+ exc_info.value.detail+ )def test_ollama_config_missing(self):- """Test error when Ollama config is missing."""+ """Test should not error when Ollama config is missing."""config: AiConfig = {}- with pytest.raises(HTTPException) as exc_info:- AnyProviderConfig.for_ollama(config)-- assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "Ollama config not found" in str(exc_info.value.detail)+ provider_config = AnyProviderConfig.for_ollama(config)+ assert provider_config == AnyProviderConfig(+ base_url="http://127.0.0.1:11434/v1",+ api_key="ollama-placeholder",+ ssl_verify=True,+ )def test_openai_compatible_config_missing(self):"""Test error when OpenAI Compatible config is missing."""@@ -981,7 +996,7 @@ class TestEdgeCases:AnyProviderConfig.for_openai_compatible(config)assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "OpenAI Compatible config not found" in str(+ assert "OpenAI Compatible API key not configured" in str(exc_info.value.detail)@@ -993,4 +1008,4 @@ class TestEdgeCases:AnyProviderConfig.for_github(config)assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST- assert "GitHub config not found" in str(exc_info.value.detail)+ assert "GitHub API key not configured" in str(exc_info.value.detail)diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex 8251fda008..218cf6aa0b 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -95,7 +95,9 @@ class TestOpenAiEndpoints:},)assert response.status_code == 400, response.text- assert response.json() == {"detail": "OpenAI API key not configured"}+ assert response.json() == {+ "detail": "OpenAI API key not configured. Go to Settings > AI to configure."+ }@staticmethod@with_session(SESSION_ID)@@ -341,7 +343,9 @@ class TestOpenAiEndpoints:},)assert response.status_code == 400, response.text- assert response.json() == {"detail": "OpenAI API key not configured"}+ assert response.json() == {+ "detail": "OpenAI API key not configured. Go to Settings > AI to configure."+ }@staticmethod@with_session(SESSION_ID)@@ -419,7 +423,7 @@ class TestAnthropicAiEndpoints:)assert response.status_code == 400, response.textassert response.json() == {- "detail": "Anthropic API key not configured"+ "detail": "Anthropic API key not configured. Go to Settings > AI to configure."}@staticmethod@@ -597,7 +601,7 @@ class TestGoogleAiEndpoints:)assert response.status_code == 400, response.textassert response.json() == {- "detail": "Google AI API key not configured"+ "detail": "Google AI API key not configured. Go to Settings > AI to configure."}@staticmethod