Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: more ai config settings for different providers (#6011)

Myles Scolnickab3fc1b68fc0
diff --git a/frontend/src/components/ai/AiProviderIcon.tsx b/frontend/src/components/ai/ai-provider-icon.tsx
similarity index 100%
rename from frontend/src/components/ai/AiProviderIcon.tsx
rename to frontend/src/components/ai/ai-provider-icon.tsx
diff --git a/frontend/src/components/app-config/ai-config.tsx b/frontend/src/components/app-config/ai-config.tsx
new file mode 100644
index 0000000000..4c06f838df
--- /dev/null
+++ b/frontend/src/components/app-config/ai-config.tsx
@@ -0,0 +1,677 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import React from "react";
+import type { FieldPath, UseFormReturn } from "react-hook-form";
+import {
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Kbd } from "@/components/ui/kbd";
+import { NativeSelect } from "@/components/ui/native-select";
+import { Textarea } from "@/components/ui/textarea";
+import { CopilotConfig } from "@/core/codemirror/copilot/copilot-config";
+import type { UserConfig } from "@/core/config/config-schema";
+import { isWasm } from "@/core/wasm/utils";
+import {
+ AiProviderIcon,
+ type AiProviderIconProps,
+} from "../ai/ai-provider-icon";
+import { ExternalLink } from "../ui/links";
+import { SettingSubtitle } from "./common";
+import { AWS_REGIONS, KNOWN_AI_MODELS } from "./constants";
+import { IncorrectModelId } from "./incorrect-model-id";
+import { IsOverridden } from "./is-overridden";
+
+const formItemClasses = "flex flex-row items-center space-x-1 space-y-0";
+
+interface AiConfigProps {
+ form: UseFormReturn<UserConfig>;
+ config: UserConfig;
+ onSubmit: (values: UserConfig) => Promise<void>;
+}
+
+interface AiProviderTitleProps {
+ provider?: AiProviderIconProps["provider"];
+ children: React.ReactNode;
+}
+
+export const AiProviderTitle: React.FC<AiProviderTitleProps> = ({
+ provider,
+ children,
+}) => {
+ return (
+ <div className="flex items-center text-base font-semibold">
+ {provider && <AiProviderIcon provider={provider} className="mr-2" />}
+ {children}
+ </div>
+ );
+};
+
+interface ApiKeyProps {
+ form: UseFormReturn<UserConfig>;
+ config: UserConfig;
+ name: FieldPath<UserConfig>;
+ placeholder: string;
+ testId: string;
+ description?: React.ReactNode;
+}
+
+export const ApiKey: React.FC<ApiKeyProps> = ({
+ form,
+ config,
+ name,
+ placeholder,
+ testId,
+ description,
+}) => {
+ return (
+ <FormField
+ control={form.control}
+ name={name}
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>API Key</FormLabel>
+ <FormControl>
+ <Input
+ data-testid={testId}
+ rootClassName="flex-1"
+ className="m-0 inline-flex h-7"
+ placeholder={placeholder}
+ {...field}
+ value={asStringOrUndefined(field.value)}
+ onChange={(e) => {
+ const value = e.target.value;
+ if (!value.includes("*")) {
+ field.onChange(value);
+ }
+ }}
+ />
+ </FormControl>
+ <FormMessage />
+ <IsOverridden userConfig={config} name={name} />
+ </FormItem>
+ {description && <FormDescription>{description}</FormDescription>}
+ </div>
+ )}
+ />
+ );
+};
+
+interface BaseUrlProps {
+ form: UseFormReturn<UserConfig>;
+ config: UserConfig;
+ name: FieldPath<UserConfig>;
+ placeholder: string;
+ testId: string;
+ description?: React.ReactNode;
+ disabled?: boolean;
+ defaultValue?: string;
+}
+
+function asStringOrUndefined<T>(value: T): string | undefined {
+ if (value == null) {
+ return undefined;
+ }
+
+ if (typeof value === "string") {
+ return value;
+ }
+
+ return String(value);
+}
+
+export const BaseUrl: React.FC<BaseUrlProps> = ({
+ form,
+ config,
+ name,
+ placeholder,
+ testId,
+ description,
+ disabled = false,
+ defaultValue,
+}) => {
+ return (
+ <FormField
+ control={form.control}
+ name={name}
+ disabled={disabled}
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>Base URL</FormLabel>
+ <FormControl>
+ <Input
+ data-testid={testId}
+ rootClassName="flex-1"
+ className="m-0 inline-flex h-7"
+ placeholder={placeholder}
+ defaultValue={defaultValue}
+ {...field}
+ value={asStringOrUndefined(field.value)}
+ />
+ </FormControl>
+ <FormMessage />
+ <IsOverridden userConfig={config} name={name} />
+ </FormItem>
+ {description && <FormDescription>{description}</FormDescription>}
+ </div>
+ )}
+ />
+ );
+};
+
+interface ModelSelectorProps {
+ form: UseFormReturn<UserConfig>;
+ config: UserConfig;
+ name: FieldPath<UserConfig>;
+ placeholder: string;
+ testId: string;
+ description?: React.ReactNode;
+ disabled?: boolean;
+}
+
+export const ModelSelector: React.FC<ModelSelectorProps> = ({
+ form,
+ config,
+ name,
+ placeholder,
+ testId,
+ description,
+ disabled = false,
+}) => {
+ return (
+ <FormField
+ control={form.control}
+ name={name}
+ disabled={disabled}
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>Model</FormLabel>
+ <FormControl>
+ <Input
+ list="ai-model-datalist"
+ data-testid={testId}
+ className="m-0 inline-flex"
+ placeholder={placeholder}
+ {...field}
+ value={asStringOrUndefined(field.value)}
+ />
+ </FormControl>
+ <FormMessage />
+ <IsOverridden userConfig={config} name={name} />
+ </FormItem>
+ <datalist id="ai-model-datalist">
+ {KNOWN_AI_MODELS.map((model) => (
+ <option value={model} key={model}>
+ {model}
+ </option>
+ ))}
+ </datalist>
+ <IncorrectModelId value={asStringOrUndefined(field.value)} />
+ {description && <FormDescription>{description}</FormDescription>}
+ </div>
+ )}
+ />
+ );
+};
+
+interface ProviderSelectProps {
+ form: UseFormReturn<UserConfig>;
+ config: UserConfig;
+ name: FieldPath<UserConfig>;
+ options: string[];
+ testId: string;
+ disabled?: boolean;
+}
+
+export const ProviderSelect: React.FC<ProviderSelectProps> = ({
+ form,
+ config,
+ name,
+ options,
+ testId,
+ disabled = false,
+}) => {
+ return (
+ <FormField
+ control={form.control}
+ name={name}
+ disabled={disabled}
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>Provider</FormLabel>
+ <FormControl>
+ <NativeSelect
+ data-testid={testId}
+ onChange={(e) => {
+ if (e.target.value === "none") {
+ field.onChange(false);
+ } else {
+ field.onChange(e.target.value);
+ }
+ }}
+ value={asStringOrUndefined(
+ field.value === true
+ ? "github"
+ : field.value === false
+ ? "none"
+ : field.value,
+ )}
+ disabled={field.disabled}
+ className="inline-flex mr-2"
+ >
+ {options.map((option) => (
+ <option value={option} key={option}>
+ {option}
+ </option>
+ ))}
+ </NativeSelect>
+ </FormControl>
+ <FormMessage />
+ <IsOverridden userConfig={config} name={name} />
+ </FormItem>
+ </div>
+ )}
+ />
+ );
+};
+
+const renderCopilotProvider = (
+ form: UseFormReturn<UserConfig>,
+ config: UserConfig,
+) => {
+ const copilot = form.getValues("completion.copilot");
+ if (copilot === false) {
+ return null;
+ }
+
+ if (copilot === "codeium") {
+ return (
+ <>
+ <p className="text-sm text-muted-secondary">
+ To get a Windsurf API key, follow{" "}
+ <ExternalLink href="https://docs.marimo.io/guides/editor_features/ai_completion.html#windsurf-copilot">
+ these instructions
+ </ExternalLink>
+ .
+ </p>
+ <ApiKey
+ form={form}
+ config={config}
+ name="completion.codeium_api_key"
+ placeholder="key"
+ testId="codeium-api-key-input"
+ />
+ </>
+ );
+ }
+
+ 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>
+ <ModelSelector
+ form={form}
+ config={config}
+ name="completion.model"
+ placeholder="Qwen2.5-Coder-7B"
+ testId="custom-model-input"
+ />
+ <BaseUrl
+ form={form}
+ config={config}
+ name="completion.base_url"
+ placeholder="http://localhost:11434/v1"
+ testId="custom-base-url-input"
+ />
+ <ApiKey
+ form={form}
+ config={config}
+ name="completion.api_key"
+ placeholder="key"
+ testId="custom-api-key-input"
+ />
+ </>
+ );
+ }
+};
+
+const SettingGroup = ({
+ title,
+ children,
+}: {
+ title: string;
+ children: React.ReactNode;
+}) => {
+ return (
+ <div className="flex flex-col gap-4 pb-4">
+ <SettingSubtitle>{title}</SettingSubtitle>
+ {children}
+ </div>
+ );
+};
+
+export const AiCodeCompletionConfig: React.FC<AiConfigProps> = ({
+ form,
+ config,
+}) => {
+ return (
+ <SettingGroup title="AI Code Completion">
+ <p className="text-sm text-muted-secondary">
+ You may use GitHub Copilot, Codeium, or a custom provider (e.g. Ollama)
+ for AI code completion.
+ </p>
+
+ <ProviderSelect
+ form={form}
+ config={config}
+ name="completion.copilot"
+ options={["none", "github", "codeium", "custom"]}
+ testId="copilot-select"
+ />
+
+ {renderCopilotProvider(form, config)}
+ </SettingGroup>
+ );
+};
+
+export const AiKeysConfig: React.FC<AiConfigProps> = ({ form, config }) => {
+ const isWasmRuntime = isWasm();
+
+ return (
+ <SettingGroup title="AI Providers">
+ <AiProviderTitle provider="openai">OpenAI</AiProviderTitle>
+ <ApiKey
+ form={form}
+ config={config}
+ name="ai.open_ai.api_key"
+ placeholder="sk-proj..."
+ testId="ai-openai-api-key-input"
+ description={
+ <>
+ Your OpenAI API key from{" "}
+ <ExternalLink href="https://platform.openai.com/account/api-keys">
+ platform.openai.com
+ </ExternalLink>
+ .
+ </>
+ }
+ />
+ <BaseUrl
+ form={form}
+ config={config}
+ name="ai.open_ai.base_url"
+ placeholder="https://api.openai.com/v1"
+ testId="ai-base-url-input"
+ disabled={isWasmRuntime}
+ />
+
+ <AiProviderTitle provider="anthropic">Anthropic</AiProviderTitle>
+ <ApiKey
+ form={form}
+ config={config}
+ name="ai.anthropic.api_key"
+ placeholder="sk-ant..."
+ testId="ai-anthropic-api-key-input"
+ description={
+ <>
+ Your Anthropic API key from{" "}
+ <ExternalLink href="https://console.anthropic.com/settings/keys">
+ console.anthropic.com
+ </ExternalLink>
+ .
+ </>
+ }
+ />
+
+ <AiProviderTitle provider="google">Google</AiProviderTitle>
+ <ApiKey
+ form={form}
+ config={config}
+ name="ai.google.api_key"
+ placeholder="AI..."
+ testId="ai-google-api-key-input"
+ description={
+ <>
+ Your Google AI API key from{" "}
+ <ExternalLink href="https://aistudio.google.com/app/apikey">
+ aistudio.google.com
+ </ExternalLink>
+ .
+ </>
+ }
+ />
+
+ <AiProviderTitle provider="ollama">Ollama</AiProviderTitle>
+ <BaseUrl
+ form={form}
+ config={config}
+ name="ai.ollama.base_url"
+ placeholder="http://localhost:11434/v1"
+ defaultValue="http://localhost:11434/v1"
+ testId="ollama-base-url-input"
+ />
+
+ <AiProviderTitle>Azure</AiProviderTitle>
+ <ApiKey
+ form={form}
+ config={config}
+ name="ai.azure.api_key"
+ placeholder="sk-proj..."
+ testId="ai-azure-api-key-input"
+ description={
+ <>
+ Your Azure API key from{" "}
+ <ExternalLink href="https://portal.azure.com/">
+ portal.azure.com
+ </ExternalLink>
+ .
+ </>
+ }
+ />
+
+ <BaseUrl
+ form={form}
+ config={config}
+ name="ai.azure.base_url"
+ placeholder="https://<your-resource-name>.openai.azure.com"
+ testId="ai-azure-base-url-input"
+ />
+
+ <AiProviderTitle>AWS Bedrock</AiProviderTitle>
+
+ <p className="text-sm text-muted-secondary mb-2">
+ To use AWS Bedrock, you need to configure AWS credentials and region.
+ See the{" "}
+ <ExternalLink href="https://docs.marimo.io/guides/editor_features/ai_completion.html#aws-bedrock">
+ documentation
+ </ExternalLink>{" "}
+ for more details.
+ </p>
+
+ <FormField
+ control={form.control}
+ disabled={isWasmRuntime}
+ name="ai.bedrock.region_name"
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>AWS Region</FormLabel>
+ <FormControl>
+ <NativeSelect
+ data-testid="bedrock-region-select"
+ onChange={(e) => field.onChange(e.target.value)}
+ value={
+ typeof field.value === "string" ? field.value : "us-east-1"
+ }
+ disabled={field.disabled}
+ className="inline-flex mr-2"
+ >
+ {AWS_REGIONS.map((option) => (
+ <option value={option} key={option}>
+ {option}
+ </option>
+ ))}
+ </NativeSelect>
+ </FormControl>
+ <FormMessage />
+ <IsOverridden userConfig={config} name="ai.bedrock.region_name" />
+ </FormItem>
+ <FormDescription>
+ The AWS region where Bedrock service is available.
+ </FormDescription>
+ </div>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ disabled={isWasmRuntime}
+ name="ai.bedrock.profile_name"
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>AWS Profile Name (Optional)</FormLabel>
+ <FormControl>
+ <Input
+ data-testid="bedrock-profile-input"
+ rootClassName="flex-1"
+ className="m-0 inline-flex h-7"
+ placeholder="default"
+ {...field}
+ value={field.value || ""}
+ />
+ </FormControl>
+ <FormMessage />
+ <IsOverridden
+ userConfig={config}
+ name="ai.bedrock.profile_name"
+ />
+ </FormItem>
+ <FormDescription>
+ The AWS profile name from your ~/.aws/credentials file. Leave
+ blank to use your default AWS credentials.
+ </FormDescription>
+ </div>
+ )}
+ />
+
+ <AiProviderTitle>OpenAI-Compatible</AiProviderTitle>
+ <ApiKey
+ form={form}
+ config={config}
+ name="ai.open_ai_compatible.api_key"
+ placeholder="sk-..."
+ testId="ai-openai-compatible-api-key-input"
+ description={
+ <>
+ API key for any OpenAI-compatible provider (e.g., Together, Groq,
+ Mistral, Perplexity, etc).
+ </>
+ }
+ />
+ <BaseUrl
+ form={form}
+ config={config}
+ name="ai.open_ai_compatible.base_url"
+ placeholder="https://api.together.xyz/v1"
+ testId="ai-openai-compatible-base-url-input"
+ description={<>Base URL for your OpenAI-compatible provider.</>}
+ />
+ </SettingGroup>
+ );
+};
+
+export const AiAssistConfig: React.FC<AiConfigProps> = ({ form, config }) => {
+ const isWasmRuntime = isWasm();
+
+ return (
+ <SettingGroup title="AI Assist">
+ <p className="text-sm text-muted-secondary">
+ Add an API key below or to <Kbd className="inline">marimo.toml</Kbd> to
+ activate marimo's AI assistant for chat or edits; see{" "}
+ <ExternalLink href="https://docs.marimo.io/guides/editor_features/ai_completion/">
+ docs
+ </ExternalLink>{" "}
+ for more info.
+ </p>
+
+ <ModelSelector
+ form={form}
+ config={config}
+ name="ai.open_ai.model"
+ placeholder="gpt-4-turbo"
+ testId="ai-model-input"
+ disabled={isWasmRuntime}
+ description={
+ <>
+ <p>
+ Models should include the provider name and model name separated
+ by a slash. For example, "anthropic/claude-3-7-sonnet-latest" or
+ "google/gemini-2.5-flash-preview-05-20".
+ </p>
+ <p className="pt-1">
+ Depending on the provider, we will use the respective API key and
+ additional configuration.
+ </p>
+ </>
+ }
+ />
+
+ <FormField
+ control={form.control}
+ name="ai.rules"
+ render={({ field }) => (
+ <div className="flex flex-col">
+ <FormItem>
+ <FormLabel>Custom Rules</FormLabel>
+ <FormControl>
+ <Textarea
+ data-testid="ai-rules-input"
+ className="m-0 inline-flex w-full h-32 p-2 text-sm"
+ placeholder="e.g. Always use type hints; prefer polars over pandas"
+ {...field}
+ value={field.value}
+ />
+ </FormControl>
+ <FormMessage />
+ <IsOverridden userConfig={config} name="ai.rules" />
+ </FormItem>
+ <FormDescription>
+ Custom rules to include in all AI completion prompts.
+ </FormDescription>
+ </div>
+ )}
+ />
+ </SettingGroup>
+ );
+};
+
+export const AiConfig: React.FC<AiConfigProps> = ({
+ form,
+ config,
+ onSubmit,
+}) => {
+ return (
+ <>
+ <AiCodeCompletionConfig form={form} config={config} onSubmit={onSubmit} />
+ <AiAssistConfig form={form} config={config} onSubmit={onSubmit} />
+ <AiKeysConfig form={form} config={config} onSubmit={onSubmit} />
+ </>
+ );
+};
diff --git a/frontend/src/components/app-config/is-overridden.tsx b/frontend/src/components/app-config/is-overridden.tsx
index 4fcee1f39d..afb94efcdc 100644
--- a/frontend/src/components/app-config/is-overridden.tsx
+++ b/frontend/src/components/app-config/is-overridden.tsx
@@ -2,6 +2,7 @@
import { useAtomValue } from "jotai";
import { get } from "lodash-es";
+import { FolderCog2 } from "lucide-react";
import type { FieldPath } from "react-hook-form";
import { Tooltip } from "@/components/ui/tooltip";
import { configOverridesAtom, useUserConfig } from "@/core/config/config";
@@ -12,7 +13,7 @@ import { Kbd } from "../ui/kbd";
* Hook to determine if a user config value is overridden by project config.
* Returns { isOverridden, currentValue, overriddenValue }
*/
-export function useIsConfigOverridden(
+function useIsConfigOverridden(
userConfig: UserConfig,
name: FieldPath<UserConfig>,
): {
@@ -68,3 +69,51 @@ export const DisableIfOverridden = ({
children
);
};
+
+export const IsOverridden = ({
+ userConfig,
+ name,
+}: {
+ userConfig: UserConfig;
+ name: FieldPath<UserConfig>;
+}) => {
+ const { isOverridden, currentValue, overriddenValue } = useIsConfigOverridden(
+ userConfig,
+ name,
+ );
+
+ if (!isOverridden) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ content={
+ <>
+ <span>
+ This setting is overridden by{" "}
+ <Kbd className="inline">pyproject.toml</Kbd>.
+ </span>
+ <br />
+ <span>
+ Edit the <Kbd className="inline">pyproject.toml</Kbd> file directly
+ to change this setting.
+ </span>
+ <br />
+ <span>
+ User value: <strong>{String(currentValue)}</strong>
+ </span>
+ <br />
+ <span>
+ Project value: <strong>{String(overriddenValue)}</strong>
+ </span>
+ </>
+ }
+ >
+ <span className="text-(--amber-12) text-xs flex items-center gap-1 border rounded px-2 py-1 bg-(--amber-2) border-(--amber-6) ml-1">
+ <FolderCog2 className="w-3 h-3" />
+ Overridden by pyproject.toml [{String(overriddenValue)}]
+ </span>
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 47207641e1..479b58d20b 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -13,7 +13,7 @@ import {
PackageIcon,
} from "lucide-react";
import React, { useRef } from "react";
-import { type FieldPath, useForm } from "react-hook-form";
+import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
@@ -25,12 +25,10 @@ import {
FormLabel,
FormMessage,
} from "@/components/ui/form";
-import { Input } from "@/components/ui/input";
import { Kbd } from "@/components/ui/kbd";
import { NativeSelect } from "@/components/ui/native-select";
import { NumberField } from "@/components/ui/number-field";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { CopilotConfig } from "@/core/codemirror/copilot/copilot-config";
import { KEYMAP_PRESETS } from "@/core/codemirror/keymaps/keymaps";
import { capabilitiesAtom } from "@/core/config/capabilities";
import { useUserConfig } from "@/core/config/config";
@@ -47,16 +45,13 @@ import { Banner } from "@/plugins/impl/common/error-banner";
import { THEMES } from "@/theme/useTheme";
import { arrayToggle } from "@/utils/arrays";
import { cn } from "@/utils/cn";
-import { AiProviderIcon } from "../ai/AiProviderIcon";
import { keyboardShortcutsAtom } from "../editor/controls/keyboard-shortcuts";
import { Badge } from "../ui/badge";
import { ExternalLink } from "../ui/links";
-import { Textarea } from "../ui/textarea";
import { Tooltip } from "../ui/tooltip";
+import { AiConfig } from "./ai-config";
import { SettingSubtitle, SQL_OUTPUT_SELECT_OPTIONS } from "./common";
-import { AWS_REGIONS, KNOWN_AI_MODELS } from "./constants";
-import { IncorrectModelId } from "./incorrect-model-id";
-import { useIsConfigOverridden } from "./is-overridden";
+import { IsOverridden } from "./is-overridden";
import { OptionalFeatures } from "./optional-features";
const formItemClasses = "flex flex-row items-center space-x-1 space-y-0";
@@ -136,128 +131,6 @@ export const UserConfigForm: React.FC = () => {
const isWasmRuntime = isWasm();
- const renderCopilotProvider = () => {
- const copilot = form.getValues("completion.copilot");
- if (copilot === false) {
- return null;
- }
-
- if (copilot === "codeium") {
- return (
- <>
- <p className="text-sm text-muted-secondary">
- To get a Windsurf API key, follow{" "}
- <ExternalLink href="https://docs.marimo.io/guides/editor_features/ai_completion.html#windsurf-copilot">
- these instructions
- </ExternalLink>
- .
- </p>
- <FormField
- control={form.control}
- name="completion.codeium_api_key"
- render={({ field }) => (
- <FormItem className={formItemClasses}>
- <FormLabel>API Key</FormLabel>
- <FormControl>
- <Input
- data-testid="codeium-api-key-input"
- className="m-0 inline-flex"
- placeholder="key"
- {...field}
- value={field.value || ""}
- />
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="completion.codeium_api_key"
- />
- </FormItem>
- )}
- />
- </>
- );
- }
-
- 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>
- <IncorrectModelId value={field.value} />
- </>
- )}
- />
- <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 = () => {
switch (activeCategory) {
case "editor":
@@ -1286,381 +1159,7 @@ export const UserConfigForm: React.FC = () => {
</SettingGroup>
);
case "ai":
- return (
- <>
- <SettingGroup title="AI Code Completion">
- <p className="text-sm text-muted-secondary">
- You may use GitHub Copilot, Codeium, or a custom provider (e.g.
- Ollama) for AI code completion.
- </p>
-
- <FormField
- control={form.control}
- name="completion.copilot"
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel>Provider</FormLabel>
- <FormControl>
- <NativeSelect
- data-testid="copilot-select"
- onChange={(e) => {
- if (e.target.value === "none") {
- field.onChange(false);
- } else {
- field.onChange(e.target.value);
- }
- }}
- value={
- field.value === true
- ? "github"
- : field.value === false
- ? "none"
- : field.value
- }
- disabled={field.disabled}
- className="inline-flex mr-2"
- >
- {["none", "github", "codeium", "custom"].map(
- (option) => (
- <option value={option} key={option}>
- {option}
- </option>
- ),
- )}
- </NativeSelect>
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="completion.copilot"
- />
- </FormItem>
- </div>
- )}
- />
-
- {renderCopilotProvider()}
- </SettingGroup>
- <SettingGroup title="AI Keys">
- <FormField
- control={form.control}
- name="ai.open_ai.api_key"
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel className="flex">
- <AiProviderIcon provider="openai" className="mr-2" />
- OpenAI API Key
- </FormLabel>
- <FormControl>
- <Input
- data-testid="ai-openai-api-key-input"
- className="m-0 inline-flex"
- placeholder="sk-proj..."
- {...field}
- onChange={(e) => {
- const value = e.target.value;
- // Don't allow *
- if (!value.includes("*")) {
- field.onChange(value);
- }
- }}
- />
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="ai.open_ai.api_key"
- />
- </FormItem>
- <FormDescription>
- Your OpenAI API key from{" "}
- <ExternalLink href="https://platform.openai.com/account/api-keys">
- platform.openai.com
- </ExternalLink>
- .
- </FormDescription>
- </div>
- )}
- />
-
- <FormField
- control={form.control}
- name="ai.anthropic.api_key"
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel className="flex">
- <AiProviderIcon provider="anthropic" className="mr-2" />
- Anthropic API Key
- </FormLabel>
- <FormControl>
- <Input
- data-testid="ai-anthropic-api-key-input"
- className="m-0 inline-flex"
- placeholder="sk-ant..."
- {...field}
- onChange={(e) => {
- const value = e.target.value;
- // Don't allow *
- if (!value.includes("*")) {
- field.onChange(value);
- }
- }}
- />
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="ai.anthropic.api_key"
- />
- </FormItem>
- <FormDescription>
- Your Anthropic API key from{" "}
- <ExternalLink href="https://console.anthropic.com/settings/keys">
- console.anthropic.com
- </ExternalLink>
- .
- </FormDescription>
- </div>
- )}
- />
-
- <FormField
- control={form.control}
- name="ai.google.api_key"
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel className="flex">
- <AiProviderIcon provider="google" className="mr-2" />
- Google AI API Key
- </FormLabel>
- <FormControl>
- <Input
- data-testid="ai-google-api-key-input"
- className="m-0 inline-flex"
- placeholder="AI..."
- {...field}
- onChange={(e) => {
- const value = e.target.value;
- // Don't allow *
- if (!value.includes("*")) {
- field.onChange(value);
- }
- }}
- />
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="ai.google.api_key"
- />
- </FormItem>
- <FormDescription>
- Your Google AI API key from{" "}
- <ExternalLink href="https://aistudio.google.com/app/apikey">
- aistudio.google.com
- </ExternalLink>
- .
- </FormDescription>
- </div>
- )}
- />
-
- <p className="text-sm font-semibold mt-3">
- AWS Bedrock Configuration
- </p>
- <p className="text-sm text-muted-secondary mb-2">
- To use AWS Bedrock, you need to configure AWS credentials and
- region. See the{" "}
- <ExternalLink href="https://docs.marimo.io/guides/editor_features/ai_completion.html#aws-bedrock">
- documentation
- </ExternalLink>{" "}
- for more details.
- </p>
- <FormField
- control={form.control}
- disabled={isWasmRuntime}
- name="ai.bedrock.region_name"
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel>AWS Region</FormLabel>
- <FormControl>
- <NativeSelect
- data-testid="bedrock-region-select"
- onChange={(e) => field.onChange(e.target.value)}
- value={
- typeof field.value === "string"
- ? field.value
- : "us-east-1"
- }
- disabled={field.disabled}
- className="inline-flex mr-2"
- >
- {AWS_REGIONS.map((option) => (
- <option value={option} key={option}>
- {option}
- </option>
- ))}
- </NativeSelect>
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="ai.bedrock.region_name"
- />
- </FormItem>
- <FormDescription>
- The AWS region where Bedrock service is available.
- </FormDescription>
- </div>
- )}
- />
-
- <FormField
- control={form.control}
- disabled={isWasmRuntime}
- name="ai.bedrock.profile_name"
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel>AWS Profile Name (Optional)</FormLabel>
- <FormControl>
- <Input
- data-testid="bedrock-profile-input"
- className="m-0 inline-flex"
- placeholder="default"
- {...field}
- value={field.value || ""}
- />
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="ai.bedrock.profile_name"
- />
- </FormItem>
- <FormDescription>
- The AWS profile name from your ~/.aws/credentials file.
- Leave blank to use your default AWS credentials.
- </FormDescription>
- </div>
- )}
- />
- </SettingGroup>
-
- <SettingGroup title="AI Assist">
- <p className="text-sm text-muted-secondary">
- Add an API key to <Kbd className="inline">marimo.toml</Kbd> to
- activate marimo's AI assistant; see{" "}
- <ExternalLink href="https://docs.marimo.io/guides/editor_features/ai_completion.html">
- docs
- </ExternalLink>{" "}
- for more info.
- </p>
- <FormField
- control={form.control}
- disabled={isWasmRuntime}
- name="ai.open_ai.base_url"
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel>Base URL</FormLabel>
- <FormControl>
- <Input
- data-testid="ai-base-url-input"
- className="m-0 inline-flex"
- placeholder="https://api.openai.com/v1"
- {...field}
- />
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="ai.open_ai.base_url"
- />
- </FormItem>
- <FormDescription>
- This URL can be any OpenAI-compatible API endpoint.
- </FormDescription>
- </div>
- )}
- />
- <FormField
- control={form.control}
- disabled={isWasmRuntime}
- name="ai.open_ai.model"
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel>Model</FormLabel>
- <FormControl>
- <Input
- list="ai-model-datalist"
- data-testid="ai-model-input"
- className="m-0 inline-flex"
- placeholder="gpt-4-turbo"
- {...field}
- />
- </FormControl>
- <FormMessage />
- <IsOverridden
- userConfig={config}
- name="ai.open_ai.model"
- />
- </FormItem>
- <datalist id="ai-model-datalist">
- {KNOWN_AI_MODELS.map((model) => (
- <option value={model} key={model}>
- {model}
- </option>
- ))}
- </datalist>
- <IncorrectModelId value={field.value} />
- <FormDescription>
- Models should include the provider name and model name
- separated by a slash. For example,
- "anthropic/claude-3-7-sonnet-latest" or
- "google/gemini-2.5-flash-preview-05-20".
- <br />
- Depending on the provider, we will use the respective API
- key and additional configuration.
- </FormDescription>
- </div>
- )}
- />
-
- <FormField
- control={form.control}
- name="ai.rules"
- render={({ field }) => (
- <div className="flex flex-col">
- <FormItem>
- <FormLabel>Custom Rules</FormLabel>
- <FormControl>
- <Textarea
- data-testid="ai-rules-input"
- className="m-0 inline-flex w-full h-32 p-2 text-sm"
- placeholder="e.g. Always use type hints; prefer polars over pandas"
- {...field}
- value={field.value}
- />
- </FormControl>
- <FormMessage />
- <IsOverridden userConfig={config} name="ai.rules" />
- </FormItem>
- <FormDescription>
- Custom rules to include in all AI completion prompts.
- </FormDescription>
- </div>
- )}
- />
- </SettingGroup>
- </>
- );
+ return <AiConfig form={form} config={config} onSubmit={onSubmit} />;
case "optionalDeps":
return <OptionalFeatures />;
case "labs":
@@ -1828,51 +1327,3 @@ const SettingGroup = ({
</div>
);
};
-
-const IsOverridden = ({
- userConfig,
- name,
-}: {
- userConfig: UserConfig;
- name: FieldPath<UserConfig>;
-}) => {
- const { isOverridden, currentValue, overriddenValue } = useIsConfigOverridden(
- userConfig,
- name,
- );
-
- if (!isOverridden) {
- return null;
- }
-
- return (
- <Tooltip
- content={
- <>
- <span>
- This setting is overridden by{" "}
- <Kbd className="inline">pyproject.toml</Kbd>.
- </span>
- <br />
- <span>
- Edit the <Kbd className="inline">pyproject.toml</Kbd> file directly
- to change this setting.
- </span>
- <br />
- <span>
- User value: <strong>{String(currentValue)}</strong>
- </span>
- <br />
- <span>
- Project value: <strong>{String(overriddenValue)}</strong>
- </span>
- </>
- }
- >
- <span className="text-(--amber-12) text-xs flex items-center gap-1 border rounded px-2 py-1 bg-(--amber-2) border-(--amber-6) ml-1">
- <FolderCog2 className="w-3 h-3" />
- Overridden by pyproject.toml [{String(overriddenValue)}]
- </span>
- </Tooltip>
- );
-};
diff --git a/frontend/src/components/ui/links.tsx b/frontend/src/components/ui/links.tsx
index 10e83dae29..804cabf4f5 100644
--- a/frontend/src/components/ui/links.tsx
+++ b/frontend/src/components/ui/links.tsx
@@ -11,7 +11,8 @@ export const ExternalLink = ({
| `https://docs.marimo.io/${string}`
| `https://docs.python.org/${string}`
| `https://marimo.io/${string}`
- | `https://links.marimo.app/${string}`;
+ | `https://links.marimo.app/${string}`
+ | `https://portal.azure.com/${string}`;
children: React.ReactNode;
}) => {
return (
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index 4f83030d37..f18e2b545c 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -42,6 +42,13 @@ export type SqlOutputType = (typeof VALID_SQL_OUTPUT_FORMATS)[number];
*/
const AUTO_DOWNLOAD_FORMATS = ["html", "markdown", "ipynb"] as const;
+const AiConfigSchema = z
+ .object({
+ api_key: z.string().optional(),
+ base_url: z.string().optional(),
+ })
+ .passthrough();
+
export const UserConfigSchema = z
.object({
completion: z
@@ -135,23 +142,18 @@ export const UserConfigSchema = z
.object({
rules: z.string().default(""),
mode: z.enum(["manual", "ask"]).default("manual"),
- open_ai: z
- .object({
- api_key: z.string().optional(),
- base_url: z.string().optional(),
- model: z.string().optional(),
- })
- .optional(),
- anthropic: z
- .object({
- api_key: z.string().optional(),
- })
- .optional(),
- google: z
- .object({
- api_key: z.string().optional(),
- })
+ // TODO: the model currently exists on the open_ai object, but we should
+ // move it to the top level.
+ open_ai: AiConfigSchema.extend({
+ model: z.string().optional(),
+ })
+ .passthrough()
.optional(),
+ anthropic: AiConfigSchema.optional(),
+ google: AiConfigSchema.optional(),
+ ollama: AiConfigSchema.optional(),
+ open_ai_compatible: AiConfigSchema.optional(),
+ azure: AiConfigSchema.optional(),
bedrock: z
.object({
region_name: z.string().optional(),
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 30d2391e8b..625a55ff8c 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -24,6 +24,7 @@ if TYPE_CHECKING:
def _generate_server_api_schema() -> dict[str, Any]:
from starlette.schemas import SchemaGenerator
+ import marimo._config.config as config
import marimo._data.models as data
import marimo._messaging.errors as errors
import marimo._messaging.ops as ops
@@ -38,7 +39,6 @@ def _generate_server_api_schema() -> dict[str, Any]:
import marimo._server.models.secrets as secrets
import marimo._snippets.snippets as snippets
from marimo._ast.cell import CellConfig, RuntimeStateType
- from marimo._config.config import MarimoConfig
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.mime import MIME
@@ -61,7 +61,12 @@ def _generate_server_api_schema() -> dict[str, Any]:
data.NonNestedLiteral,
data.DataType,
CellConfig,
- MarimoConfig,
+ config.OpenAiConfig,
+ config.AnthropicConfig,
+ config.GoogleAiConfig,
+ config.BedrockConfig,
+ config.AiConfig,
+ config.MarimoConfig,
# Errors
errors.SetupRootError,
errors.MultipleDefinitionError,
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 00484fd27b..571732a64f 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -251,10 +251,15 @@ class AiConfig(TypedDict, total=False):
rules: NotRequired[str]
max_tokens: NotRequired[int]
mode: NotRequired[CopilotMode]
+
+ # providers
open_ai: OpenAiConfig
anthropic: AnthropicConfig
google: GoogleAiConfig
bedrock: BedrockConfig
+ azure: OpenAiConfig
+ ollama: OpenAiConfig
+ open_ai_compatible: OpenAiConfig
@dataclass
diff --git a/marimo/_config/secrets.py b/marimo/_config/secrets.py
index af0a8ae328..813642e87e 100644
--- a/marimo/_config/secrets.py
+++ b/marimo/_config/secrets.py
@@ -30,6 +30,9 @@ def mask_secrets(config: MarimoConfig) -> MarimoConfig:
secrets = [
["ai", "open_ai", "api_key"],
+ ["ai", "open_ai_compatible", "api_key"],
+ ["ai", "azure", "api_key"],
+ ["ai", "ollama", "api_key"],
["ai", "anthropic", "api_key"],
["ai", "google", "api_key"],
["ai", "bedrock", "aws_access_key_id"],
diff --git a/marimo/_server/ai/config.py b/marimo/_server/ai/config.py
new file mode 100644
index 0000000000..689f306ea0
--- /dev/null
+++ b/marimo/_server/ai/config.py
@@ -0,0 +1,235 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import (
+ Any,
+ Optional,
+ cast,
+)
+
+from starlette.exceptions import HTTPException
+
+from marimo._config.config import (
+ AiConfig,
+ CompletionConfig,
+ CopilotMode,
+ MarimoConfig,
+)
+from marimo._server.ai.ids import AiModelId
+from marimo._server.ai.tools import Tool, get_tool_manager
+from marimo._server.api.status import HTTPStatus
+
+DEFAULT_MAX_TOKENS = 4096
+DEFAULT_MODEL = "gpt-4o-mini"
+
+
+@dataclass
+class AnyProviderConfig:
+ """Normalized config for any AI provider."""
+
+ base_url: Optional[str]
+ api_key: str
+ ssl_verify: Optional[bool] = None
+ ca_bundle_path: Optional[str] = None
+ client_pem: Optional[str] = None
+ tools: list[Tool] = field(default_factory=list)
+
+ @classmethod
+ def for_openai(cls, config: AiConfig) -> AnyProviderConfig:
+ return cls._for_openai_like(config, "open_ai", "OpenAI")
+
+ @classmethod
+ def for_azure(cls, config: AiConfig) -> AnyProviderConfig:
+ return cls._for_openai_like(config, "azure", "Azure OpenAI")
+
+ @classmethod
+ def for_openai_compatible(cls, config: AiConfig) -> AnyProviderConfig:
+ return cls._for_openai_like(
+ config, "open_ai_compatible", "OpenAI Compatible"
+ )
+
+ @classmethod
+ def for_ollama(cls, config: AiConfig) -> AnyProviderConfig:
+ return cls._for_openai_like(
+ config, "ollama", "Ollama", fallback_key="ollama-placeholder"
+ )
+
+ @classmethod
+ def _for_openai_like(
+ cls,
+ config: AiConfig,
+ key: str,
+ name: str,
+ *,
+ fallback_key: Optional[str] = None,
+ ) -> AnyProviderConfig:
+ ai_config = _get_ai_config(config, key, name)
+ key = _get_key(ai_config, name, fallback_key=fallback_key)
+
+ kwargs: dict[str, Any] = {
+ "base_url": _get_base_url(ai_config),
+ "api_key": key,
+ "ssl_verify": ai_config.get("ssl_verify", True),
+ "ca_bundle_path": ai_config.get("ca_bundle_path", None),
+ "client_pem": ai_config.get("client_pem", None),
+ }
+
+ # Only include tools if they are available
+ # Empty tools list causes an error with deepseek
+ # https://discord.com/channels/1059888774789730424/1387766267792068821
+ tools = _get_tools(config.get("mode", "manual"))
+ if len(tools) > 0:
+ kwargs["tools"] = tools
+
+ return AnyProviderConfig(**kwargs)
+
+ @classmethod
+ def for_anthropic(cls, config: AiConfig) -> AnyProviderConfig:
+ ai_config = _get_ai_config(config, "anthropic", "Anthropic")
+ key = _get_key(ai_config, "Anthropic")
+ return cls(
+ base_url=_get_base_url(ai_config),
+ api_key=key,
+ tools=_get_tools(config.get("mode", "manual")),
+ )
+
+ @classmethod
+ def for_google(cls, config: AiConfig) -> AnyProviderConfig:
+ ai_config = _get_ai_config(config, "google", "Google AI")
+ key = _get_key(ai_config, "Google AI")
+ return cls(
+ base_url=_get_base_url(ai_config),
+ api_key=key,
+ tools=_get_tools(config.get("mode", "manual")),
+ )
+
+ @classmethod
+ def for_bedrock(cls, config: AiConfig) -> AnyProviderConfig:
+ ai_config = _get_ai_config(config, "bedrock", "Bedrock")
+ key = _get_key(ai_config, "Bedrock")
+ return cls(
+ base_url=_get_base_url(ai_config),
+ api_key=key,
+ tools=_get_tools(config.get("mode", "manual")),
+ )
+
+ @classmethod
+ def for_completion(cls, config: CompletionConfig) -> AnyProviderConfig:
+ key = _get_key(config, "AI completion")
+ return cls(
+ base_url=_get_base_url(config),
+ api_key=key,
+ tools=[], # Inline completion never uses tools
+ )
+
+ @classmethod
+ def for_model(cls, model: str, config: AiConfig) -> AnyProviderConfig:
+ model_id = AiModelId.from_model(model)
+ if model_id.provider == "anthropic":
+ return cls.for_anthropic(config)
+ elif model_id.provider == "google":
+ return cls.for_google(config)
+ elif model_id.provider == "bedrock":
+ return cls.for_bedrock(config)
+ elif model_id.provider == "ollama":
+ return cls.for_ollama(config)
+ elif model_id.provider == "openai":
+ return cls.for_openai(config)
+ elif model_id.provider == "azure":
+ return cls.for_azure(config)
+ elif model_id.provider == "openai_compatible":
+ return cls.for_openai_compatible(config)
+ else:
+ # Catch-all: try OpenAI compatible first, then OpenAI.
+ try:
+ return cls.for_openai_compatible(config)
+ except HTTPException:
+ return cls.for_openai(config)
+
+
+def _get_tools(mode: CopilotMode) -> list[Tool]:
+ tool_manager = get_tool_manager()
+ return tool_manager.get_tools_for_mode(mode)
+
+
+def _get_ai_config(config: AiConfig, key: str, name: str) -> dict[str, Any]:
+ if key not in config:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail=f"{name} config not found",
+ )
+ return cast(dict[str, Any], config.get(key, {}))
+
+
+def get_model(config: AiConfig) -> str:
+ return config.get("open_ai", {}).get("model") or DEFAULT_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_key(
+ config: Any,
+ name: str,
+ *,
+ fallback_key: Optional[str] = None,
+) -> str:
+ """Get the API key for a given provider."""
+ if not isinstance(config, dict):
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Invalid config",
+ )
+
+ if name == "Bedrock":
+ if "profile_name" in config:
+ profile_name = config.get("profile_name", "")
+ return f"profile:{profile_name}"
+ elif (
+ "aws_access_key_id" in config and "aws_secret_access_key" in config
+ ):
+ return f"{config['aws_access_key_id']}:{config['aws_secret_access_key']}"
+ else:
+ return ""
+
+ if "api_key" in config:
+ key = config["api_key"]
+ if key:
+ return cast(str, key)
+
+ if "http://127.0.0.1:11434/" in config.get("base_url", ""):
+ # Ollama can be configured and in that case the api key is not needed.
+ # We send a placeholder value to prevent the user from being confused.
+ return "ollama-placeholder"
+
+ if fallback_key:
+ return fallback_key
+
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail=f"{name} API key not configured",
+ )
+
+
+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 == "Bedrock":
+ if "region_name" in config:
+ return cast(str, config["region_name"])
+ else:
+ return None
+ elif "base_url" in config:
+ return cast(str, config["base_url"])
+ return None
diff --git a/marimo/_server/ai/ids.py b/marimo/_server/ai/ids.py
index fca30eea7c..8a365372c3 100644
--- a/marimo/_server/ai/ids.py
+++ b/marimo/_server/ai/ids.py
@@ -48,6 +48,7 @@ def _guess_provider(model: str) -> AiProviderId:
def is_openai(model: str) -> bool:
return (
model.startswith("gpt")
+ or model.startswith("o4")
or model.startswith("o3")
or model.startswith("o1")
)
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index 7adf293acc..75ec485a81 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -6,7 +6,7 @@ import os
import uuid
from abc import ABC, abstractmethod
from collections.abc import Generator, Iterator
-from dataclasses import dataclass, field
+from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
@@ -31,13 +31,8 @@ from marimo._ai._convert import (
convert_to_openai_tools,
)
from marimo._ai._types import ChatMessage
-from marimo._config.config import (
- AiConfig,
- CompletionConfig,
- CopilotMode,
- MarimoConfig,
-)
from marimo._dependencies.dependencies import DependencyManager
+from marimo._server.ai.config import AnyProviderConfig
from marimo._server.ai.ids import AiModelId
from marimo._server.api.status import HTTPStatus
@@ -72,7 +67,6 @@ if TYPE_CHECKING:
ChatCompletionChunk,
)
-from marimo._server.ai.tools import Tool, get_tool_manager
ResponseT = TypeVar("ResponseT")
StreamT = TypeVar("StreamT")
@@ -103,9 +97,6 @@ StreamContent = Union[StreamTextContent, StreamDictContent, FinishContent]
LOGGER = _loggers.marimo_logger()
-DEFAULT_MAX_TOKENS = 4096
-DEFAULT_MODEL = "gpt-4o-mini"
-
@dataclass
class StreamOptions:
@@ -113,148 +104,6 @@ class StreamOptions:
format_stream: bool = False
-@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
- tools: list[Tool] = field(default_factory=list)
-
- @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")
-
- kwargs: dict[str, Any] = {
- "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),
- }
-
- # Only include tools if they are available
- # Empty tools list causes an error with deepseek
- # https://discord.com/channels/1059888774789730424/1387766267792068821
- tools = _get_tools(config.get("mode", "manual"))
- if len(tools) > 0:
- kwargs["tools"] = tools
-
- return AnyProviderConfig(**kwargs)
-
- @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,
- tools=_get_tools(config.get("mode", "manual")),
- )
-
- @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,
- tools=_get_tools(config.get("mode", "manual")),
- )
-
- @staticmethod
- def for_bedrock(config: AiConfig) -> AnyProviderConfig:
- if "bedrock" not in config:
- raise HTTPException(
- status_code=HTTPStatus.BAD_REQUEST,
- detail="Bedrock config not found",
- )
- key = _get_key(config["bedrock"], "Bedrock")
- return AnyProviderConfig(
- base_url=_get_base_url(config["bedrock"], "Bedrock"),
- api_key=key,
- tools=_get_tools(config.get("mode", "manual")),
- )
-
- @staticmethod
- def for_completion(config: CompletionConfig) -> AnyProviderConfig:
- key = _get_key(config, "AI completion")
- return AnyProviderConfig(
- base_url=_get_base_url(config),
- api_key=key,
- tools=[], # Inline completion never uses tools
- )
-
- @staticmethod
- def for_model(model: str, config: AiConfig) -> AnyProviderConfig:
- model_id = AiModelId.from_model(model)
- if model_id.provider == "anthropic":
- return AnyProviderConfig.for_anthropic(config)
- elif model_id.provider == "google":
- return AnyProviderConfig.for_google(config)
- elif model_id.provider == "bedrock":
- return AnyProviderConfig.for_bedrock(config)
- else:
- # OpenAI has a default API that ollama also uses, that is
- # why it is a catch all at the end here.
- return AnyProviderConfig.for_openai(config)
-
-
-def _get_key(config: Any, name: str) -> str:
- if name == "Bedrock":
- if "profile_name" in config:
- profile_name = config.get("profile_name", "")
- return f"profile:{profile_name}"
- elif (
- "aws_access_key_id" in config and "aws_secret_access_key" in config
- ):
- return f"{config['aws_access_key_id']}:{config['aws_secret_access_key']}"
- else:
- return ""
- if "api_key" in config:
- key = config["api_key"]
- if key:
- return cast(str, key)
- if "http://127.0.0.1:11434/" in config.get("base_url", ""):
- # Ollama can be configured and in that case the api key is not needed.
- # We send a placeholder value to prevent the user from being confused.
- return "ollama-placeholder"
- raise HTTPException(
- status_code=HTTPStatus.BAD_REQUEST,
- detail=f"{name} API key not configured",
- )
-
-
-def _get_base_url(config: Any, name: str = "") -> Optional[str]:
- if name == "Bedrock":
- if "region_name" in config:
- return cast(str, config["region_name"])
- else:
- return None
- elif "base_url" in config:
- return cast(str, config["base_url"])
- return None
-
-
-def _get_tools(mode: CopilotMode) -> list[Tool]:
- tool_manager = get_tool_manager()
- return tool_manager.get_tools_for_mode(mode)
-
-
class CompletionProvider(Generic[ResponseT, StreamT], ABC):
"""Base class for AI completion providers."""
@@ -473,7 +322,7 @@ class OpenAIProvider(
# https://openai.com/index/openai-o3-mini/
DEFAULT_REASONING_EFFORT = "medium"
- def is_reasoning_model(self, model: str) -> bool:
+ def _is_reasoning_model(self, model: str) -> bool:
# only o-series models support reasoning
return model.startswith("o")
@@ -481,20 +330,18 @@ class OpenAIProvider(
DependencyManager.openai.require(why="for AI assistance with OpenAI")
import ssl
-
- # library to check if paths exists
from pathlib import Path
- from urllib.parse import parse_qs, urlparse
- # ssl related libs, httpx is a dependency of openai
import httpx
- from openai import AzureOpenAI, OpenAI
+ from openai import OpenAI
base_url = config.base_url or None
key = config.api_key
# Add SSL parameters/values
- ssl_verify: bool = config.ssl_verify or True
+ ssl_verify: bool = (
+ config.ssl_verify if config.ssl_verify is not None else True
+ )
ca_bundle_path: Optional[str] = config.ca_bundle_path
client_pem: Optional[str] = config.client_pem
@@ -514,59 +361,44 @@ class OpenAIProvider(
status_code=HTTPStatus.BAD_REQUEST,
detail="Client PEM is not a valid path or does not exist",
)
- # 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:
- # the default httpx client uses ssl_verify=True by default under the hoood. We are checking if it's here, to see if the user overrides and uses false. If the ssl_verify argument isn't there, it is true by default
- if ssl_verify:
- ctx = None # Initialize ctx to avoid UnboundLocalError
- client = None # Initialize client to avoid UnboundLocalError
- if ca_bundle_path:
- ctx = ssl.create_default_context(cafile=ca_bundle_path)
- if client_pem:
- # if ctx already exists from caBundlePath argument
- if ctx:
- ctx.load_cert_chain(certfile=client_pem)
- else:
- ctx = ssl.create_default_context()
- ctx.load_cert_chain(certfile=client_pem)
-
- # if ssl context was created by the above statements
+
+ # the default httpx client uses ssl_verify=True by default under the hoood. We are checking if it's here, to see if the user overrides and uses false. If the ssl_verify argument isn't there, it is true by default
+ if ssl_verify:
+ ctx = None # Initialize ctx to avoid UnboundLocalError
+ client = None # Initialize client to avoid UnboundLocalError
+ if ca_bundle_path:
+ ctx = ssl.create_default_context(cafile=ca_bundle_path)
+ if client_pem:
+ # if ctx already exists from caBundlePath argument
if ctx:
- client = httpx.Client(verify=ctx)
+ ctx.load_cert_chain(certfile=client_pem)
else:
- pass
- else:
- client = httpx.Client(verify=False)
-
- # if client is created, either with a custom context or with verify=False, use it as the http_client object in `OpenAI`
- if client:
- return OpenAI(
- default_headers={"api-key": key},
- api_key=key,
- base_url=base_url,
- http_client=client,
- )
- # if not, return bog standard OpenAI object
+ ctx = ssl.create_default_context()
+ ctx.load_cert_chain(certfile=client_pem)
+
+ # if ssl context was created by the above statements
+ if ctx:
+ client = httpx.Client(verify=ctx)
else:
- return OpenAI(
- default_headers={"api-key": key},
- api_key=key,
- base_url=base_url,
- )
+ pass
+ else:
+ client = httpx.Client(verify=False)
+
+ # if client is created, either with a custom context or with verify=False, use it as the http_client object in `OpenAI`
+ if client:
+ return OpenAI(
+ default_headers={"api-key": key},
+ api_key=key,
+ base_url=base_url,
+ http_client=client,
+ )
+
+ # if not, return bog standard OpenAI object
+ return OpenAI(
+ default_headers={"api-key": key},
+ api_key=key,
+ base_url=base_url,
+ )
def stream_completion(
self,
@@ -591,7 +423,7 @@ class OpenAIProvider(
"timeout": 15,
"tools": convert_to_openai_tools(self.config.tools),
}
- if self.is_reasoning_model(self.model):
+ if self._is_reasoning_model(self.model):
create_params["reasoning_effort"] = self.DEFAULT_REASONING_EFFORT
return cast(
"OpenAiStream[ChatCompletionChunk]",
@@ -601,8 +433,9 @@ class OpenAIProvider(
def extract_content(
self,
response: ChatCompletionChunk,
- _tool_call_id: Optional[str] = None,
+ tool_call_id: Optional[str] = None,
) -> Optional[ExtractedContent]:
+ del tool_call_id
if (
hasattr(response, "choices")
and response.choices
@@ -670,6 +503,28 @@ class OpenAIProvider(
return messages
+class AzureOpenAIProvider(OpenAIProvider):
+ def get_client(self, config: AnyProviderConfig) -> OpenAI:
+ from urllib.parse import parse_qs, urlparse
+
+ from openai import AzureOpenAI
+
+ base_url = config.base_url or None
+ key = config.api_key
+
+ # Azure OpenAI clients are instantiated slightly differently
+ parsed_url = urlparse(base_url)
+ 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)}",
+ )
+
+
class AnthropicProvider(
CompletionProvider[
"RawMessageStreamEvent", "AnthropicStream[RawMessageStreamEvent]"
@@ -745,8 +600,9 @@ class AnthropicProvider(
def extract_content(
self,
response: RawMessageStreamEvent,
- _tool_call_id: Optional[str] = None,
+ tool_call_id: Optional[str] = None,
) -> Optional[ExtractedContent]:
+ del tool_call_id
from anthropic.types import (
InputJSONDelta,
RawContentBlockDeltaEvent,
@@ -978,8 +834,9 @@ class BedrockProvider(
def extract_content(
self,
response: LitellmStreamResponse,
- _tool_call_id: Optional[str] = None,
+ tool_call_id: Optional[str] = None,
) -> Optional[ExtractedContent]:
+ del tool_call_id
if (
hasattr(response, "choices")
and response.choices
@@ -1044,25 +901,12 @@ def get_completion_provider(
return GoogleProvider(model_id.model, config)
elif model_id.provider == "bedrock":
return BedrockProvider(model_id.model, config)
+ elif model_id.provider == "azure":
+ return AzureOpenAIProvider(model_id.model, config)
else:
return OpenAIProvider(model_id.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"]
-
-
def merge_backticks(chunks: Iterator[str]) -> Generator[str, None, None]:
buffer: Optional[str] = None
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index 9bc49562c7..df66f70acb 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -15,6 +15,12 @@ from starlette.responses import (
from marimo import _loggers
from marimo._ai._types import ChatMessage
from marimo._config.config import AiConfig, MarimoConfig
+from marimo._server.ai.config import (
+ DEFAULT_MODEL,
+ AnyProviderConfig,
+ get_max_tokens,
+ get_model,
+)
from marimo._server.ai.prompts import (
FILL_ME_TAG,
get_chat_system_prompt,
@@ -22,12 +28,8 @@ from marimo._server.ai.prompts import (
get_refactor_or_insert_notebook_cell_system_prompt,
)
from marimo._server.ai.providers import (
- DEFAULT_MODEL,
- AnyProviderConfig,
StreamOptions,
get_completion_provider,
- get_max_tokens,
- get_model,
without_wrapping_backticks,
)
from marimo._server.ai.tools import get_tool_manager
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 9ee9dd0691..48ea2e41a2 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -52,6 +52,32 @@ components:
- code
- language
type: object
+ AiConfig:
+ properties:
+ anthropic:
+ $ref: '#/components/schemas/AnthropicConfig'
+ azure:
+ $ref: '#/components/schemas/OpenAiConfig'
+ bedrock:
+ $ref: '#/components/schemas/BedrockConfig'
+ google:
+ $ref: '#/components/schemas/GoogleAiConfig'
+ max_tokens:
+ type: integer
+ mode:
+ enum:
+ - ask
+ - manual
+ type: string
+ ollama:
+ $ref: '#/components/schemas/OpenAiConfig'
+ open_ai:
+ $ref: '#/components/schemas/OpenAiConfig'
+ open_ai_compatible:
+ $ref: '#/components/schemas/OpenAiConfig'
+ rules:
+ type: string
+ type: object
AiInlineCompletionRequest:
properties:
language:
@@ -89,6 +115,11 @@ components:
- description
- name
type: object
+ AnthropicConfig:
+ properties:
+ api_key:
+ type: string
+ type: object
Banner:
properties:
action:
@@ -121,6 +152,17 @@ components:
required:
- success
type: object
+ BedrockConfig:
+ properties:
+ aws_access_key_id:
+ type: string
+ aws_secret_access_key:
+ type: string
+ profile_name:
+ type: string
+ region_name:
+ type: string
+ type: object
CellChannel:
enum:
- stdout
@@ -1095,6 +1137,11 @@ components:
- status
- name
type: object
+ GoogleAiConfig:
+ properties:
+ api_key:
+ type: string
+ type: object
HTTPRequest:
type: 'null'
HumanReadableStatus:
@@ -1444,53 +1491,7 @@ components:
MarimoConfig:
properties:
ai:
- properties:
- anthropic:
- properties:
- api_key:
- type: string
- type: object
- bedrock:
- properties:
- aws_access_key_id:
- type: string
- aws_secret_access_key:
- type: string
- profile_name:
- type: string
- region_name:
- type: string
- type: object
- google:
- properties:
- api_key:
- type: string
- type: object
- max_tokens:
- type: integer
- mode:
- enum:
- - ask
- - manual
- type: string
- open_ai:
- properties:
- api_key:
- type: string
- base_url:
- type: string
- ca_bundle_path:
- type: string
- client_pem:
- type: string
- model:
- type: string
- ssl_verify:
- type: boolean
- type: object
- rules:
- type: string
- type: object
+ $ref: '#/components/schemas/AiConfig'
completion:
properties:
activate_on_typing:
@@ -1976,6 +1977,21 @@ components:
- type: boolean
- format: byte
type: string
+ OpenAiConfig:
+ properties:
+ api_key:
+ type: string
+ base_url:
+ type: string
+ ca_bundle_path:
+ type: string
+ client_pem:
+ type: string
+ model:
+ type: string
+ ssl_verify:
+ type: boolean
+ type: object
OpenTutorialRequest:
properties:
tutorialId:
@@ -2731,7 +2747,7 @@ components:
type: object
info:
title: marimo API
- version: 0.14.16
+ version: 0.14.17
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 78d444dd4c..77ec296076 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -2564,6 +2564,19 @@ export interface components {
prompt: string;
selectedText?: string | null;
};
+ AiConfig: {
+ anthropic?: components["schemas"]["AnthropicConfig"];
+ azure?: components["schemas"]["OpenAiConfig"];
+ bedrock?: components["schemas"]["BedrockConfig"];
+ google?: components["schemas"]["GoogleAiConfig"];
+ max_tokens?: number;
+ /** @enum {string} */
+ mode?: "ask" | "manual";
+ ollama?: components["schemas"]["OpenAiConfig"];
+ open_ai?: components["schemas"]["OpenAiConfig"];
+ open_ai_compatible?: components["schemas"]["OpenAiConfig"];
+ rules?: string;
+ };
AiInlineCompletionRequest: {
/** @enum {string} */
language: "python" | "markdown" | "sql";
@@ -2578,6 +2591,9 @@ export interface components {
/** @enum {string|null} */
variant?: "danger" | null;
};
+ AnthropicConfig: {
+ api_key?: string;
+ };
Banner: {
/** @enum {string|null} */
action?: "restart" | null;
@@ -2591,6 +2607,12 @@ export interface components {
BaseResponse: {
success: boolean;
};
+ BedrockConfig: {
+ aws_access_key_id?: string;
+ aws_secret_access_key?: string;
+ profile_name?: string;
+ region_name?: string;
+ };
/** @enum {string} */
CellChannel:
| "stdout"
@@ -2990,6 +3012,9 @@ export interface components {
| null;
status: components["schemas"]["HumanReadableStatus"];
};
+ GoogleAiConfig: {
+ api_key?: string;
+ };
HTTPRequest: null;
HumanReadableStatus: {
/** @enum {string} */
@@ -3152,32 +3177,7 @@ export interface components {
type: "ancestor-stopped";
};
MarimoConfig: {
- ai?: {
- anthropic?: {
- api_key?: string;
- };
- bedrock?: {
- aws_access_key_id?: string;
- aws_secret_access_key?: string;
- profile_name?: string;
- region_name?: string;
- };
- google?: {
- api_key?: string;
- };
- max_tokens?: number;
- /** @enum {string} */
- mode?: "ask" | "manual";
- open_ai?: {
- api_key?: string;
- base_url?: string;
- ca_bundle_path?: string;
- client_pem?: string;
- model?: string;
- ssl_verify?: boolean;
- };
- rules?: string;
- };
+ ai?: components["schemas"]["AiConfig"];
completion: {
activate_on_typing: boolean;
api_key?: string | null;
@@ -3388,6 +3388,14 @@ export interface components {
type: "multiple-defs";
};
NonNestedLiteral: number | string | boolean;
+ OpenAiConfig: {
+ api_key?: string;
+ base_url?: string;
+ ca_bundle_path?: string;
+ client_pem?: string;
+ model?: string;
+ ssl_verify?: boolean;
+ };
OpenTutorialRequest: {
tutorialId:
| (
diff --git a/tests/_server/ai/test_ai_config.py b/tests/_server/ai/test_ai_config.py
new file mode 100644
index 0000000000..92351299d4
--- /dev/null
+++ b/tests/_server/ai/test_ai_config.py
@@ -0,0 +1,589 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any, cast
+from unittest.mock import patch
+
+import pytest
+from starlette.exceptions import HTTPException
+
+from marimo._config.config import (
+ AiConfig,
+ CompletionConfig,
+ MarimoConfig,
+)
+from marimo._server.ai.config import (
+ DEFAULT_MAX_TOKENS,
+ DEFAULT_MODEL,
+ AnyProviderConfig,
+ _get_ai_config,
+ _get_base_url,
+ _get_key,
+ get_max_tokens,
+ get_model,
+)
+from marimo._server.ai.tools import Tool
+from marimo._server.api.status import HTTPStatus
+
+
+class TestAnyProviderConfig:
+ """Tests for AnyProviderConfig class."""
+
+ def test_for_openai_basic(self):
+ """Test basic OpenAI configuration."""
+ config: AiConfig = {
+ "open_ai": {
+ "api_key": "test-openai-key",
+ "model": "gpt-4",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_openai(config)
+
+ assert provider_config.api_key == "test-openai-key"
+ assert provider_config.base_url is None
+ assert provider_config.ssl_verify is True
+ assert provider_config.ca_bundle_path is None
+ assert provider_config.client_pem is None
+
+ def test_for_openai_with_base_url(self):
+ """Test OpenAI configuration with custom base URL."""
+ config: AiConfig = {
+ "open_ai": {
+ "api_key": "test-key",
+ "base_url": "https://custom.openai.com",
+ "ssl_verify": False,
+ "ca_bundle_path": "/path/to/ca.pem",
+ "client_pem": "/path/to/client.pem",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_openai(config)
+
+ assert provider_config.api_key == "test-key"
+ assert provider_config.base_url == "https://custom.openai.com"
+ assert provider_config.ssl_verify is False
+ assert provider_config.ca_bundle_path == "/path/to/ca.pem"
+ assert provider_config.client_pem == "/path/to/client.pem"
+
+ def test_for_azure(self):
+ """Test Azure OpenAI configuration."""
+ config: AiConfig = {
+ "azure": {
+ "api_key": "test-azure-key",
+ "base_url": "https://test.openai.azure.com",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_azure(config)
+
+ assert provider_config.api_key == "test-azure-key"
+ assert provider_config.base_url == "https://test.openai.azure.com"
+
+ def test_for_openai_compatible(self):
+ """Test OpenAI compatible service configuration."""
+ config: AiConfig = {
+ "open_ai_compatible": {
+ "api_key": "test-compatible-key",
+ "base_url": "https://compatible.service.com",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_openai_compatible(config)
+
+ assert provider_config.api_key == "test-compatible-key"
+ assert provider_config.base_url == "https://compatible.service.com"
+
+ def test_for_ollama(self):
+ """Test Ollama configuration."""
+ config: AiConfig = {
+ "ollama": {
+ "api_key": "test-ollama-key",
+ "base_url": "http://localhost:11434",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_ollama(config)
+
+ assert provider_config.api_key == "test-ollama-key"
+ assert provider_config.base_url == "http://localhost:11434"
+
+ def test_for_ollama_placeholder_key(self):
+ """Test Ollama configuration with default URL gets placeholder key."""
+ config: AiConfig = {
+ "ollama": {
+ "base_url": "http://127.0.0.1:11434/",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_ollama(config)
+
+ assert provider_config.api_key == "ollama-placeholder"
+
+ def test_for_anthropic(self):
+ """Test Anthropic configuration."""
+ config: AiConfig = {
+ "anthropic": {
+ "api_key": "test-anthropic-key",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_anthropic(config)
+
+ assert provider_config.api_key == "test-anthropic-key"
+ assert provider_config.base_url is None
+
+ def test_for_google(self):
+ """Test Google AI configuration."""
+ config: AiConfig = {
+ "google": {
+ "api_key": "test-google-key",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_google(config)
+
+ assert provider_config.api_key == "test-google-key"
+ assert provider_config.base_url is None
+
+ def test_for_bedrock_with_profile(self):
+ """Test Bedrock configuration with profile name."""
+ config: AiConfig = {
+ "bedrock": {
+ "profile_name": "test-profile",
+ "region_name": "us-east-1",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_bedrock(config)
+
+ assert provider_config.api_key == "profile:test-profile"
+ # Note: base_url is None because _get_base_url doesn't get "Bedrock" name parameter
+ assert provider_config.base_url is None
+
+ def test_for_bedrock_with_credentials(self):
+ """Test Bedrock configuration with AWS credentials."""
+ config: AiConfig = {
+ "bedrock": {
+ "aws_access_key_id": "test-access-key",
+ "aws_secret_access_key": "test-secret-key",
+ "region_name": "us-west-2",
+ }
+ }
+
+ provider_config = AnyProviderConfig.for_bedrock(config)
+
+ assert provider_config.api_key == "test-access-key:test-secret-key"
+ # Note: base_url is None because _get_base_url doesn't get "Bedrock" name parameter
+ assert provider_config.base_url is None
+
+ def test_for_completion(self):
+ """Test completion configuration."""
+ config: CompletionConfig = {
+ "activate_on_typing": True,
+ "copilot": "custom",
+ "api_key": "test-completion-key",
+ "base_url": "https://completion.service.com",
+ }
+
+ provider_config = AnyProviderConfig.for_completion(config)
+
+ assert provider_config.api_key == "test-completion-key"
+ assert provider_config.base_url == "https://completion.service.com"
+ assert provider_config.tools == [] # Completion never uses tools
+
+ def test_for_model_openai(self) -> None:
+ """Test for_model with OpenAI model."""
+ config: AiConfig = {"open_ai": {"api_key": "test-key"}}
+
+ provider_config = AnyProviderConfig.for_model("gpt-4", config)
+
+ assert provider_config.api_key == "test-key"
+
+ def test_for_model_anthropic(self) -> None:
+ """Test for_model with Anthropic model."""
+ config: AiConfig = {"anthropic": {"api_key": "test-anthropic-key"}}
+
+ provider_config = AnyProviderConfig.for_model("claude-3-opus", config)
+
+ assert provider_config.api_key == "test-anthropic-key"
+
+ def test_for_model_unknown_defaults_to_ollama(self) -> None:
+ """Test for_model with unknown provider defaults to Ollama."""
+ config: AiConfig = {"ollama": {"api_key": "test-key"}}
+
+ provider_config = AnyProviderConfig.for_model("unknown-model", config)
+
+ assert provider_config.api_key == "test-key"
+
+ def test_for_model_unknown_provider_defaults_to_openai_compatible(
+ self,
+ ) -> None:
+ """Test for_model with unknown provider defaults to OpenAI compatible."""
+ config: AiConfig = {
+ "open_ai_compatible": {"api_key": "test-key"},
+ "open_ai": {"api_key": "other-key"},
+ }
+
+ provider_config = AnyProviderConfig.for_model(
+ "provider/unknown-model", config
+ )
+
+ assert provider_config.api_key == "test-key"
+
+ # Fallback to OpenAI if OpenAI compatible is not configured
+ config: AiConfig = {
+ "open_ai": {"api_key": "other-key"},
+ }
+
+ provider_config = AnyProviderConfig.for_model(
+ "provider/unknown-model", config
+ )
+
+ assert provider_config.api_key == "other-key"
+
+ @patch("marimo._server.ai.config._get_tools")
+ def test_tools_included_when_available(self, mock_get_tools: Any) -> None:
+ """Test that tools are included when available."""
+ mock_tool = Tool(
+ name="test_tool",
+ description="Test tool",
+ parameters={},
+ source="backend",
+ mode=["manual"],
+ )
+ mock_get_tools.return_value = [mock_tool]
+
+ config: AiConfig = {
+ "open_ai": {"api_key": "test-key"},
+ "mode": "manual",
+ }
+
+ provider_config = AnyProviderConfig.for_openai(config)
+
+ assert len(provider_config.tools) == 1
+ assert provider_config.tools[0] == mock_tool
+
+ @patch("marimo._server.ai.config._get_tools")
+ def test_tools_excluded_when_empty(self, mock_get_tools: Any) -> None:
+ """Test that tools are excluded when empty to prevent errors with deepseek."""
+ mock_get_tools.return_value = []
+
+ config: AiConfig = {
+ "open_ai": {"api_key": "test-key"},
+ "mode": "manual",
+ }
+
+ provider_config = AnyProviderConfig.for_openai(config)
+
+ assert provider_config.tools == []
+
+
+class TestGetKey:
+ """Tests for _get_key function."""
+
+ def test_get_key_with_api_key(self):
+ """Test getting API key from config."""
+ config = {"api_key": "test-key"}
+
+ result = _get_key(config, "Test Service")
+
+ assert result == "test-key"
+
+ def test_get_key_bedrock_profile(self):
+ """Test getting Bedrock key with profile name."""
+ config = {"profile_name": "aws-profile"}
+
+ result = _get_key(config, "Bedrock")
+
+ assert result == "profile:aws-profile"
+
+ def test_get_key_bedrock_credentials(self):
+ """Test getting Bedrock key with AWS credentials."""
+ config = {
+ "aws_access_key_id": "access-key",
+ "aws_secret_access_key": "secret-key",
+ }
+
+ result = _get_key(config, "Bedrock")
+
+ assert result == "access-key:secret-key"
+
+ def test_get_key_bedrock_fallback(self):
+ """Test Bedrock key fallback when no credentials."""
+ config = {}
+
+ result = _get_key(config, "Bedrock")
+
+ assert result == ""
+
+ def test_get_key_ollama_placeholder(self):
+ """Test Ollama gets placeholder key for local URL."""
+ config = {"base_url": "http://127.0.0.1:11434/"}
+
+ result = _get_key(config, "Ollama")
+
+ assert result == "ollama-placeholder"
+
+ def test_get_key_invalid_config(self):
+ """Test error when config is not a dict."""
+ with pytest.raises(HTTPException) as exc_info:
+ _get_key("invalid", "Test Service")
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "Invalid config" in str(exc_info.value.detail)
+
+ def test_get_key_missing_api_key(self):
+ """Test error when API key is missing."""
+ config = {}
+
+ with pytest.raises(HTTPException) as exc_info:
+ _get_key(config, "Test Service")
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "Test Service API key not configured" in str(
+ exc_info.value.detail
+ )
+
+ def test_get_key_empty_api_key(self):
+ """Test error when API key is empty."""
+ config = {"api_key": ""}
+
+ with pytest.raises(HTTPException) as exc_info:
+ _get_key(config, "Test Service")
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "Test Service API key not configured" in str(
+ exc_info.value.detail
+ )
+
+ def test_get_key_none_api_key(self):
+ """Test error when API key is None."""
+ config = {"api_key": None}
+
+ with pytest.raises(HTTPException) as exc_info:
+ _get_key(config, "Test Service")
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "Test Service API key not configured" in str(
+ exc_info.value.detail
+ )
+
+
+class TestGetBaseUrl:
+ """Tests for _get_base_url function."""
+
+ def test_get_base_url_with_url(self):
+ """Test getting base URL from config."""
+ config = {"base_url": "https://api.example.com"}
+
+ result = _get_base_url(config)
+
+ assert result == "https://api.example.com"
+
+ def test_get_base_url_bedrock_region(self):
+ """Test getting Bedrock base URL from region."""
+ config = {"region_name": "us-east-1"}
+
+ result = _get_base_url(config, "Bedrock")
+
+ assert result == "us-east-1"
+
+ def test_get_base_url_bedrock_without_name_param(self):
+ """Test that Bedrock base URL is None when name param is not passed."""
+ config = {"region_name": "us-east-1"}
+
+ result = _get_base_url(config) # No name parameter
+
+ assert result is None
+
+ def test_get_base_url_bedrock_no_region(self):
+ """Test Bedrock base URL when no region specified."""
+ config = {}
+
+ result = _get_base_url(config, "Bedrock")
+
+ assert result is None
+
+ def test_get_base_url_missing(self):
+ """Test when base URL is not in config."""
+ config = {}
+
+ result = _get_base_url(config)
+
+ assert result is None
+
+ def test_get_base_url_invalid_config(self):
+ """Test error when config is not a dict."""
+ with pytest.raises(HTTPException) as exc_info:
+ _get_base_url("invalid")
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "Invalid config" in str(exc_info.value.detail)
+
+
+class TestGetAiConfig:
+ """Tests for _get_ai_config function."""
+
+ def test_get_ai_config_success(self):
+ """Test successful retrieval of AI config."""
+ config: AiConfig = {"open_ai": {"api_key": "test-key"}}
+
+ result = _get_ai_config(config, "open_ai", "OpenAI")
+
+ assert result == {"api_key": "test-key"}
+
+ def test_get_ai_config_missing_key(self):
+ """Test error when AI config key is missing."""
+ config: AiConfig = {}
+
+ with pytest.raises(HTTPException) as exc_info:
+ _get_ai_config(config, "open_ai", "OpenAI")
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "OpenAI config not found" in str(exc_info.value.detail)
+
+
+class TestUtilityFunctions:
+ """Tests for utility functions."""
+
+ def test_get_model_with_openai_config(self):
+ """Test getting model from OpenAI config."""
+ config: AiConfig = {
+ "open_ai": {"model": "gpt-4", "api_key": "test-key"}
+ }
+
+ result = get_model(config)
+
+ assert result == "gpt-4"
+
+ def test_get_model_default(self):
+ """Test getting default model when not specified."""
+ config: AiConfig = {"open_ai": {"api_key": "test-key"}}
+
+ result = get_model(config)
+
+ assert result == DEFAULT_MODEL
+
+ def test_get_model_no_openai_config(self):
+ """Test getting default model when no OpenAI config."""
+ config: AiConfig = {}
+
+ result = get_model(config)
+
+ assert result == DEFAULT_MODEL
+
+ def test_get_max_tokens_from_config(self):
+ """Test getting max tokens from config."""
+ config = cast(
+ MarimoConfig,
+ {
+ "ai": {"max_tokens": 2048},
+ },
+ )
+
+ result = get_max_tokens(config)
+
+ assert result == 2048
+
+ def test_get_max_tokens_default_no_ai_config(self):
+ """Test getting default max tokens when no AI config."""
+ config = cast(
+ MarimoConfig,
+ {
+ "completion": {"activate_on_typing": True, "copilot": False},
+ },
+ )
+
+ result = get_max_tokens(config)
+
+ assert result == DEFAULT_MAX_TOKENS
+
+ def test_get_max_tokens_default_no_max_tokens(self):
+ """Test getting default max tokens when max_tokens not specified."""
+ config = cast(
+ MarimoConfig,
+ {
+ "ai": {},
+ },
+ )
+
+ result = get_max_tokens(config)
+
+ assert result == DEFAULT_MAX_TOKENS
+
+
+class TestEdgeCases:
+ """Tests for edge cases and error conditions."""
+
+ def test_openai_config_missing(self):
+ """Test error when OpenAI config is missing."""
+ config: AiConfig = {}
+
+ with pytest.raises(HTTPException) as exc_info:
+ AnyProviderConfig.for_openai(config)
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "OpenAI config not found" in str(exc_info.value.detail)
+
+ def test_anthropic_config_missing(self):
+ """Test error when Anthropic config is missing."""
+ config: AiConfig = {}
+
+ with pytest.raises(HTTPException) as exc_info:
+ AnyProviderConfig.for_anthropic(config)
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "Anthropic config not found" in str(exc_info.value.detail)
+
+ def test_google_config_missing(self):
+ """Test error when Google config is missing."""
+ config: AiConfig = {}
+
+ with pytest.raises(HTTPException) as exc_info:
+ 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)
+
+ def test_bedrock_config_missing(self):
+ """Test error when Bedrock config is missing."""
+ 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)
+
+ def test_azure_config_missing(self):
+ """Test error when Azure config is missing."""
+ config: AiConfig = {}
+
+ with pytest.raises(HTTPException) as exc_info:
+ 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)
+
+ def test_ollama_config_missing(self):
+ """Test 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)
+
+ def test_openai_compatible_config_missing(self):
+ """Test error when OpenAI Compatible config is missing."""
+ config: AiConfig = {}
+
+ with pytest.raises(HTTPException) as exc_info:
+ AnyProviderConfig.for_openai_compatible(config)
+
+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
+ assert "OpenAI Compatible config not found" in str(
+ exc_info.value.detail
+ )
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index 3a718fa464..48ad04aaaf 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -2,14 +2,12 @@
from __future__ import annotations
import unittest
-from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional
from unittest.mock import MagicMock, Mock, patch
import pytest
-from marimo._config.manager import UserConfigManager
from marimo._dependencies.dependencies import DependencyManager
from marimo._server.ai.prompts import FILL_ME_TAG
from marimo._server.ai.providers import (
@@ -78,7 +76,11 @@ class TestOpenAiEndpoints:
del openai_mock
user_config_manager = get_session_config_manager(client)
- with no_openai_config(user_config_manager):
+ with patch.object(
+ user_config_manager,
+ "get_config",
+ return_value=_no_openai_config(),
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -108,7 +110,11 @@ class TestOpenAiEndpoints:
)
]
- with openai_config(user_config_manager):
+ with patch.object(
+ user_config_manager,
+ "get_config",
+ return_value=_openai_config(),
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -145,7 +151,11 @@ class TestOpenAiEndpoints:
)
]
- with openai_config(user_config_manager):
+ with patch.object(
+ user_config_manager,
+ "get_config",
+ return_value=_openai_config(),
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -179,7 +189,11 @@ class TestOpenAiEndpoints:
)
]
- with openai_config_custom_model(user_config_manager):
+ with patch.object(
+ user_config_manager,
+ "get_config",
+ return_value=_openai_config_custom_model(),
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -211,7 +225,11 @@ class TestOpenAiEndpoints:
)
]
- with openai_config_custom_base_url(user_config_manager):
+ with patch.object(
+ user_config_manager,
+ "get_config",
+ return_value=_openai_config_custom_base_url(),
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -244,7 +262,9 @@ class TestOpenAiEndpoints:
)
]
- with openai_config(user_config_manager):
+ with patch.object(
+ user_config_manager, "get_config", return_value=_openai_config()
+ ):
response = client.post(
"/api/ai/inline_completion",
headers=HEADERS,
@@ -278,7 +298,9 @@ class TestOpenAiEndpoints:
del openai_mock
user_config_manager = get_session_config_manager(client)
- with no_openai_config(user_config_manager):
+ with patch.object(
+ user_config_manager, "get_config", return_value=_no_openai_config()
+ ):
response = client.post(
"/api/ai/inline_completion",
headers=HEADERS,
@@ -308,7 +330,9 @@ class TestOpenAiEndpoints:
FakeChoices(choices=[Choice(delta=Delta(content="SELECT 1;"))])
]
- with openai_config(user_config_manager):
+ with patch.object(
+ user_config_manager, "get_config", return_value=_openai_config()
+ ):
response = client.post(
"/api/ai/inline_completion",
headers=HEADERS,
@@ -342,7 +366,11 @@ class TestAnthropicAiEndpoints:
del anthropic_mock
user_config_manager = get_session_config_manager(client)
- with no_anthropic_config(user_config_manager):
+ with patch.object(
+ user_config_manager,
+ "get_config",
+ return_value=_no_anthropic_config(),
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -372,7 +400,9 @@ class TestAnthropicAiEndpoints:
RawContentBlockDeltaEvent(TextDelta("import pandas as pd"))
]
- with anthropic_config(user_config_manager):
+ with patch.object(
+ user_config_manager, "get_config", return_value=_anthropic_config()
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -407,7 +437,9 @@ class TestAnthropicAiEndpoints:
RawContentBlockDeltaEvent(TextDelta("df = pd.DataFrame()"))
]
- with anthropic_config(user_config_manager):
+ with patch.object(
+ user_config_manager, "get_config", return_value=_anthropic_config()
+ ):
response = client.post(
"/api/ai/inline_completion",
headers=HEADERS,
@@ -450,7 +482,20 @@ class TestGoogleAiEndpoints:
)
]
- with google_ai_config(user_config_manager):
+ config = {
+ "ai": {
+ "open_ai": {"model": "gemini-1.5-pro"},
+ "google": {"api_key": "fake-key"},
+ },
+ "completion": {
+ "model": "gemini-1.5-pro-for-inline-completion",
+ "api_key": "fake-key",
+ },
+ }
+
+ with patch.object(
+ user_config_manager, "get_config", return_value=config
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -480,7 +525,16 @@ class TestGoogleAiEndpoints:
del google_ai_mock
user_config_manager = get_session_config_manager(client)
- with no_google_ai_config(user_config_manager):
+ config = {
+ "ai": {
+ "open_ai": {"model": "gemini-1.5-pro"},
+ "google": {"api_key": ""},
+ },
+ }
+
+ with patch.object(
+ user_config_manager, "get_config", return_value=config
+ ):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -513,7 +567,9 @@ class TestGoogleAiEndpoints:
)
]
- with google_ai_config(user_config_manager):
+ with patch.object(
+ user_config_manager, "get_config", return_value=_google_ai_config()
+ ):
response = client.post(
"/api/ai/inline_completion",
headers=HEADERS,
@@ -536,173 +592,100 @@ class TestGoogleAiEndpoints:
)
-@contextmanager
-def openai_config(config: UserConfigManager):
- prev_config = config.get_config()
- try:
- config.save_config(
- {
- "ai": {
- "open_ai": {
- "api_key": "fake-api",
- "model": "some-openai-model",
- }
- },
- "completion": {
- "model": "gpt-marimo-for-inline-completion",
- "api_key": "fake-api",
- },
- }
- )
- yield
- finally:
- config.save_config(prev_config)
-
-
-@contextmanager
-def openai_config_custom_model(config: UserConfigManager):
- prev_config = config.get_config()
- try:
- config.save_config(
- {
- "ai": {
- "open_ai": {
- "api_key": "fake-api",
- "model": "gpt-marimo",
- }
- },
- "completion": {
- "model": "gpt-marimo-for-inline-completion",
- "api_key": "fake-api",
- },
- }
- )
- yield
- finally:
- config.save_config(prev_config)
-
-
-@contextmanager
-def openai_config_custom_base_url(config: UserConfigManager):
- prev_config = config.get_config()
- try:
- config.save_config(
- {
- "ai": {
- "open_ai": {
- "api_key": "fake-api",
- "base_url": "https://my-openai-instance.com",
- "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",
- },
+def _openai_config():
+ return {
+ "ai": {
+ "open_ai": {
+ "api_key": "fake-api",
+ "model": "openai/some-openai-model",
}
- )
- yield
- finally:
- config.save_config(prev_config)
-
-
-@contextmanager
-def no_openai_config(config: UserConfigManager):
- prev_config = config.get_config()
- try:
- config.save_config(
- {
- "ai": {"open_ai": {"api_key": "", "model": ""}},
- "completion": {
- "model": "gpt-marimo-for-inline-completion",
- "api_key": "",
- },
+ },
+ "completion": {
+ "model": "gpt-marimo-for-inline-completion",
+ "api_key": "fake-api",
+ },
+ }
+
+
+def _openai_config_custom_model():
+ return {
+ "ai": {
+ "open_ai": {
+ "api_key": "fake-api",
+ "model": "gpt-marimo",
}
- )
- yield
- finally:
- config.save_config(prev_config)
-
-
-@contextmanager
-def no_anthropic_config(config: UserConfigManager):
- prev_config = config.get_config()
- try:
- config.save_config(
- {
- "ai": {
- "open_ai": {"model": "claude-3.5"},
- "anthropic": {"api_key": ""},
- },
- "completion": {
- "model": "claude-3.5-for-inline-completion",
- "api_key": "",
- },
- }
- )
- yield
- finally:
- config.save_config(prev_config)
-
-
-@contextmanager
-def anthropic_config(config: UserConfigManager):
- prev_config = config.get_config()
- try:
- config.save_config(
- {
- "ai": {
- "open_ai": {"model": "claude-3.5"},
- "anthropic": {"api_key": "fake-key"},
- },
- "completion": {
- "model": "claude-3.5-for-inline-completion",
- "api_key": "fake-key",
- },
+ },
+ "completion": {
+ "model": "gpt-marimo-for-inline-completion",
+ "api_key": "fake-api",
+ },
+ }
+
+
+def _openai_config_custom_base_url():
+ return {
+ "ai": {
+ "open_ai": {
+ "api_key": "fake-api",
+ "base_url": "https://my-openai-instance.com",
+ "model": "openai/some-openai-model-with-base-url",
}
- )
- yield
- finally:
- config.save_config(prev_config)
-
-
-@contextmanager
-def google_ai_config(config: UserConfigManager):
- prev_config = config.get_config()
- try:
- config.save_config(
- {
- "ai": {
- "open_ai": {"model": "gemini-1.5-pro"},
- "google": {"api_key": "fake-key"},
- },
- "completion": {
- "model": "gemini-1.5-pro-for-inline-completion",
- "api_key": "fake-key",
- },
- }
- )
- yield
- finally:
- config.save_config(prev_config)
-
-
-@contextmanager
-def no_google_ai_config(config: UserConfigManager):
- prev_config = config.get_config()
- try:
- config.save_config(
- {
- "ai": {
- "open_ai": {"model": "gemini-1.5-pro"},
- "google": {"api_key": ""},
- },
- }
- )
- yield
- finally:
- config.save_config(prev_config)
+ },
+ "completion": {
+ "model": "gpt-marimo-for-inline-completion",
+ "api_key": "fake-api",
+ "base_url": "https://my-openai-instance.com",
+ },
+ }
+
+
+def _no_openai_config():
+ return {
+ "ai": {"open_ai": {"api_key": "", "model": ""}},
+ "completion": {
+ "model": "gpt-marimo-for-inline-completion",
+ "api_key": "",
+ },
+ }
+
+
+def _no_anthropic_config():
+ return {
+ "ai": {
+ "open_ai": {"model": "claude-3.5"},
+ "anthropic": {"api_key": ""},
+ },
+ "completion": {
+ "model": "claude-3.5-for-inline-completion",
+ "api_key": "",
+ },
+ }
+
+
+def _anthropic_config():
+ return {
+ "ai": {
+ "open_ai": {"model": "claude-3.5"},
+ "anthropic": {"api_key": "fake-key"},
+ },
+ "completion": {
+ "model": "claude-3.5-for-inline-completion",
+ "api_key": "fake-key",
+ },
+ }
+
+
+def _google_ai_config():
+ return {
+ "ai": {
+ "open_ai": {"model": "gemini-1.5-pro"},
+ "google": {"api_key": "fake-key"},
+ },
+ "completion": {
+ "model": "gemini-1.5-pro-for-inline-completion",
+ "api_key": "fake-key",
+ },
+ }
@with_session(SESSION_ID)
@@ -721,7 +704,9 @@ def test_chat_without_code(client: TestClient) -> None:
)
]
- with openai_config(user_config_manager):
+ with patch.object(
+ user_config_manager, "get_config", return_value=_openai_config()
+ ):
response = client.post(
"/api/ai/chat",
headers=HEADERS,
@@ -756,7 +741,9 @@ def test_chat_with_code(client: TestClient) -> None:
)
]
- with openai_config(user_config_manager):
+ with patch.object(
+ user_config_manager, "get_config", return_value=_openai_config()
+ ):
response = client.post(
"/api/ai/chat",
headers=HEADERS,