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
feat: custom inline completions provider (ollama, anthropic, openai, gemini) (#4136)
Myles Scolnickf98326c6b03e
diff --git a/docs/guides/editor_features/ai_completion.md b/docs/guides/editor_features/ai_completion.mdindex 40121fe6ec..5466c2894c 100644--- a/docs/guides/editor_features/ai_completion.md+++ b/docs/guides/editor_features/ai_completion.md@@ -70,6 +70,29 @@ copilot = "codeium"activate_on_typing = true```+## Custom Copilot++marimo also supports integrating with custom LLM providers for code completion suggestions. This allows you to use your own LLM service to provide in-line code suggestions based on internal providers or local models (e.g. Ollama). You may also use OpenAI, Anthropic, or Google AI by providing your own API keys.++To configure a custom copilot:++1. Ensure you have an LLM provider that offers API access for code completion (either external or running locally)+2. Add the following configuration to your `marimo.toml` (or configure in the UI settings):++```toml title="marimo.toml"+[completion]+copilot = "custom"+api_key = "your-llm-api-key"+model = "your-llm-model-name"+base_url = "http://127.0.0.1:11434/v1" # or https://your-llm-api-endpoint.com+```++The configuration options include:++- `api_key`: Your LLM provider's API key. This may not be required for local models, so you can set it to any random string.+- `model`: The specific model to use for completion suggestions.+- `base_url`: The endpoint URL for your LLM provider's API+## Generate code with our AI assistantmarimo has built-in support for generating and refactoring code with AI, with a variety of providers. marimo works with hosted AI providers, such as OpenAI, Anthropic, and Google, as well as local models served via Ollama.diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 775c719879..2bb7ab5d62 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -130,6 +130,7 @@ export const UserConfigForm: React.FC = () => {if (copilot === false) {return null;}+if (copilot === "codeium") {return (<>@@ -171,9 +172,81 @@ export const UserConfigForm: React.FC = () => {</>);}+if (copilot === "github") {return <CopilotConfig />;}++ if (copilot === "custom") {+ return (+ <>+ <p className="text-sm text-muted-secondary">+ Configure your custom AI completion provider with the following+ settings.+ </p>+ <FormField+ control={form.control}+ name="completion.model"+ render={({ field }) => (+ <FormItem className={formItemClasses}>+ <FormLabel>Model</FormLabel>+ <FormControl>+ <Input+ data-testid="custom-model-input"+ className="m-0 inline-flex"+ placeholder="Qwen2.5-Coder-7B"+ {...field}+ value={field.value || ""}+ />+ </FormControl>+ <FormMessage />+ <IsOverridden userConfig={config} name="completion.model" />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="completion.base_url"+ render={({ field }) => (+ <FormItem className={formItemClasses}>+ <FormLabel>Base URL</FormLabel>+ <FormControl>+ <Input+ data-testid="custom-base-url-input"+ className="m-0 inline-flex"+ placeholder="http://localhost:11434/v1"+ {...field}+ value={field.value || ""}+ />+ </FormControl>+ <FormMessage />+ <IsOverridden userConfig={config} name="completion.base_url" />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="completion.api_key"+ render={({ field }) => (+ <FormItem className={formItemClasses}>+ <FormLabel>API Key</FormLabel>+ <FormControl>+ <Input+ data-testid="custom-api-key-input"+ className="m-0 inline-flex"+ placeholder="key"+ {...field}+ value={field.value || ""}+ />+ </FormControl>+ <FormMessage />+ <IsOverridden userConfig={config} name="completion.api_key" />+ </FormItem>+ )}+ />+ </>+ );+ }};const renderBody = () => {@@ -774,7 +847,8 @@ export const UserConfigForm: React.FC = () => {<><SettingGroup title="AI Code Completion"><p className="text-sm text-muted-secondary">- You may use GitHub Copilot or Codeium for AI code completion.+ You may use GitHub Copilot, Codeium, or a custom provider (e.g.+ Ollama) for AI code completion.</p><FormField@@ -804,11 +878,13 @@ export const UserConfigForm: React.FC = () => {disabled={field.disabled}className="inline-flex mr-2">- {["none", "github", "codeium"].map((option) => (- <option value={option} key={option}>- {option}- </option>- ))}+ {["none", "github", "codeium", "custom"].map(+ (option) => (+ <option value={option} key={option}>+ {option}+ </option>+ ),+ )}</NativeSelect></FormControl><FormMessage />diff --git a/frontend/src/core/codemirror/copilot/extension.ts b/frontend/src/core/codemirror/copilot/extension.tsindex c0e52de3af..304d6426d7 100644--- a/frontend/src/core/codemirror/copilot/extension.ts+++ b/frontend/src/core/codemirror/copilot/extension.ts@@ -25,6 +25,9 @@ import type {CopilotGetCompletionsResult,} from "./types";import { Logger } from "@/utils/Logger";+import { languageAdapterState } from "../language/extension";+import { API } from "@/core/network/api";+import type { AiInlineCompletionRequest } from "@/core/kernel/messages";const copilotCompartment = new Compartment();@@ -91,6 +94,47 @@ export const copilotBundle = (config: CompletionConfig): Extension => {);}+ if (config.copilot === "custom") {+ extensions.push(+ inlineSuggestion({+ delay: 500,+ fetchFn: async (state) => {+ if (state.doc.length === 0) {+ return "";+ }++ // If not focused, don't fetch+ const prefix = state.doc.sliceString(0, state.selection.main.head);+ const suffix = state.doc.sliceString(+ state.selection.main.head,+ state.doc.length,+ );++ // If no prefix, don't fetch+ if (prefix.length === 0) {+ return "";+ }++ const language = state.field(languageAdapterState).type;+ let res = await API.post<AiInlineCompletionRequest, string>(+ "/ai/inline_completion",+ { prefix, suffix, language },+ );++ // Sometimes the prefix might get included in the response, so we need to trim it+ if (prefix && res.startsWith(prefix)) {+ res = res.slice(prefix.length);+ }+ if (suffix && res.endsWith(suffix)) {+ res = res.slice(0, -suffix.length);+ }++ return res;+ },+ }),+ );+ }+return [...extensions,// grab the first 4 elements of the array is the LSP without hover/autocompletiondiff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 2d775b0003..2def52d800 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -35,7 +35,7 @@ export const UserConfigSchema = z.object({activate_on_typing: z.boolean().default(true),copilot: z- .union([z.boolean(), z.enum(["github", "codeium"])])+ .union([z.boolean(), z.enum(["github", "codeium", "custom"])]).default(false).transform((copilot) => {if (copilot === true) {diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex 9b6fa84820..668d43eecd 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -14,6 +14,7 @@ export const DATA_TYPES = ["unknown",] as const;export type Banner = OperationMessageData<"banner">;+export type AiInlineCompletionRequest = schemas["AiInlineCompletionRequest"];export type DataTableColumn = schemas["DataTableColumn"];export type DataTable = schemas["DataTable"];export type Database = schemas["Database"];diff --git a/marimo/_ai/_convert.py b/marimo/_ai/_convert.pyindex d07a778e2c..06aa71d31f 100644--- a/marimo/_ai/_convert.py+++ b/marimo/_ai/_convert.py@@ -2,10 +2,16 @@from __future__ import annotationsimport base64-from typing import Any, TypedDict+from typing import TYPE_CHECKING, Anyfrom marimo._ai._types import ChatMessage+if TYPE_CHECKING:+ from google.generativeai.types import ( # type: ignore[import-not-found]+ ContentDict,+ PartType,+ )+def convert_to_openai_messages(messages: list[ChatMessage],@@ -118,19 +124,13 @@ def convert_to_groq_messages(return groq_messages-# Matches from google.generativeai.types import content_types-class BlobDict(TypedDict):- mime_type: str- data: bytes--def convert_to_google_messages(messages: list[ChatMessage],-) -> list[dict[Any, Any]]:- google_messages: list[dict[Any, Any]] = []+) -> list[ContentDict]:+ google_messages: list[ContentDict] = []for message in messages:- parts: list[str | BlobDict] = [str(message.content)]+ parts: list[PartType] = [str(message.content)]if message.attachments:for attachment in message.attachments:content_type = attachment.content_type or "text/plain"diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 179233d75b..b5a511e5a0 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -125,7 +125,12 @@ def _generate_server_api_schema() -> dict[str, Any]:snippets.Snippets,requests.SetUIElementValueRequest,# Requests/responses+ completion.SchemaColumn,+ completion.SchemaTable,+ completion.AiCompletionContext,completion.AiCompletionRequest,+ completion.AiInlineCompletionRequest,+ completion.ChatRequest,export.ExportAsHTMLRequest,export.ExportAsMarkdownRequest,export.ExportAsScriptRequest,diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 52f1050b72..e41fec1e7c 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -38,13 +38,24 @@ class CompletionConfig(TypedDict):- `activate_on_typing`: if `False`, completion won't activateuntil the completion hotkey is entered- - `copilot`: if `True`, enable the GitHub Copilot language server+ - `copilot`: one of `"github"`, `"codeium"`, or `"custom"`+ - `codeium_api_key`: the Codeium API key+ - `api_key`: the API key for the LLM provider, when `copilot` is `"custom"`+ - `model`: the model to use, when `copilot` is `"custom"`+ - `base_url`: the base URL for the API, when `copilot` is `"custom"`"""activate_on_typing: bool- copilot: Union[bool, Literal["github", "codeium"]]+ copilot: Union[bool, Literal["github", "codeium", "custom"]]++ # Codeiumcodeium_api_key: NotRequired[Optional[str]]+ # Custom+ api_key: NotRequired[Optional[str]]+ model: NotRequired[Optional[str]]+ base_url: NotRequired[Optional[str]]+@mddoc@dataclassdiff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.pyindex bb4c249e4f..13ef2d7938 100644--- a/marimo/_server/ai/prompts.py+++ b/marimo/_server/ai/prompts.py@@ -73,6 +73,13 @@ class Prompter:return system_prompt+ @staticmethod+ def get_inline_system_prompt(*, language: Language) -> str:+ return (+ f"You are a {language} programmer that replaces <FILL_ME> part with the right code. "+ "Only output the code that replaces <FILL_ME> part. Do not add any explanation or markdown."+ )+def get_prompt(self, *, user_prompt: str, include_other_code: str) -> str:prompt = user_promptif include_other_code:diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.pynew file mode 100644index 0000000000..3071cf0766--- /dev/null+++ b/marimo/_server/ai/providers.py@@ -0,0 +1,377 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from abc import ABC, abstractmethod+from collections.abc import Generator+from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar, cast++from starlette.exceptions import HTTPException++from marimo import _loggers+from marimo._ai._convert import (+ convert_to_anthropic_messages,+ convert_to_google_messages,+ convert_to_openai_messages,+)+from marimo._ai._types import ChatMessage+from marimo._config.config import AiConfig, MarimoConfig+from marimo._dependencies.dependencies import DependencyManager+from marimo._server.api.status import HTTPStatus++if TYPE_CHECKING:+ from anthropic import ( # type: ignore[import-not-found]+ Client,+ Stream as AnthropicStream,+ )+ from anthropic.types import ( # type: ignore[import-not-found]+ RawMessageStreamEvent,+ )+ from google.generativeai import ( # type: ignore[import-not-found]+ GenerativeModel,+ )+ from google.generativeai.types import ( # type: ignore[import-not-found]+ GenerateContentResponse,+ )+ from openai import ( # type: ignore[import-not-found]+ OpenAI,+ Stream as OpenAiStream,+ )+ from openai.types.chat import ( # type: ignore[import-not-found]+ ChatCompletionChunk,+ )+++ResponseT = TypeVar("ResponseT")+StreamT = TypeVar("StreamT")++LOGGER = _loggers.marimo_logger()++DEFAULT_MAX_TOKENS = 4096+DEFAULT_MODEL = "gpt-4o-mini"+++class CompletionProvider(Generic[ResponseT, StreamT], ABC):+ """Base class for AI completion providers."""++ def __init__(self, model: str, config: AiConfig):+ self.model = model+ self.config = config++ @abstractmethod+ def stream_completion(+ self,+ messages: list[ChatMessage],+ system_prompt: str,+ max_tokens: int,+ ) -> StreamT:+ """Create a completion stream."""+ pass++ @abstractmethod+ def extract_content(self, response: ResponseT) -> str | None:+ """Extract content from a response chunk."""+ pass++ def as_stream_response(+ self, response: StreamT+ ) -> Generator[str, None, None]:+ """Convert a stream to a generator of strings."""+ original_content = ""+ buffer = ""++ for chunk in cast(Generator[ResponseT, None, None], response):+ content = self.extract_content(chunk)+ if not content:+ continue++ buffer += content+ original_content += content++ yield buffer+ buffer = ""++ LOGGER.debug(f"Completion content: {original_content}")++ def collect_stream(self, response: StreamT) -> str:+ """Collect a stream into a single string."""+ return "".join(self.as_stream_response(response))++ def make_stream_response(+ self, response: StreamT+ ) -> Generator[str, None, None]:+ """Convert a stream to a generator of strings, handling code blocks."""+ original_content = ""+ buffer = ""+ in_code_fence = False++ for chunk in cast(Generator[ResponseT, None, None], response):+ content = self.extract_content(chunk)+ if not content:+ continue++ buffer += content+ original_content += content+ first_newline = buffer.find("\n")++ # Open code-fence, with no newline+ # wait for the next newline+ if (+ buffer.startswith("```")+ and first_newline == -1+ and not in_code_fence+ ):+ continue++ if (+ buffer.startswith("```")+ and first_newline > 0+ and not in_code_fence+ ):+ # And also ends with ```+ if buffer.endswith("```"):+ yield buffer[first_newline + 1 : -3]+ buffer = ""+ in_code_fence = False+ continue++ yield buffer[first_newline + 1 :]+ buffer = ""+ in_code_fence = True+ continue++ if buffer.endswith("```") and in_code_fence:+ yield buffer[:-3]+ buffer = ""+ in_code_fence = False+ continue++ yield buffer+ buffer = ""++ LOGGER.debug(f"Completion content: {original_content}")+++class OpenAIProvider(+ CompletionProvider[+ "ChatCompletionChunk", "OpenAiStream[ChatCompletionChunk]"+ ]+):+ def get_client(self, config: AiConfig) -> OpenAI:+ DependencyManager.openai.require(why="for AI assistance with OpenAI")++ from urllib.parse import parse_qs, urlparse++ from 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++ # Azure OpenAI clients are instantiated slightly differently+ parsed_url = urlparse(base_url)+ if parsed_url.hostname and cast(str, parsed_url.hostname).endswith(+ ".openai.azure.com"+ ):+ deployment_model = cast(str, parsed_url.path).split("/")[3]+ api_version = parse_qs(cast(str, parsed_url.query))["api-version"][+ 0+ ]+ return AzureOpenAI(+ api_key=key,+ api_version=api_version,+ azure_deployment=deployment_model,+ azure_endpoint=f"{cast(str, parsed_url.scheme)}://{cast(str, parsed_url.hostname)}",+ )+ else:+ return OpenAI(+ default_headers={"api-key": key},+ api_key=key,+ base_url=base_url,+ )++ def stream_completion(+ self,+ messages: list[ChatMessage],+ system_prompt: str,+ max_tokens: int,+ ) -> OpenAiStream[ChatCompletionChunk]:+ client = self.get_client(self.config)+ return client.chat.completions.create(+ model=self.model,+ messages=cast(+ Any,+ convert_to_openai_messages(+ [ChatMessage(role="system", content=system_prompt)]+ + messages+ ),+ ),+ max_tokens=max_tokens,+ stream=True,+ timeout=15,+ )++ def extract_content(self, response: ChatCompletionChunk) -> str | None:+ if (+ hasattr(response, "choices")+ and response.choices+ and response.choices[0].delta+ ):+ return response.choices[0].delta.content+ return None+++class AnthropicProvider(+ CompletionProvider[+ "RawMessageStreamEvent", "AnthropicStream[RawMessageStreamEvent]"+ ]+):+ def get_client(self, config: AiConfig) -> 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)++ def stream_completion(+ self,+ messages: list[ChatMessage],+ system_prompt: str,+ max_tokens: int,+ ) -> AnthropicStream[RawMessageStreamEvent]:+ client = self.get_client(self.config)+ return client.messages.create(+ model=self.model,+ max_tokens=max_tokens,+ messages=cast(+ Any,+ convert_to_anthropic_messages(messages),+ ),+ system=system_prompt,+ stream=True,+ temperature=0,+ )++ def extract_content(self, response: RawMessageStreamEvent) -> str | None:+ from anthropic.types import RawContentBlockDeltaEvent, TextDelta++ if isinstance(response, TextDelta):+ return response.text # type: ignore[no-any-return]++ if isinstance(response, RawContentBlockDeltaEvent):+ if isinstance(response.delta, TextDelta):+ return response.delta.text # type: ignore[no-any-return]++ return None+++class GoogleProvider(+ CompletionProvider["GenerateContentResponse", "GenerateContentResponse"]+):+ def get_client(+ self, config: AiConfig, model: str, system_prompt: str+ ) -> GenerativeModel:+ try:+ import google.generativeai as genai+ except ImportError:+ DependencyManager.google_ai.require(+ why="for AI assistance with Google AI"+ )+ 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)+ return genai.GenerativeModel(+ model_name=model,+ system_instruction=system_prompt,+ generation_config=genai.GenerationConfig(+ max_output_tokens=DEFAULT_MAX_TOKENS,+ temperature=0,+ ),+ )++ 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,+ },+ )++ def extract_content(self, response: GenerateContentResponse) -> str | None:+ if hasattr(response, "text"):+ return response.text # type: ignore[no-any-return]+ return None+++def get_completion_provider(+ config: AiConfig, model_override: Optional[str] = None+) -> 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"):+ return GoogleProvider(model, config)+ else:+ return OpenAIProvider(model, config)+++def get_model(config: AiConfig) -> str:+ model: str = config.get("open_ai", {}).get("model", DEFAULT_MODEL)+ if not model:+ model = DEFAULT_MODEL+ return model+++def get_max_tokens(config: MarimoConfig) -> int:+ if "ai" not in config:+ return DEFAULT_MAX_TOKENS+ if "max_tokens" not in config["ai"]:+ return DEFAULT_MAX_TOKENS+ return config["ai"]["max_tokens"]diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex ecb12984c1..5c23562690 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -1,318 +1,49 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, Any, Optional, cast+from typing import TYPE_CHECKINGfrom starlette.authentication import requiresfrom starlette.exceptions import HTTPException-from starlette.responses import StreamingResponse+from starlette.responses import PlainTextResponse, StreamingResponsefrom marimo import _loggers-from marimo._ai._convert import (- convert_to_anthropic_messages,- convert_to_google_messages,- convert_to_openai_messages,-)from marimo._ai._types import ChatMessage-from marimo._config.config import MarimoConfig-from marimo._dependencies.dependencies import DependencyManager+from marimo._config.config import AiConfig, MarimoConfigfrom marimo._server.ai.prompts import Prompter+from marimo._server.ai.providers import (+ DEFAULT_MODEL,+ get_completion_provider,+ get_max_tokens,+)from marimo._server.api.deps import AppStatefrom marimo._server.api.status import HTTPStatusfrom marimo._server.api.utils import parse_requestfrom marimo._server.models.completion import (AiCompletionRequest,+ AiInlineCompletionRequest,ChatRequest,)from marimo._server.router import APIRouterif TYPE_CHECKING:- from collections.abc import Generator-- from anthropic import ( # type: ignore[import-not-found]- Client,- Stream as AnthropicStream,- )- from anthropic.types import ( # type: ignore[import-not-found]- RawMessageStreamEvent,- )- from google.generativeai import ( # type: ignore[import-not-found]- GenerativeModel,- )- from google.generativeai.types import ( # type: ignore[import-not-found]- GenerateContentResponse,- )- from openai import ( # type: ignore[import-not-found]- OpenAI,- Stream as OpenAiStream,- )- from openai.types.chat import ( # type: ignore[import-not-found]- ChatCompletionChunk,- )from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for file airouter = APIRouter()-DEFAULT_MAX_TOKENS = 4096---def get_openai_client(config: MarimoConfig) -> OpenAI:- DependencyManager.openai.require(why="for AI assistance with OpenAI")-- from urllib.parse import parse_qs, urlparse-- from openai import ( # type: ignore[import-not-found]- AzureOpenAI,- OpenAI,- )-- if "ai" not in config:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="OpenAI API key not configured",- )- if "open_ai" not in config["ai"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="OpenAI API key not configured",- )- if "api_key" not in config["ai"]["open_ai"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="OpenAI API key not configured",- )-- key: str = config["ai"]["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.get("ai", {}).get("open_ai", {}).get("base_url", None)- )- if not base_url:- base_url = None-- # Azure OpenAI clients are instantiated slightly differently- # To check if we're using Azure, we check the base_url for the format- # https://[subdomain].openai.azure.com/openai/deployments/[model]/chat/completions?api-version=[api_version]- parsed_url = urlparse(base_url)- if parsed_url.hostname and cast(str, parsed_url.hostname).endswith(- ".openai.azure.com"- ):- deployment_model = cast(str, parsed_url.path).split("/")[3]- api_version = parse_qs(cast(str, parsed_url.query))["api-version"][0]- return AzureOpenAI(- api_key=key,- api_version=api_version,- azure_deployment=deployment_model,- azure_endpoint=f"{cast(str, parsed_url.scheme)}://{cast(str, parsed_url.hostname)}",- )- else:- return OpenAI(- default_headers={"api-key": key},- api_key=key,- base_url=base_url,- )---def get_anthropic_client(config: MarimoConfig) -> Client:- DependencyManager.anthropic.require(why="for AI assistance with Anthropic")-- from anthropic import Client # type: ignore[import-not-found]- if "ai" not in config:+def get_ai_config(config: MarimoConfig) -> AiConfig:+ ai_config = config.get("ai", None)+ if ai_config is None:raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,- detail="Anthropic not configured",+ detail="AI is not configured. Configure them in the settings dialog.",)- if "anthropic" not in config["ai"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Anthropic not configured",- )- if "api_key" not in config["ai"]["anthropic"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Anthropic API key not configured",- )-- key: str = config["ai"]["anthropic"]["api_key"]-- if not key:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Anthropic API key not configured",- )-- return Client(api_key=key)---def get_model(config: MarimoConfig) -> str:- model: str = (- config.get("ai", {}).get("open_ai", {}).get("model", "gpt-4-turbo")- )- if not model:- model = "gpt-4-turbo"- return model---def get_max_tokens(config: MarimoConfig) -> int:- if "ai" not in config:- return DEFAULT_MAX_TOKENS- if "max_tokens" not in config["ai"]:- return DEFAULT_MAX_TOKENS- return config["ai"]["max_tokens"]---def get_content(- response: (- RawMessageStreamEvent | ChatCompletionChunk | GenerateContentResponse- ),-) -> str | None:- if (- hasattr(response, "choices")- and response.choices- and response.choices[0].delta- ):- return response.choices[0].delta.content # type: ignore-- if hasattr(response, "text"):- return response.text # type: ignore-- from anthropic.types import ( # type: ignore[import-not-found]- RawContentBlockDeltaEvent,- TextDelta,- )-- if isinstance(response, RawContentBlockDeltaEvent):- if isinstance(response.delta, TextDelta):- return response.delta.text # type: ignore-- return None---def make_stream_response(- response: (- OpenAiStream[ChatCompletionChunk]- | AnthropicStream[RawMessageStreamEvent]- | GenerateContentResponse- ),-) -> Generator[str, None, None]:- original_content = ""- buffer = ""- in_code_fence = False-- for chunk in response:- content = get_content(chunk)- if not content:- continue-- buffer += content- original_content += content- first_newline = buffer.find("\n")-- # Open code-fence, with no newline- # wait for the next newline- if (- buffer.startswith("```")- and first_newline == -1- and not in_code_fence- ):- continue-- if (- buffer.startswith("```")- and first_newline > 0- and not in_code_fence- ):- # And also ends with ```- if buffer.endswith("```"):- yield buffer[first_newline + 1 : -3]- buffer = ""- in_code_fence = False- continue-- yield buffer[first_newline + 1 :]- buffer = ""- in_code_fence = True- continue-- if buffer.endswith("```") and in_code_fence:- yield buffer[:-3]- buffer = ""- in_code_fence = False- continue-- yield buffer- buffer = ""-- LOGGER.debug(f"Completion content: {original_content}")---def as_stream_response(- response: (- OpenAiStream[ChatCompletionChunk]- | AnthropicStream[RawMessageStreamEvent]- | GenerateContentResponse- ),-) -> Generator[str, None, None]:- original_content = ""- buffer = ""-- for chunk in response:- content = get_content(chunk)- if not content:- continue-- buffer += content- original_content += content-- yield buffer- buffer = ""-- LOGGER.debug(f"Completion content: {original_content}")---def get_google_client(config: MarimoConfig, model: str) -> GenerativeModel:- try:- import google.generativeai as genai # type: ignore[import-not-found]- except ImportError:- DependencyManager.google_ai.require(- why="for AI assistance with Google AI"- )-- if "ai" not in config or "google" not in config["ai"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Google AI not configured",- )- if "api_key" not in config["ai"]["google"]:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="Google AI API key not configured",- )-- key: str = config["ai"]["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)- return genai.GenerativeModel(- model_name=model,- generation_config=genai.GenerationConfig(- max_output_tokens=1000,- temperature=0,- ),- )+ return ai_config@router.post("/completion")@@ -323,7 +54,7 @@ async def ai_completion() -> StreamingResponse:"""requestBody:- description: The prompt to get AI completion for+ description: The request body for AI completionrequired: truecontent:application/json:@@ -344,7 +75,9 @@ async def ai_completion(body = await parse_request(request, cls=AiCompletionRequest, allow_unknown_keys=True)- custom_rules = config.get("ai", {}).get("rules", None)+ ai_config = get_ai_config(config)++ custom_rules = ai_config.get("rules", None)prompter = Prompter(code=body.code)system_prompt = Prompter.get_system_prompt(@@ -354,62 +87,15 @@ async def ai_completion(user_prompt=body.prompt, include_other_code=body.include_other_code)- model = get_model(config)-- # If the model starts with claude, use anthropic- if model.startswith("claude"):- anthropic_client = get_anthropic_client(config)- anthropic_response = anthropic_client.messages.create(- model=model,- max_tokens=get_max_tokens(config),- messages=[- {- "role": "user",- "content": prompt,- }- ],- system=system_prompt,- stream=True,- temperature=0,- )-- return StreamingResponse(- content=make_stream_response(anthropic_response),- media_type="application/json",- )-- # If the model starts with google/gemini, use Google AI- if model.startswith("google") or model.startswith("gemini"):- google_client = get_google_client(config, model)- google_response = google_client.generate_content(- contents=prompt,- stream=True,- )-- return StreamingResponse(- content=make_stream_response(google_response),- media_type="application/json",- )-- openai_client = get_openai_client(config)- response = openai_client.chat.completions.create(- model=get_model(config),- messages=[- {- "role": "system",- "content": system_prompt,- },- {- "role": "user",- "content": prompt,- },- ],- stream=True,- timeout=15,+ provider = get_completion_provider(ai_config)+ response = provider.stream_completion(+ messages=[ChatMessage(role="user", content=prompt)],+ system_prompt=system_prompt,+ max_tokens=get_max_tokens(config),)return StreamingResponse(- content=make_stream_response(response),+ content=provider.as_stream_response(response),media_type="application/json",)@@ -421,7 +107,13 @@ async def ai_chat(request: Request,) -> StreamingResponse:"""- Chat endpoint that handles ongoing conversations+ requestBody:+ description: The request body for AI chat+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ChatRequest""""app_state = AppState(request)app_state.require_current_session()@@ -429,9 +121,7 @@ async def ai_chat(body = await parse_request(request, cls=ChatRequest, allow_unknown_keys=True)-- # Get the model from request or fallback to config- model = body.model or get_model(config)+ ai_config = get_ai_config(config)messages = body.messages# Get the system prompt@@ -442,52 +132,71 @@ async def ai_chat(include_other_code=body.include_other_code,)- # Handle different model providers- if model.startswith("claude"):- anthropic_client = get_anthropic_client(config)- response = anthropic_client.messages.create(- model=model,- max_tokens=get_max_tokens(config),- messages=cast(Any, convert_to_anthropic_messages(messages)),- system=system_prompt,- stream=True,- temperature=0,- )+ max_tokens = get_max_tokens(config)- return StreamingResponse(- content=as_stream_response(response),- media_type="application/json",- )+ provider = get_completion_provider(ai_config, model_override=body.model)+ response = provider.stream_completion(+ messages=messages,+ system_prompt=system_prompt,+ max_tokens=max_tokens,+ )- if model.startswith("google") or model.startswith("gemini"):- google_client = get_google_client(config, model)- response = google_client.generate_content(- contents=convert_to_google_messages(- [ChatMessage(role="system", content=system_prompt)] + messages- ),- stream=True,- )+ return StreamingResponse(+ content=provider.as_stream_response(response),+ media_type="application/json",+ )- return StreamingResponse(- content=as_stream_response(response),- media_type="application/json",- )- # Default to OpenAI- openai_client = get_openai_client(config)- response = openai_client.chat.completions.create(- model=model,- messages=cast(- Any,- convert_to_openai_messages(- [ChatMessage(role="system", content=system_prompt)] + messages- ),- ),- stream=True,- timeout=15,[email protected]("/inline_completion")+@requires("edit")+async def ai_inline_completion(+ *,+ request: Request,+) -> PlainTextResponse:+ """+ requestBody:+ description: The request body for AI inline completion+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/AiInlineCompletionRequest"+ responses:+ 200:+ description: Get AI inline completion for code+ content:+ text/plain:+ schema:+ type: string+ """+ app_state = AppState(request)+ app_state.require_current_session()+ config = app_state.app_config_manager.get_config(hide_secrets=False)+ body = await parse_request(+ request, cls=AiInlineCompletionRequest, allow_unknown_keys=True)+ 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)- return StreamingResponse(- content=as_stream_response(response),- media_type="application/json",+ # This is currently not configurable and smaller than the default+ # of 4096, since it is smaller/faster for inline completions+ INLINE_COMPLETION_MAX_TOKENS = 1024++ try:+ model = config["completion"]["model"] or DEFAULT_MODEL+ except Exception:+ model = DEFAULT_MODEL++ provider = get_completion_provider(ai_config, model_override=model)+ response = provider.stream_completion(+ messages=messages,+ system_prompt=system_prompt,+ max_tokens=INLINE_COMPLETION_MAX_TOKENS,+ )++ return PlainTextResponse(+ content=provider.collect_stream(response),+ media_type="text/plain",)diff --git a/marimo/_server/models/completion.py b/marimo/_server/models/completion.pyindex d3c6f5c431..29fa0f41c1 100644--- a/marimo/_server/models/completion.py+++ b/marimo/_server/models/completion.py@@ -37,6 +37,13 @@ class AiCompletionRequest:language: Language = "python"+@dataclass+class AiInlineCompletionRequest:+ prefix: str+ suffix: str+ language: Language = "python"++@dataclassclass ChatRequest:context: AiCompletionContextdiff --git a/openapi/api.yaml b/openapi/api.yamlindex cfdb8744bf..74cba79c2f 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -7,42 +7,22 @@ components:required:- packagetype: object+ AiCompletionContext:+ properties:+ schema:+ items:+ $ref: '#/components/schemas/SchemaTable'+ type: array+ required:+ - schema+ type: objectAiCompletionRequest:properties:code:type: stringcontext:+ $ref: '#/components/schemas/AiCompletionContext'nullable: true- properties:- schema:- items:- properties:- columns:- items:- properties:- name:- type: string- sampleValues:- items: {}- type: array- type:- type: string- required:- - name- - type- - sampleValues- type: object- type: array- name:- type: string- required:- - name- - columns- type: object- type: array- required:- - schema- type: objectincludeOtherCode:type: stringlanguage:@@ -59,6 +39,23 @@ components:- code- languagetype: object+ AiInlineCompletionRequest:+ properties:+ language:+ enum:+ - python+ - markdown+ - sql+ type: string+ prefix:+ type: string+ suffix:+ type: string+ required:+ - prefix+ - suffix+ - language+ type: objectAlert:properties:description:@@ -222,6 +219,58 @@ components:- data- timestamptype: object+ ChatRequest:+ properties:+ context:+ $ref: '#/components/schemas/AiCompletionContext'+ includeOtherCode:+ type: string+ messages:+ items:+ properties:+ attachments:+ items:+ properties:+ contentType:+ nullable: true+ type: string+ name:+ type: string+ url:+ type: string+ required:+ - url+ - name+ type: object+ nullable: true+ type: array+ content:+ additionalProperties: true+ type: object+ role:+ enum:+ - user+ - assistant+ - system+ type: string+ required:+ - role+ - content+ type: object+ type: array+ model:+ nullable: true+ type: string+ variables:+ items:+ type: string+ nullable: true+ type: array+ required:+ - context+ - includeOtherCode+ - messages+ type: objectCodeCompletionRequest:properties:cellId:@@ -1262,6 +1311,12 @@ components:properties:activate_on_typing:type: boolean+ api_key:+ nullable: true+ type: string+ base_url:+ nullable: true+ type: stringcodeium_api_key:nullable: truetype: string@@ -1271,7 +1326,11 @@ components:- enum:- github- codeium+ - customtype: string+ model:+ nullable: true+ type: stringrequired:- activate_on_typing- copilot@@ -2046,6 +2105,32 @@ components:- name- tablestype: object+ SchemaColumn:+ properties:+ name:+ type: string+ sampleValues:+ items: {}+ type: array+ type:+ type: string+ required:+ - name+ - type+ - sampleValues+ type: object+ SchemaTable:+ properties:+ columns:+ items:+ $ref: '#/components/schemas/SchemaColumn'+ type: array+ name:+ type: string+ required:+ - name+ - columns+ type: objectSendUIElementMessage:properties:buffers:@@ -2301,7 +2386,7 @@ components:type: objectinfo:title: marimo API- version: 0.11.19+ version: 0.11.21openapi: 3.1.0paths:/@file/{filename_and_length}:@@ -2322,6 +2407,15 @@ paths:description: Get a virtual file404:description: Invalid byte length in virtual file request+ /api/ai/chat:+ post:+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ChatRequest'+ description: The request body for AI chat+ required: true/api/ai/completion:post:requestBody:@@ -2329,7 +2423,7 @@ paths:application/json:schema:$ref: '#/components/schemas/AiCompletionRequest'- description: The prompt to get AI completion for+ description: The request body for AI completionrequired: trueresponses:200:@@ -2339,6 +2433,22 @@ paths:additionalProperties: truetype: objectdescription: Get AI completion for a prompt+ /api/ai/inline_completion:+ post:+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AiInlineCompletionRequest'+ description: The request body for AI inline completion+ required: true+ responses:+ 200:+ content:+ text/plain:+ schema:+ type: string+ description: Get AI inline completion for code/api/datasources/preview_column:post:requestBody:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex cd89a392b4..d22923c620 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -49,6 +49,36 @@ export interface paths {patch?: never;trace?: never;};+ "/api/ai/chat": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /** @description The request body for AI chat */+ requestBody: {+ content: {+ "application/json": components["schemas"]["ChatRequest"];+ };+ };+ responses: never;+ };+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/ai/completion": {parameters: {query?: never;@@ -65,7 +95,7 @@ export interface paths {path?: never;cookie?: never;};- /** @description The prompt to get AI completion for */+ /** @description The request body for AI completion */requestBody: {content: {"application/json": components["schemas"]["AiCompletionRequest"];@@ -91,6 +121,46 @@ export interface paths {patch?: never;trace?: never;};+ "/api/ai/inline_completion": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /** @description The request body for AI inline completion */+ requestBody: {+ content: {+ "application/json": components["schemas"]["AiInlineCompletionRequest"];+ };+ };+ responses: {+ /** @description Get AI inline completion for code */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "text/plain": string;+ };+ };+ };+ };+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/datasources/preview_column": {parameters: {query?: never;@@ -2153,23 +2223,23 @@ export interface components {AddPackageRequest: {package: string;};+ AiCompletionContext: {+ schema: components["schemas"]["SchemaTable"][];+ };AiCompletionRequest: {code: string;- context?: {- schema: {- columns: {- name: string;- sampleValues: unknown[];- type: string;- }[];- name: string;- }[];- } | null;+ context?: components["schemas"]["AiCompletionContext"];includeOtherCode: string;/** @enum {string} */language: "python" | "markdown" | "sql";prompt: string;};+ AiInlineCompletionRequest: {+ /** @enum {string} */+ language: "python" | "markdown" | "sql";+ prefix: string;+ suffix: string;+ };Alert: {description: string;/** @enum {string} */@@ -2245,6 +2315,26 @@ export interface components {mimetype: components["schemas"]["MimeType"];timestamp: number;};+ ChatRequest: {+ context: components["schemas"]["AiCompletionContext"];+ includeOtherCode: string;+ messages: {+ attachments?:+ | {+ contentType?: string | null;+ name: string;+ url: string;+ }[]+ | null;+ content: {+ [key: string]: unknown;+ };+ /** @enum {string} */+ role: "user" | "assistant" | "system";+ }[];+ model?: string | null;+ variables?: string[] | null;+ };CodeCompletionRequest: {cellId: string;document: string;@@ -2688,8 +2778,11 @@ export interface components {};completion: {activate_on_typing: boolean;+ api_key?: string | null;+ base_url?: string | null;codeium_api_key?: string | null;- copilot: boolean | ("github" | "codeium");+ copilot: boolean | ("github" | "codeium" | "custom");+ model?: string | null;};datasources?: {auto_discover_columns?: boolean | "auto";@@ -3011,6 +3104,15 @@ export interface components {name: string;tables: components["schemas"]["DataTable"][];};+ SchemaColumn: {+ name: string;+ sampleValues: unknown[];+ type: string;+ };+ SchemaTable: {+ columns: components["schemas"]["SchemaColumn"][];+ name: string;+ };SendUIElementMessage: {buffers?: string[] | null;message: {diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex 09b82fef88..907ebd546d 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -11,7 +11,7 @@ import pytestfrom marimo._config.manager import UserConfigManagerfrom marimo._dependencies.dependencies import DependencyManager-from marimo._server.api.endpoints.ai import get_content, make_stream_response+from marimo._server.ai.providers import OpenAIProviderfrom tests._server.conftest import get_session_config_managerfrom tests._server.mocks import token_header, with_session@@ -219,6 +219,97 @@ class TestOpenAiEndpoints:base_url = openai_mock.call_args.kwargs["base_url"]assert base_url == "https://my-openai-instance.com"+ @staticmethod+ @with_session(SESSION_ID)+ @patch("openai.OpenAI")+ def test_inline_completion(client: TestClient, openai_mock: Any) -> None:+ user_config_manager = get_session_config_manager(client)++ oaiclient = MagicMock()+ openai_mock.return_value = oaiclient++ oaiclient.chat.completions.create.return_value = [+ FakeChoices(+ choices=[Choice(delta=Delta(content="df = pd.DataFrame()"))]+ )+ ]++ with openai_config(user_config_manager):+ response = client.post(+ "/api/ai/inline_completion",+ headers=HEADERS,+ json={+ "prefix": "import pandas as pd\n",+ "suffix": "\ndf.head()",+ "language": "python",+ },+ )+ assert response.status_code == 200, response.text+ # Assert the prompt it was called with+ prompt = oaiclient.chat.completions.create.call_args.kwargs[+ "messages"+ ][1]["content"]+ assert prompt == "import pandas as pd\n<FILL_ME>\ndf.head()"+ # Assert the system prompt includes language-specific instructions+ system_prompt = oaiclient.chat.completions.create.call_args.kwargs[+ "messages"+ ][0]["content"]+ assert "python" in system_prompt++ @staticmethod+ @with_session(SESSION_ID)+ @patch("openai.OpenAI")+ def test_inline_completion_without_token(+ client: TestClient, openai_mock: Any+ ) -> None:+ del openai_mock+ user_config_manager = get_session_config_manager(client)++ with no_openai_config(user_config_manager):+ response = client.post(+ "/api/ai/inline_completion",+ headers=HEADERS,+ json={+ "prefix": "import pandas as pd\n",+ "suffix": "\ndf.head()",+ "language": "python",+ },+ )+ assert response.status_code == 400, response.text+ assert response.json() == {"detail": "OpenAI API key not configured"}++ @staticmethod+ @with_session(SESSION_ID)+ @patch("openai.OpenAI")+ def test_inline_completion_different_language(+ client: TestClient, openai_mock: Any+ ) -> None:+ user_config_manager = get_session_config_manager(client)++ oaiclient = MagicMock()+ openai_mock.return_value = oaiclient++ oaiclient.chat.completions.create.return_value = [+ FakeChoices(choices=[Choice(delta=Delta(content="SELECT 1;"))])+ ]++ with openai_config(user_config_manager):+ response = client.post(+ "/api/ai/inline_completion",+ headers=HEADERS,+ json={+ "prefix": "SELECT 1;",+ "suffix": "\nSELECT 2;",+ "language": "sql",+ },+ )+ assert response.status_code == 200, response.text+ # Assert the system prompt includes language-specific instructions+ system_prompt = oaiclient.chat.completions.create.call_args.kwargs[+ "messages"+ ][0]["content"]+ assert "sql" in system_prompt+@pytest.mark.skipif(not HAS_ANTHROPIC_DEPS, reason="optional dependencies not installed"@@ -282,6 +373,38 @@ class TestAnthropicAiEndpoints:"Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>")+ @staticmethod+ @with_session(SESSION_ID)+ @patch("anthropic.Client")+ def test_anthropic_inline_completion(+ client: TestClient, anthropic_mock: Any+ ) -> None:+ user_config_manager = get_session_config_manager(client)++ anthropic_client = MagicMock()+ anthropic_mock.return_value = anthropic_client++ anthropic_client.messages.create.return_value = [+ RawContentBlockDeltaEvent(TextDelta("df = pd.DataFrame()"))+ ]++ with anthropic_config(user_config_manager):+ response = client.post(+ "/api/ai/inline_completion",+ headers=HEADERS,+ json={+ "prefix": "import pandas as pd\n",+ "suffix": "\ndf.head()",+ "language": "python",+ },+ )+ assert response.status_code == 200, response.text+ # Assert the prompt it was called with+ prompt: str = anthropic_client.messages.create.call_args.kwargs[+ "messages"+ ][0]["content"]+ assert prompt == "import pandas as pd\n<FILL_ME>\ndf.head()"+@pytest.mark.skipif(not HAS_GOOGLE_AI_DEPS, reason="optional dependencies not installed"@@ -317,7 +440,7 @@ class TestGoogleAiEndpoints:prompt = google_client.generate_content.call_args.kwargs["contents"]- assert prompt == (+ assert prompt[0]["parts"][0] == ("Help me create a dataframe\n\n<current-code>\nimport pandas as pd\n</current-code>")@@ -345,6 +468,41 @@ class TestGoogleAiEndpoints:"detail": "Google AI API key not configured"}+ @staticmethod+ @with_session(SESSION_ID)+ @patch("google.generativeai.GenerativeModel")+ def test_google_ai_inline_completion(+ client: TestClient, google_ai_mock: Any+ ) -> None:+ user_config_manager = get_session_config_manager(client)++ google_client = MagicMock()+ google_ai_mock.return_value = google_client++ google_client.predict.return_value = MagicMock(+ text="df = pd.DataFrame()"+ )++ with google_ai_config(user_config_manager):+ response = client.post(+ "/api/ai/inline_completion",+ headers=HEADERS,+ json={+ "prefix": "import pandas as pd\n",+ "suffix": "\ndf.head()",+ "language": "python",+ },+ )+ 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]+ == "import pandas as pd\n<FILL_ME>\ndf.head()"+ )+@contextmanagerdef openai_config(config: UserConfigManager):@@ -433,7 +591,11 @@ def anthropic_config(config: UserConfigManager):"ai": {"open_ai": {"model": "claude-3.5"},"anthropic": {"api_key": "fake-key"},- }+ },+ "completion": {+ "model": "claude-3.5",+ "api_key": "fake-key",+ },})yield@@ -450,7 +612,11 @@ def google_ai_config(config: UserConfigManager):"ai": {"open_ai": {"model": "gemini-1.5-pro"},"google": {"api_key": "fake-key"},- }+ },+ "completion": {+ "model": "gemini-1.5-pro",+ "api_key": "fake-key",+ },})yield@@ -467,7 +633,7 @@ def no_google_ai_config(config: UserConfigManager):"ai": {"open_ai": {"model": "gemini-1.5-pro"},"google": {"api_key": ""},- }+ },})yield@@ -493,31 +659,35 @@ class TestStreamResponse(unittest.TestCase):yield MockChunk(content)def test_no_code_fence(self):+ provider = OpenAIProvider(model="gpt-4o", config={})response = self.simulate_stream(["Hello, world!"])- result = list(make_stream_response(response))+ result = list(provider.make_stream_response(response))assert result == ["Hello, world!"]def test_single_complete_code_fence(self):+ provider = OpenAIProvider(model="gpt-4o", config={})response = self.simulate_stream(["```python\nprint('Hello, world!')\n```"])- result = list(make_stream_response(response))+ result = list(provider.make_stream_response(response))assert result == ["print('Hello, world!')\n"]def test_code_fence_across_chunks(self):+ provider = OpenAIProvider(model="gpt-4o", config={})response = self.simulate_stream(["```python\nprint('Hello,"," world!')\n```",])- result = list(make_stream_response(response))+ result = list(provider.make_stream_response(response))assert result == ["print('Hello,"," world!')\n",]def test_code_fence_across_more_chunks(self):+ provider = OpenAIProvider(model="gpt-4o", config={})response = self.simulate_stream(["```",@@ -527,7 +697,7 @@ class TestStreamResponse(unittest.TestCase):"```",])- result = list(make_stream_response(response))+ result = list(provider.make_stream_response(response))assert result == ["print('Hello,", " world!')\n", ""]def test_multiple_code_fences(self):@@ -539,7 +709,8 @@ class TestStreamResponse(unittest.TestCase):"```sql\nSELECT * FROM users;\n```",])- result = list(make_stream_response(response))+ provider = OpenAIProvider(model="gpt-4o", config={})+ result = list(provider.make_stream_response(response))assert result == ["print('Hello',"," 'world!')\n",@@ -551,93 +722,91 @@ class TestStreamResponse(unittest.TestCase):response = self.simulate_stream(["```python\nprint('```nested```')\n```"])- result = list(make_stream_response(response))+ provider = OpenAIProvider(model="gpt-4o", config={})+ result = list(provider.make_stream_response(response))assert result == ["print('```nested```')\n"]- @staticmethod- @with_session(SESSION_ID)- @patch("openai.OpenAI")- def test_chat_without_code(- client: TestClient, openai_mock: Any- ) -> None:- user_config_manager = get_session_config_manager(client)-- oaiclient = MagicMock()- openai_mock.return_value = oaiclient-- oaiclient.chat.completions.create.return_value = [- FakeChoices(- choices=[- Choice(- delta=Delta(content="Hello, how can I help you?")- )- ]- )- ]- with openai_config(user_config_manager):- response = client.post(- "/api/ai/chat",- headers=HEADERS,- json={- "messages": [{"role": "user", "content": "Hello"}],- "model": "gpt-4-turbo",- "variables": [],- "include_other_code": "",- "id": "123",- },- )- assert response.status_code == 200, response.text- # Assert the prompt it was called with- prompt = oaiclient.chat.completions.create.call_args.kwargs[- "messages"- ][1]["content"]- assert prompt == "Hello"-- @staticmethod- @with_session(SESSION_ID)- @patch("openai.OpenAI")- def test_chat_with_code(client: TestClient, openai_mock: Any) -> None:- user_config_manager = get_session_config_manager(client)-- oaiclient = MagicMock()- openai_mock.return_value = oaiclient-- oaiclient.chat.completions.create.return_value = [- FakeChoices(- choices=[- Choice(delta=Delta(content="import pandas as pd"))- ]- )- ]+@with_session(SESSION_ID)+def test_chat_without_code(client: TestClient) -> None:+ user_config_manager = get_session_config_manager(client)- with openai_config(user_config_manager):- response = client.post(- "/api/ai/chat",- headers=HEADERS,- json={- "messages": [- {- "role": "user",- "content": "Help me create a dataframe",- }- ],- "model": "gpt-4-turbo",- "variables": [],- "include_other_code": "import pandas as pd",- "id": "123",- },- )- assert response.status_code == 200, response.text- # Assert the prompt it was called with- prompt = oaiclient.chat.completions.create.call_args.kwargs[- "messages"- ][1]["content"]- assert prompt == "Help me create a dataframe"+ with patch("openai.OpenAI") as openai_mock:+ oaiclient = MagicMock()+ openai_mock.return_value = oaiclient++ oaiclient.chat.completions.create.return_value = [+ FakeChoices(+ choices=[+ Choice(delta=Delta(content="Hello, how can I help you?"))+ ]+ )+ ]++ with openai_config(user_config_manager):+ response = client.post(+ "/api/ai/chat",+ headers=HEADERS,+ json={+ "messages": [{"role": "user", "content": "Hello"}],+ "model": "gpt-4-turbo",+ "variables": [],+ "include_other_code": "",+ "context": {},+ "id": "123",+ },+ )+ assert response.status_code == 200, response.text+ # Assert the prompt it was called with+ prompt = oaiclient.chat.completions.create.call_args.kwargs[+ "messages"+ ][1]["content"]+ assert prompt == "Hello"+++@with_session(SESSION_ID)+def test_chat_with_code(client: TestClient) -> None:+ user_config_manager = get_session_config_manager(client)++ with patch("openai.OpenAI") as openai_mock:+ oaiclient = MagicMock()+ openai_mock.return_value = oaiclient++ oaiclient.chat.completions.create.return_value = [+ FakeChoices(+ choices=[Choice(delta=Delta(content="import pandas as pd"))]+ )+ ]++ with openai_config(user_config_manager):+ response = client.post(+ "/api/ai/chat",+ headers=HEADERS,+ json={+ "messages": [+ {+ "role": "user",+ "content": "Help me create a dataframe",+ }+ ],+ "model": "gpt-4-turbo",+ "variables": [],+ "include_other_code": "import pandas as pd",+ "context": {},+ "id": "123",+ },+ )+ assert response.status_code == 200, response.text+ # Assert the prompt it was called with+ prompt = oaiclient.chat.completions.create.call_args.kwargs[+ "messages"+ ][1]["content"]+ assert prompt == "Help me create a dataframe"class TestGetContent(unittest.TestCase):- def test_get_content_with_none_delta(self) -> None:+ def test_extract_content_with_none_delta(self) -> None:+ provider = OpenAIProvider(model="gpt-4o", config={})# Create a mock response with choices but delta is Nonemock_response = Mock()mock_response.choices = [Mock()]@@ -647,12 +816,12 @@ class TestGetContent(unittest.TestCase):type(mock_response).text = property(lambda _: None)# Call get_content with the mock response- result = get_content(mock_response)+ result = provider.extract_content(mock_response)# Assert that the result is Noneassert result is None- def test_get_content_with_delta_content(self) -> None:+ def test_extract_content_with_delta_content(self) -> None:# Create a mock response with choices and delta.contentmock_response = Mock()mock_response.choices = [Mock()]@@ -660,7 +829,8 @@ class TestGetContent(unittest.TestCase):mock_response.choices[0].delta.content = "Test content"# Call get_content with the mock response- result = get_content(mock_response)+ provider = OpenAIProvider(model="gpt-4o", config={})+ result = provider.extract_content(mock_response)# Assert that the result is the expected contentassert result == "Test content"