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
fix: custom config used for inline-completions with ollama (#4257)
Myles Scolnick13c7d12be236
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.pyindex 8665d23285..7c5425f908 100644--- a/marimo/_server/ai/providers.py+++ b/marimo/_server/ai/providers.py@@ -3,8 +3,16 @@ from __future__ import annotationsfrom abc import ABC, abstractmethodfrom collections.abc import Generator-from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar, cast+from typing import (+ TYPE_CHECKING,+ Any,+ Generic,+ Optional,+ TypeVar,+ cast,+)+from attr import dataclassfrom starlette.exceptions import HTTPExceptionfrom marimo import _loggers@@ -14,7 +22,7 @@ from marimo._ai._convert import (convert_to_openai_messages,)from marimo._ai._types import ChatMessage-from marimo._config.config import AiConfig, MarimoConfig+from marimo._config.config import AiConfig, CompletionConfig, MarimoConfigfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._server.api.status import HTTPStatus@@ -50,10 +58,95 @@ DEFAULT_MAX_TOKENS = 4096DEFAULT_MODEL = "gpt-4o-mini"+@dataclass+class AnyProviderConfig:+ base_url: Optional[str]+ api_key: str+ ssl_verify: Optional[bool] = None+ ca_bundle_path: Optional[str] = None+ client_pem: Optional[str] = None++ @staticmethod+ def for_openai(config: AiConfig) -> AnyProviderConfig:+ if "open_ai" not in config:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="OpenAI config not found",+ )+ key = _get_key(config["open_ai"], "OpenAI")+ return AnyProviderConfig(+ base_url=_get_base_url(config["open_ai"]),+ api_key=key,+ 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),+ )++ @staticmethod+ def for_anthropic(config: AiConfig) -> AnyProviderConfig:+ if "anthropic" not in config:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Anthropic config not found",+ )+ key = _get_key(config["anthropic"], "Anthropic")+ return AnyProviderConfig(+ base_url=_get_base_url(config["anthropic"]),+ api_key=key,+ )++ @staticmethod+ def for_google(config: AiConfig) -> AnyProviderConfig:+ if "google" not in config:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Google config not found",+ )+ key = _get_key(config["google"], "Google AI")+ return AnyProviderConfig(+ base_url=_get_base_url(config["google"]),+ api_key=key,+ )++ @staticmethod+ def for_completion(config: CompletionConfig) -> AnyProviderConfig:+ key = _get_key(config, "AI completion")+ return AnyProviderConfig(+ base_url=_get_base_url(config),+ api_key=key,+ )++ @staticmethod+ def for_model(model: str, config: AiConfig) -> AnyProviderConfig:+ if model.startswith("claude"):+ return AnyProviderConfig.for_anthropic(config)+ elif model.startswith("google") or model.startswith("gemini"):+ return AnyProviderConfig.for_google(config)+ else:+ return AnyProviderConfig.for_openai(config)+++def _get_key(config: Any, name: str) -> str:+ if "api_key" in config:+ key = config["api_key"]+ if key:+ return cast(str, key)+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail=f"{name} API key not configured",+ )+++def _get_base_url(config: Any) -> Optional[str]:+ if "base_url" in config:+ return cast(str, config["base_url"])+ return None++class CompletionProvider(Generic[ResponseT, StreamT], ABC):"""Base class for AI completion providers."""- def __init__(self, model: str, config: AiConfig):+ def __init__(self, model: str, config: AnyProviderConfig):self.model = modelself.config = config@@ -156,7 +249,7 @@ class OpenAIProvider("ChatCompletionChunk", "OpenAiStream[ChatCompletionChunk]"]):- def get_client(self, config: AiConfig) -> OpenAI:+ def get_client(self, config: AnyProviderConfig) -> OpenAI:DependencyManager.openai.require(why="for AI assistance with OpenAI")import ssl@@ -169,32 +262,13 @@ class OpenAIProvider(import httpxfrom openai import AzureOpenAI, OpenAI- if "open_ai" not in config or "api_key" not in config["open_ai"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="OpenAI API key not configured",- )-- key: str = config["open_ai"]["api_key"]- if not key:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="OpenAI API key not configured",- )-- base_url: Optional[str] = config["open_ai"].get("base_url", None)- if not base_url:- base_url = None-- # Extract open_ai config once to avoid multiple dictionary lookups- open_ai_config = config["open_ai"]+ base_url = config.base_url+ key = config.api_key# Add SSL parameters/values- ssl_verify: bool = open_ai_config.get(- "ssl_verify", True- ) # Default to True to match httpx behavior- ca_bundle_path: Optional[str] = open_ai_config.get("ca_bundle_path")- client_pem: Optional[str] = open_ai_config.get("client_pem")+ ssl_verify: bool = config.ssl_verify or True+ ca_bundle_path: Optional[str] = config.ca_bundle_path+ client_pem: Optional[str] = config.client_pem# Check if ca_bundle_path and client_pem are valid filesif ca_bundle_path:@@ -302,26 +376,13 @@ class AnthropicProvider("RawMessageStreamEvent", "AnthropicStream[RawMessageStreamEvent]"]):- def get_client(self, config: AiConfig) -> Client:+ def get_client(self, config: AnyProviderConfig) -> Client:DependencyManager.anthropic.require(why="for AI assistance with Anthropic")from anthropic import Client- if "anthropic" not in config or "api_key" not in config["anthropic"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Anthropic API key not configured",- )-- key: str = config["anthropic"]["api_key"]- if not key:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Anthropic API key not configured",- )-- return Client(api_key=key)+ return Client(api_key=config.api_key)def stream_completion(self,@@ -359,7 +420,7 @@ class GoogleProvider(CompletionProvider["GenerateContentResponse", "GenerateContentResponse"]):def get_client(- self, config: AiConfig, model: str, system_prompt: str+ self, config: AnyProviderConfig, model: str, system_prompt: str) -> GenerativeModel:try:import google.generativeai as genai@@ -369,20 +430,7 @@ class GoogleProvider()import google.generativeai as genai # type: ignore- if "google" not in config or "api_key" not in config["google"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Google AI API key not configured",- )-- key: str = config["google"]["api_key"]- if not key:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Google AI API key not configured",- )-- genai.configure(api_key=key)+ genai.configure(api_key=config.api_key)return genai.GenerativeModel(model_name=model,system_instruction=system_prompt,@@ -414,10 +462,8 @@ class GoogleProvider(def get_completion_provider(- config: AiConfig, model_override: Optional[str] = None+ config: AnyProviderConfig, model: str) -> CompletionProvider[Any, Any]:- model = model_override or get_model(config)-if model.startswith("claude"):return AnthropicProvider(model, config)elif model.startswith("google") or model.startswith("gemini"):diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex 5c23562690..ba072f998f 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -13,8 +13,10 @@ from marimo._config.config import AiConfig, MarimoConfigfrom marimo._server.ai.prompts import Prompterfrom marimo._server.ai.providers import (DEFAULT_MODEL,+ AnyProviderConfig,get_completion_provider,get_max_tokens,+ get_model,)from marimo._server.api.deps import AppStatefrom marimo._server.api.status import HTTPStatus@@ -87,7 +89,11 @@ async def ai_completion(user_prompt=body.prompt, include_other_code=body.include_other_code)- provider = get_completion_provider(ai_config)+ model = get_model(ai_config)+ provider = get_completion_provider(+ AnyProviderConfig.for_model(model, ai_config),+ model=model,+ )response = provider.stream_completion(messages=[ChatMessage(role="user", content=prompt)],system_prompt=system_prompt,@@ -134,7 +140,11 @@ async def ai_chat(max_tokens = get_max_tokens(config)- provider = get_completion_provider(ai_config, model_override=body.model)+ model = body.model or get_model(ai_config)+ provider = get_completion_provider(+ AnyProviderConfig.for_model(model, ai_config),+ model=model,+ )response = provider.stream_completion(messages=messages,system_prompt=system_prompt,@@ -178,7 +188,6 @@ async def ai_inline_completion(prompt = f"{body.prefix}<FILL_ME>{body.suffix}"messages = [ChatMessage(role="user", content=prompt)]system_prompt = Prompter.get_inline_system_prompt(language=body.language)- ai_config = get_ai_config(config)# This is currently not configurable and smaller than the default# of 4096, since it is smaller/faster for inline completions@@ -189,7 +198,10 @@ async def ai_inline_completion(except Exception:model = DEFAULT_MODEL- provider = get_completion_provider(ai_config, model_override=model)+ provider = get_completion_provider(+ AnyProviderConfig.for_completion(config["completion"]),+ model=model,+ )response = provider.stream_completion(messages=messages,system_prompt=system_prompt,diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex 907ebd546d..b3cb862fc1 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -118,6 +118,9 @@ class TestOpenAiEndpoints:"messages"][1]["content"]assert prompt == ("Help me create a dataframe")+ # Assert the model it was called with+ model = oaiclient.chat.completions.create.call_args.kwargs["model"]+ assert model == "some-openai-model"@staticmethod@with_session(SESSION_ID)@@ -218,6 +221,9 @@ class TestOpenAiEndpoints:# Assert the base_url it was called withbase_url = openai_mock.call_args.kwargs["base_url"]assert base_url == "https://my-openai-instance.com"+ # Assert the model it was called with+ model = oaiclient.chat.completions.create.call_args.kwargs["model"]+ assert model == "some-openai-model-with-base-url"@staticmethod@with_session(SESSION_ID)@@ -255,6 +261,9 @@ class TestOpenAiEndpoints:"messages"][0]["content"]assert "python" in system_prompt+ # Assert the model it was called with+ model = oaiclient.chat.completions.create.call_args.kwargs["model"]+ assert model == "gpt-marimo-for-inline-completion"@staticmethod@with_session(SESSION_ID)@@ -276,7 +285,9 @@ class TestOpenAiEndpoints:},)assert response.status_code == 400, response.text- assert response.json() == {"detail": "OpenAI API key not configured"}+ assert response.json() == {+ "detail": "AI completion API key not configured"+ }@staticmethod@with_session(SESSION_ID)@@ -309,6 +320,9 @@ class TestOpenAiEndpoints:"messages"][0]["content"]assert "sql" in system_prompt+ # Assert model+ model = oaiclient.chat.completions.create.call_args.kwargs["model"]+ assert model == "gpt-marimo-for-inline-completion"@pytest.mark.skipif(@@ -372,6 +386,9 @@ class TestAnthropicAiEndpoints:assert prompt == ("Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>")+ # Assert the model it was called with+ model = anthropic_client.messages.create.call_args.kwargs["model"]+ assert model == "claude-3.5"@staticmethod@with_session(SESSION_ID)@@ -404,6 +421,9 @@ class TestAnthropicAiEndpoints:"messages"][0]["content"]assert prompt == "import pandas as pd\n<FILL_ME>\ndf.head()"+ # Assert the model it was called with+ model = anthropic_client.messages.create.call_args.kwargs["model"]+ assert model == "claude-3.5-for-inline-completion"@pytest.mark.skipif(@@ -509,7 +529,18 @@ def openai_config(config: UserConfigManager):prev_config = config.get_config()try:config.save_config(- {"ai": {"open_ai": {"api_key": "fake-api", "model": ""}}}+ {+ "ai": {+ "open_ai": {+ "api_key": "fake-api",+ "model": "some-openai-model",+ }+ },+ "completion": {+ "model": "gpt-marimo-for-inline-completion",+ "api_key": "fake-api",+ },+ })yieldfinally:@@ -527,7 +558,11 @@ def openai_config_custom_model(config: UserConfigManager):"api_key": "fake-api","model": "gpt-marimo",}- }+ },+ "completion": {+ "model": "gpt-marimo-for-inline-completion",+ "api_key": "fake-api",+ },})yield@@ -545,9 +580,14 @@ def openai_config_custom_base_url(config: UserConfigManager):"open_ai": {"api_key": "fake-api","base_url": "https://my-openai-instance.com",- "model": "",+ "model": "some-openai-model-with-base-url",}- }+ },+ "completion": {+ "model": "gpt-marimo-for-inline-completion",+ "api_key": "fake-api",+ "base_url": "https://my-openai-instance.com",+ },})yield@@ -559,7 +599,15 @@ def openai_config_custom_base_url(config: UserConfigManager):def no_openai_config(config: UserConfigManager):prev_config = config.get_config()try:- config.save_config({"ai": {"open_ai": {"api_key": "", "model": ""}}})+ config.save_config(+ {+ "ai": {"open_ai": {"api_key": "", "model": ""}},+ "completion": {+ "model": "gpt-marimo-for-inline-completion",+ "api_key": "",+ },+ }+ )yieldfinally:config.save_config(prev_config)@@ -574,7 +622,11 @@ def no_anthropic_config(config: UserConfigManager):"ai": {"open_ai": {"model": "claude-3.5"},"anthropic": {"api_key": ""},- }+ },+ "completion": {+ "model": "claude-3.5-for-inline-completion",+ "api_key": "",+ },})yield@@ -593,7 +645,7 @@ def anthropic_config(config: UserConfigManager):"anthropic": {"api_key": "fake-key"},},"completion": {- "model": "claude-3.5",+ "model": "claude-3.5-for-inline-completion","api_key": "fake-key",},}@@ -614,7 +666,7 @@ def google_ai_config(config: UserConfigManager):"google": {"api_key": "fake-key"},},"completion": {- "model": "gemini-1.5-pro",+ "model": "gemini-1.5-pro-for-inline-completion","api_key": "fake-key",},}