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.

smartly set chat & edit models based on ai config (#7901)

Shahmir Varqhab96df0088112
diff --git a/frontend/src/components/ai/__tests__/ai-utils.test.ts b/frontend/src/components/ai/__tests__/ai-utils.test.ts
new file mode 100644
index 0000000000..de16b70604
--- /dev/null
+++ b/frontend/src/components/ai/__tests__/ai-utils.test.ts
@@ -0,0 +1,276 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { AiModel } from "@marimo-team/llm-info";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { UserConfig } from "@/core/config/config-schema";
+
+// Mock the models.json import
+vi.mock("@marimo-team/llm-info/models.json", () => {
+ const models: AiModel[] = [
+ {
+ name: "GPT-4",
+ model: "gpt-4",
+ description: "OpenAI GPT-4 model",
+ providers: ["openai"],
+ roles: ["chat", "edit"],
+ thinking: false,
+ },
+ {
+ name: "Claude 3",
+ model: "claude-3-sonnet",
+ description: "Anthropic Claude 3 Sonnet",
+ providers: ["anthropic"],
+ roles: ["chat", "edit"],
+ thinking: false,
+ },
+ {
+ name: "Gemini Pro",
+ model: "gemini-pro",
+ description: "Google Gemini Pro model",
+ providers: ["google"],
+ roles: ["chat", "edit"],
+ thinking: false,
+ },
+ {
+ name: "Ollama Model",
+ model: "llama2",
+ description: "Ollama Llama 2 model",
+ providers: ["ollama"],
+ roles: ["chat", "edit"],
+ thinking: false,
+ },
+ ];
+
+ return {
+ models: models,
+ };
+});
+
+// Must import after mock
+import {
+ autoPopulateModels,
+ getConfiguredProvider,
+ getRecommendedModel,
+} from "../ai-utils";
+
+describe("ai-utils", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("getConfiguredProvider", () => {
+ it("should return undefined when no AI config", () => {
+ const config: UserConfig = {} as UserConfig;
+ expect(getConfiguredProvider(config)).toBeUndefined();
+ });
+
+ it("should return undefined when AI config has no credentials", () => {
+ const config: UserConfig = {
+ ai: {},
+ } as UserConfig;
+ expect(getConfiguredProvider(config)).toBeUndefined();
+ });
+
+ it("should return openai when OpenAI API key is set", () => {
+ const config: UserConfig = {
+ ai: {
+ open_ai: { api_key: "sk-test" },
+ },
+ } as UserConfig;
+ expect(getConfiguredProvider(config)).toBe("openai");
+ });
+
+ it("should return anthropic when Anthropic API key is set", () => {
+ const config: UserConfig = {
+ ai: {
+ anthropic: { api_key: "sk-ant-test" },
+ },
+ } as UserConfig;
+ expect(getConfiguredProvider(config)).toBe("anthropic");
+ });
+
+ it("should return google when Google API key is set", () => {
+ const config: UserConfig = {
+ ai: {
+ google: { api_key: "google-key" },
+ },
+ } as UserConfig;
+ expect(getConfiguredProvider(config)).toBe("google");
+ });
+
+ it("should return ollama when Ollama base URL is set", () => {
+ const config: UserConfig = {
+ ai: {
+ ollama: { base_url: "http://localhost:11434" },
+ },
+ } as UserConfig;
+ expect(getConfiguredProvider(config)).toBe("ollama");
+ });
+
+ it("should return azure only when both API key and base URL are set", () => {
+ const config: UserConfig = {
+ ai: {
+ azure: { api_key: "azure-key", base_url: "https://azure.com" },
+ },
+ } as UserConfig;
+ expect(getConfiguredProvider(config)).toBe("azure");
+ });
+
+ it("should return undefined for azure with only API key", () => {
+ const config: UserConfig = {
+ ai: {
+ azure: { api_key: "azure-key" },
+ },
+ } as UserConfig;
+ expect(getConfiguredProvider(config)).toBeUndefined();
+ });
+
+ it("should return custom provider when configured", () => {
+ const config = {
+ ai: {
+ custom_providers: {
+ my_provider: { base_url: "https://my-api.com" },
+ },
+ },
+ } as unknown as UserConfig;
+ expect(getConfiguredProvider(config)).toBe("my_provider");
+ });
+ });
+
+ describe("getRecommendedModel", () => {
+ it("should return undefined when no provider is configured", () => {
+ const config: UserConfig = {} as UserConfig;
+ expect(getRecommendedModel(config)).toBeUndefined();
+ });
+
+ it("should return openai model when OpenAI is configured", () => {
+ const config: UserConfig = {
+ ai: {
+ open_ai: { api_key: "sk-test" },
+ },
+ } as UserConfig;
+ expect(getRecommendedModel(config)).toBe("openai/gpt-4");
+ });
+
+ it("should return anthropic model when Anthropic is configured", () => {
+ const config: UserConfig = {
+ ai: {
+ anthropic: { api_key: "sk-ant-test" },
+ },
+ } as UserConfig;
+ expect(getRecommendedModel(config)).toBe("anthropic/claude-3-sonnet");
+ });
+
+ it("should return google model when Google is configured", () => {
+ const config: UserConfig = {
+ ai: {
+ google: { api_key: "google-key" },
+ },
+ } as UserConfig;
+ expect(getRecommendedModel(config)).toBe("google/gemini-pro");
+ });
+
+ it("should return ollama model when Ollama is configured", () => {
+ const config: UserConfig = {
+ ai: {
+ ollama: { base_url: "http://localhost:11434" },
+ },
+ } as UserConfig;
+ expect(getRecommendedModel(config)).toBe("ollama/llama2");
+ });
+ });
+
+ describe("autoPopulateModels", () => {
+ it("should return empty result when both models are already set", () => {
+ const values = {
+ ai: {
+ open_ai: { api_key: "sk-test" },
+ models: {
+ chat_model: "openai/gpt-4",
+ edit_model: "openai/gpt-4",
+ custom_models: [],
+ displayed_models: [],
+ },
+ },
+ } as unknown as UserConfig;
+
+ const result = autoPopulateModels(values);
+
+ expect(result.chatModel).toBeUndefined();
+ expect(result.editModel).toBeUndefined();
+ });
+
+ it("should return empty result when no credentials are configured", () => {
+ const values: UserConfig = {
+ ai: {},
+ } as UserConfig;
+
+ const result = autoPopulateModels(values);
+
+ expect(result.chatModel).toBeUndefined();
+ expect(result.editModel).toBeUndefined();
+ });
+
+ it("should auto-populate both models when neither is set", () => {
+ const values: UserConfig = {
+ ai: {
+ open_ai: { api_key: "sk-test" },
+ },
+ } as UserConfig;
+
+ const result = autoPopulateModels(values);
+
+ expect(result.chatModel).toBe("openai/gpt-4");
+ expect(result.editModel).toBe("openai/gpt-4");
+ });
+
+ it("should only auto-populate chat_model when edit_model is set", () => {
+ const values = {
+ ai: {
+ open_ai: { api_key: "sk-test" },
+ models: {
+ edit_model: "openai/gpt-3.5-turbo",
+ custom_models: [],
+ displayed_models: [],
+ },
+ },
+ } as unknown as UserConfig;
+
+ const result = autoPopulateModels(values);
+
+ expect(result.chatModel).toBe("openai/gpt-4");
+ expect(result.editModel).toBeUndefined();
+ });
+
+ it("should only auto-populate edit_model when chat_model is set", () => {
+ const values = {
+ ai: {
+ open_ai: { api_key: "sk-test" },
+ models: {
+ chat_model: "openai/gpt-3.5-turbo",
+ custom_models: [],
+ displayed_models: [],
+ },
+ },
+ } as unknown as UserConfig;
+
+ const result = autoPopulateModels(values);
+
+ expect(result.chatModel).toBeUndefined();
+ expect(result.editModel).toBe("openai/gpt-4");
+ });
+
+ it("should return recommended model for anthropic provider", () => {
+ const values: UserConfig = {
+ ai: {
+ anthropic: { api_key: "sk-ant-test" },
+ },
+ } as UserConfig;
+
+ const result = autoPopulateModels(values);
+
+ expect(result.chatModel).toBe("anthropic/claude-3-sonnet");
+ expect(result.editModel).toBe("anthropic/claude-3-sonnet");
+ });
+ });
+});
diff --git a/frontend/src/components/ai/ai-utils.ts b/frontend/src/components/ai/ai-utils.ts
new file mode 100644
index 0000000000..becd0eb243
--- /dev/null
+++ b/frontend/src/components/ai/ai-utils.ts
@@ -0,0 +1,101 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import {
+ KNOWN_PROVIDERS,
+ type KnownProviderId,
+ type ProviderId,
+} from "@/core/ai/ids/ids";
+import { getKnownModelMaps } from "@/core/ai/model-registry";
+import type { AiConfig, UserConfig } from "@/core/config/config-schema";
+
+type CredentialChecker = (ai: AiConfig | undefined) => boolean;
+
+/**
+ * Credential checkers for each known provider.
+ */
+const CREDENTIAL_CHECKERS: Record<KnownProviderId, CredentialChecker> = {
+ openai: (ai) => Boolean(ai?.open_ai?.api_key),
+ anthropic: (ai) => Boolean(ai?.anthropic?.api_key),
+ google: (ai) => Boolean(ai?.google?.api_key),
+ github: (ai) => Boolean(ai?.github?.api_key),
+ openrouter: (ai) => Boolean(ai?.openrouter?.api_key),
+ azure: (ai) => Boolean(ai?.azure?.api_key && ai?.azure?.base_url),
+ wandb: (ai) => Boolean(ai?.wandb?.api_key),
+ bedrock: (ai) => Boolean(ai?.bedrock?.region_name),
+ ollama: (ai) => Boolean(ai?.ollama?.base_url),
+ // These providers don't have user-configurable credentials in the UI
+ deepseek: () => false,
+ marimo: () => false,
+};
+
+/**
+ * Returns the first configured provider based on credentials.
+ */
+export function getConfiguredProvider(
+ config: UserConfig,
+): ProviderId | undefined {
+ const ai = config.ai;
+
+ for (const provider of KNOWN_PROVIDERS) {
+ if (CREDENTIAL_CHECKERS[provider](ai)) {
+ return provider;
+ }
+ }
+
+ // Check custom providers
+ const customProviders = ai?.custom_providers;
+ if (customProviders) {
+ const firstCustomProvider = Object.entries(customProviders).find(
+ ([_, providerConfig]) => providerConfig?.base_url,
+ );
+ if (firstCustomProvider) {
+ return firstCustomProvider[0];
+ }
+ }
+}
+
+export function getRecommendedModel(config: UserConfig): string | undefined {
+ const provider = getConfiguredProvider(config);
+ if (!provider) {
+ return undefined;
+ }
+ return getKnownModelMaps().defaultModelByProvider.get(provider);
+}
+
+export interface AutoPopulateResult {
+ chatModel: string | undefined;
+ editModel: string | undefined;
+}
+
+/**
+ * Determines which models to auto-populate based on configured credentials.
+ * Returns the recommended model for chat/edit if credentials are configured but models aren't set.
+ *
+ * @param values - The full form values
+ */
+export function autoPopulateModels(values: UserConfig): AutoPopulateResult {
+ const result: AutoPopulateResult = {
+ chatModel: undefined,
+ editModel: undefined,
+ };
+
+ const needsChatModel = !values.ai?.models?.chat_model;
+ const needsEditModel = !values.ai?.models?.edit_model;
+
+ if (!needsChatModel && !needsEditModel) {
+ return result;
+ }
+
+ const recommendedModel = getRecommendedModel(values);
+ if (!recommendedModel) {
+ return result;
+ }
+
+ if (needsChatModel) {
+ result.chatModel = recommendedModel;
+ }
+ if (needsEditModel) {
+ result.editModel = recommendedModel;
+ }
+ return result;
+}
diff --git a/frontend/src/components/app-config/ai-config.tsx b/frontend/src/components/app-config/ai-config.tsx
index dd6dacc4a1..cbd94deb47 100644
--- a/frontend/src/components/app-config/ai-config.tsx
+++ b/frontend/src/components/app-config/ai-config.tsx
@@ -115,6 +115,7 @@ interface ApiKeyProps {
placeholder: string;
testId: string;
description?: React.ReactNode;
+ onChange?: (value: string) => void;
}
export const ApiKey: React.FC<ApiKeyProps> = ({
@@ -124,6 +125,7 @@ export const ApiKey: React.FC<ApiKeyProps> = ({
placeholder,
testId,
description,
+ onChange,
}) => {
return (
<FormField
@@ -141,11 +143,12 @@ export const ApiKey: React.FC<ApiKeyProps> = ({
placeholder={placeholder}
type="password"
{...field}
- value={asStringOrUndefined(field.value)}
+ value={asStringOrEmpty(field.value)}
onChange={(e) => {
const value = e.target.value;
if (!value.includes("*")) {
field.onChange(value);
+ onChange?.(value);
}
}}
/>
@@ -168,12 +171,12 @@ interface BaseUrlProps {
testId: string;
description?: React.ReactNode;
disabled?: boolean;
- defaultValue?: string;
+ onChange?: (value: string) => void;
}
-function asStringOrUndefined<T>(value: T): string | undefined {
+function asStringOrEmpty<T>(value: T): string {
if (value == null) {
- return undefined;
+ return "";
}
if (typeof value === "string") {
@@ -191,13 +194,12 @@ export const BaseUrl: React.FC<BaseUrlProps> = ({
testId,
description,
disabled = false,
- defaultValue,
+ onChange,
}) => {
return (
<FormField
control={form.control}
name={name}
- disabled={disabled}
render={({ field }) => (
<div className="flex flex-col space-y-1">
<FormItem className={formItemClasses}>
@@ -208,9 +210,13 @@ export const BaseUrl: React.FC<BaseUrlProps> = ({
rootClassName="flex-1"
className="m-0 inline-flex h-7"
placeholder={placeholder}
- defaultValue={defaultValue}
{...field}
- value={asStringOrUndefined(field.value)}
+ value={asStringOrEmpty(field.value)}
+ disabled={disabled}
+ onChange={(e) => {
+ field.onChange(e.target.value);
+ onChange?.(e.target.value);
+ }}
/>
</FormControl>
<FormMessage />
@@ -252,9 +258,8 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
<FormField
control={form.control}
name={name}
- disabled={disabled}
render={({ field }) => {
- const value = asStringOrUndefined(field.value);
+ const value = asStringOrEmpty(field.value);
const selectModel = (modelId: QualifiedModelId) => {
field.onChange(modelId);
@@ -286,7 +291,8 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
className="w-full border-border shadow-none focus-visible:shadow-xs"
placeholder={placeholder}
{...field}
- value={asStringOrUndefined(field.value)}
+ value={asStringOrEmpty(field.value)}
+ disabled={disabled}
onKeyDown={Events.stopPropagation()}
/>
{value && (
@@ -339,7 +345,6 @@ export const ProviderSelect: React.FC<ProviderSelectProps> = ({
<FormField
control={form.control}
name={name}
- disabled={disabled}
render={({ field }) => (
<div className="flex flex-col space-y-1">
<FormItem className={formItemClasses}>
@@ -354,14 +359,14 @@ export const ProviderSelect: React.FC<ProviderSelectProps> = ({
field.onChange(e.target.value);
}
}}
- value={asStringOrUndefined(
+ value={asStringOrEmpty(
field.value === true
? "github"
: field.value === false
? "none"
: field.value,
)}
- disabled={field.disabled}
+ disabled={disabled}
className="inline-flex mr-2"
>
{options.map((option) => (
@@ -715,6 +720,22 @@ export const CustomProvidersConfig: React.FC<AiConfigProps> = ({
</div>
);
+ // Update a provider field by updating the entire custom_providers object.
+ // As this config will be replaced, it needs to be sent in its entirety.
+ const updateProviderField = (opts: {
+ providerName: string;
+ fieldName: keyof CustomProviderConfig;
+ value: string;
+ }) => {
+ field.onChange({
+ ...customProviders,
+ [opts.providerName]: {
+ ...customProviders[opts.providerName],
+ [opts.fieldName]: opts.value || undefined,
+ },
+ });
+ };
+
const renderAccordionItem = ({
providerName,
providerConfig,
@@ -744,6 +765,13 @@ export const CustomProvidersConfig: React.FC<AiConfigProps> = ({
}
placeholder="sk-..."
testId={`custom-provider-${providerName}-api-key`}
+ onChange={(value) =>
+ updateProviderField({
+ providerName,
+ fieldName: "api_key",
+ value,
+ })
+ }
/>
<BaseUrl
form={form}
@@ -753,6 +781,13 @@ export const CustomProvidersConfig: React.FC<AiConfigProps> = ({
}
placeholder="https://api.example.com/v1"
testId={`custom-provider-${providerName}-base-url`}
+ onChange={(value) =>
+ updateProviderField({
+ providerName,
+ fieldName: "base_url",
+ value,
+ })
+ }
/>
<Button
variant="destructive"
@@ -918,7 +953,6 @@ export const AiProvidersConfig: React.FC<AiConfigProps> = ({
config={config}
name="ai.ollama.base_url"
placeholder="http://localhost:11434/v1"
- defaultValue="http://localhost:11434/v1"
testId="ollama-base-url-input"
/>
</AccordionFormItem>
@@ -1038,7 +1072,6 @@ export const AiProvidersConfig: React.FC<AiConfigProps> = ({
config={config}
name="ai.azure.base_url"
placeholder="https://<your-resource-name>.openai.azure.com/openai/deployments/<deployment-name>?api-version=<api-version>"
- defaultValue="https://<your-resource-name>.openai.azure.com/openai/deployments/<deployment-name>?api-version=<api-version>"
testId="ai-azure-base-url-input"
/>
</AccordionFormItem>
@@ -1427,6 +1460,13 @@ export const AiModelDisplayConfig: React.FC<AiConfigProps> = ({
const deleteModel = useEvent((modelId: QualifiedModelId) => {
const newModels = customModels.filter((id) => id !== modelId);
+ // Remove from displayed models if it's in there
+ const newDisplayedModels = currentDisplayedModels.filter(
+ (id) => id !== modelId,
+ );
+ form.setValue("ai.models.displayed_models", newDisplayedModels, {
+ shouldDirty: true,
+ });
form.setValue("ai.models.custom_models", newModels, {
shouldDirty: true,
});
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 83c5ec12d2..cf615b028e 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -50,6 +50,7 @@ import { Banner } from "@/plugins/impl/common/error-banner";
import { THEMES } from "@/theme/useTheme";
import { arrayToggle } from "@/utils/arrays";
import { cn } from "@/utils/cn";
+import { autoPopulateModels } from "../ai/ai-utils";
import { keyboardShortcutsAtom } from "../editor/controls/keyboard-shortcuts";
import { Badge } from "../ui/badge";
import { ExternalLink } from "../ui/links";
@@ -180,6 +181,28 @@ export const UserConfigForm: React.FC = () => {
defaultValues: config,
});
+ const setAiModels = (values: UserConfig, dirtyAiConfig: UserConfig["ai"]) => {
+ const { chatModel, editModel } = autoPopulateModels(values);
+ if (chatModel || editModel) {
+ dirtyAiConfig = {
+ ...dirtyAiConfig,
+ models: {
+ ...dirtyAiConfig?.models,
+ ...(chatModel && { chat_model: chatModel }),
+ ...(editModel && { edit_model: editModel }),
+ },
+ } as typeof dirtyAiConfig;
+ if (chatModel) {
+ form.setValue("ai.models.chat_model", chatModel);
+ }
+ if (editModel) {
+ form.setValue("ai.models.edit_model", editModel);
+ }
+ }
+
+ return dirtyAiConfig;
+ };
+
const onSubmitNotDebounced = async (values: UserConfig) => {
// Only send values that were actually changed to avoid
// overwriting backend values the form doesn't manage
@@ -187,6 +210,12 @@ export const UserConfigForm: React.FC = () => {
if (Object.keys(dirtyValues).length === 0) {
return; // Nothing changed
}
+
+ // Auto-populate AI models when credentials are set, makes it easier to get started
+ if (dirtyValues.ai) {
+ dirtyValues.ai = setAiModels(values, dirtyValues.ai);
+ }
+
await saveUserConfig({ config: dirtyValues }).then(() => {
// Update local state with form values
setConfig((prev) => ({ ...prev, ...values }));
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index bb77b43a8d..6abb75421b 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -426,14 +426,14 @@ const ChatInput: React.FC<ChatInputProps> = memo(
ChatInput.displayName = "ChatInput";
const ChatPanel = () => {
- const aiEnabled = useAtomValue(aiEnabledAtom);
+ const aiConfigured = useAtomValue(aiEnabledAtom);
const { handleClick } = useOpenSettingsToTab();
- if (!aiEnabled) {
+ if (!aiConfigured) {
return (
<PanelEmptyState
title="Chat with AI"
- description="AI is currently disabled. Add your API key to enable."
+ description="No AI provider configured or model selected"
action={
<Button variant="outline" size="sm" onClick={() => handleClick("ai")}>
Edit AI settings
diff --git a/frontend/src/core/ai/model-registry.ts b/frontend/src/core/ai/model-registry.ts
index d38062dd1a..d1c57f2887 100644
--- a/frontend/src/core/ai/model-registry.ts
+++ b/frontend/src/core/ai/model-registry.ts
@@ -21,8 +21,17 @@ export interface AiModel extends AiModelType {
custom: boolean;
}
-const getKnownModelMap = once((): ReadonlyMap<QualifiedModelId, AiModel> => {
+interface KnownModelMaps {
+ /** Map of qualified model ID to model info */
+ modelMap: ReadonlyMap<QualifiedModelId, AiModel>;
+ /** Map of provider ID to first default model (supports chat or edit) */
+ defaultModelByProvider: ReadonlyMap<ProviderId, QualifiedModelId>;
+}
+
+export const getKnownModelMaps = once((): KnownModelMaps => {
const modelMap = new Map<QualifiedModelId, AiModel>();
+ const defaultModelByProvider = new Map<ProviderId, QualifiedModelId>();
+
for (const model of models) {
const modelId = model.model as ShortModelId;
const modelInfo: AiModel = {
@@ -33,12 +42,21 @@ const getKnownModelMap = once((): ReadonlyMap<QualifiedModelId, AiModel> => {
custom: false,
};
+ const supportsChatOrEdit =
+ modelInfo.roles.includes("chat") || modelInfo.roles.includes("edit");
+
for (const provider of modelInfo.providers) {
const qualifiedModelId: QualifiedModelId = `${provider}/${modelId}`;
modelMap.set(qualifiedModelId, modelInfo);
+
+ // Track first model per provider that supports chat or edit
+ if (supportsChatOrEdit && !defaultModelByProvider.has(provider)) {
+ defaultModelByProvider.set(provider, qualifiedModelId);
+ }
}
}
- return modelMap;
+
+ return { modelMap, defaultModelByProvider };
});
const getProviderMap = once(
@@ -125,7 +143,7 @@ export class AiModelRegistry {
}) {
const { displayedModels, customModels } = opts;
const hasDisplayedModels = displayedModels.size > 0;
- const knownModelMap = getKnownModelMap();
+ const knownModelMap = getKnownModelMaps().modelMap;
const customModelsMap = new Map<QualifiedModelId, AiModel>();
let modelsMap = new Map<QualifiedModelId, AiModel>();
diff --git a/marimo/_utils/deep_merge.py b/marimo/_utils/deep_merge.py
index e90380a7ec..8e0d4fd52a 100644
--- a/marimo/_utils/deep_merge.py
+++ b/marimo/_utils/deep_merge.py
@@ -21,7 +21,12 @@ def _merge_key(
# new keys in update get added to original
return update[key]
elif path in replace_paths:
- # This path should be replaced, not merged
+ # Use merge-replace behavior:
+ # - Keys come from UPDATE only (so deletions work)
+ # - But each key's value is merged with original (so partial updates
+ # preserve unmodified fields like api_key)
+ if isinstance(original[key], dict) and isinstance(update[key], dict):
+ return _merge_replace(original[key], update[key])
return update[key]
elif isinstance(original[key], dict) and isinstance(update[key], dict):
# both dicts, so recurse
@@ -34,6 +39,29 @@ def _merge_key(
return update[key]
+def _merge_replace(
+ original: dict[Any, Any], update: dict[Any, Any]
+) -> dict[Any, Any]:
+ """Merge-replace: keys from update, but merge each value with original.
+
+ This handles record-type dicts like custom_providers where:
+ - Deleting a record works (key not in update = deleted)
+ - Editing a record preserves unmodified fields (values are merged)
+ """
+ result = {}
+ for key in update:
+ if (
+ key in original
+ and isinstance(original[key], dict)
+ and isinstance(update[key], dict)
+ ):
+ # Merge the record's fields (original first, update overwrites)
+ result[key] = {**original[key], **update[key]}
+ else:
+ result[key] = update[key]
+ return result
+
+
def deep_merge(
original: dict[Any, Any],
update: dict[Any, Any],
@@ -45,11 +73,12 @@ def deep_merge(
Args:
original: The original dict.
update: The dict to merge into the original.
- replace_paths: Optional set of dot-separated paths that should be
- replaced instead of merged. For example, {"ai.custom_providers"}
- means that if both original and update have ai.custom_providers,
- the update value will completely replace the original instead of
- being deep merged.
+ replace_paths: Optional set of dot-separated paths that use
+ merge-replace behavior. For these paths:
+ - Keys come from update only (so deletions work)
+ - Each key's value is merged with original (so partial updates
+ preserve unmodified fields like masked api_key)
+ Example: {"ai.custom_providers"}
current_path: Internal parameter for tracking the current path during
recursion.
diff --git a/tests/_config/test_config.py b/tests/_config/test_config.py
index 4e515238be..0c8974c4e5 100644
--- a/tests/_config/test_config.py
+++ b/tests/_config/test_config.py
@@ -232,7 +232,7 @@ def test_merge_config_custom_providers_replaces_instead_of_merging() -> None:
new_custom_providers = new_config.get("ai", {}).get("custom_providers", {})
assert "provider1" in new_custom_providers
assert "provider2" not in new_custom_providers
- assert new_custom_providers["provider1"]["api_key"] == "key1_updated"
+ assert new_custom_providers["provider1"].get("api_key") == "key1_updated"
def test_merge_config_custom_providers_can_be_emptied() -> None:
@@ -306,3 +306,191 @@ def test_merge_config_custom_providers_preserves_other_ai_settings() -> None:
custom_providers = new_config.get("ai", {}).get("custom_providers", {})
assert "provider1" not in custom_providers
assert "provider2" in custom_providers
+
+
+def test_merge_config_custom_providers_partial_update_preserves_fields() -> (
+ None
+):
+ """Test that updating one field of a provider preserves other fields.
+
+ This validates the merge-replace behavior: when updating only base_url,
+ the api_key should be preserved (not lost due to replacement).
+ """
+ prev_config = merge_default_config(
+ PartialMarimoConfig(
+ ai={
+ "custom_providers": {
+ "provider1": {
+ "api_key": "secret_key",
+ "base_url": "https://old.example.com",
+ },
+ },
+ },
+ )
+ )
+
+ # Update only base_url (simulates getDirtyValues sending partial update)
+ new_config = merge_config(
+ prev_config,
+ PartialMarimoConfig(
+ ai={
+ "custom_providers": {
+ "provider1": {
+ "base_url": "https://new.example.com",
+ },
+ },
+ },
+ ),
+ )
+
+ # api_key should be preserved, base_url should be updated
+ provider1 = (
+ new_config.get("ai", {})
+ .get("custom_providers", {})
+ .get("provider1", {})
+ )
+ assert provider1.get("api_key") == "secret_key", (
+ "api_key should be preserved"
+ )
+ assert provider1.get("base_url") == "https://new.example.com", (
+ "base_url should be updated"
+ )
+
+
+def test_merge_config_custom_providers_partial_update_api_key_preserves_base_url() -> (
+ None
+):
+ """Test that updating api_key preserves base_url (inverse of above test)."""
+ prev_config = merge_default_config(
+ PartialMarimoConfig(
+ ai={
+ "custom_providers": {
+ "provider1": {
+ "api_key": "old_key",
+ "base_url": "https://api.example.com",
+ },
+ },
+ },
+ )
+ )
+
+ # Update only api_key
+ new_config = merge_config(
+ prev_config,
+ PartialMarimoConfig(
+ ai={
+ "custom_providers": {
+ "provider1": {
+ "api_key": "new_key",
+ },
+ },
+ },
+ ),
+ )
+
+ provider1 = (
+ new_config.get("ai", {})
+ .get("custom_providers", {})
+ .get("provider1", {})
+ )
+ assert provider1.get("api_key") == "new_key", "api_key should be updated"
+ assert provider1.get("base_url") == "https://api.example.com", (
+ "base_url should be preserved"
+ )
+
+
+def test_merge_config_custom_providers_add_new_keeps_existing() -> None:
+ """Test that adding a new provider preserves existing providers."""
+ prev_config = merge_default_config(
+ PartialMarimoConfig(
+ ai={
+ "custom_providers": {
+ "provider1": {
+ "api_key": "key1",
+ "base_url": "https://api1.example.com",
+ },
+ },
+ },
+ )
+ )
+
+ # Add provider2 while keeping provider1
+ new_config = merge_config(
+ prev_config,
+ PartialMarimoConfig(
+ ai={
+ "custom_providers": {
+ "provider1": {
+ "api_key": "key1",
+ "base_url": "https://api1.example.com",
+ },
+ "provider2": {
+ "api_key": "key2",
+ "base_url": "https://api2.example.com",
+ },
+ },
+ },
+ ),
+ )
+
+ custom_providers = new_config.get("ai", {}).get("custom_providers", {})
+ assert "provider1" in custom_providers, "provider1 should still exist"
+ assert "provider2" in custom_providers, "provider2 should be added"
+ assert custom_providers["provider1"].get("api_key") == "key1"
+ assert custom_providers["provider2"].get("api_key") == "key2"
+
+
+def test_merge_config_custom_providers_update_one_preserves_others() -> None:
+ """Test that updating one provider doesn't affect other providers."""
+ prev_config = merge_default_config(
+ PartialMarimoConfig(
+ ai={
+ "custom_providers": {
+ "provider1": {
+ "api_key": "key1",
+ "base_url": "https://api1.example.com",
+ },
+ "provider2": {
+ "api_key": "key2",
+ "base_url": "https://api2.example.com",
+ },
+ },
+ },
+ )
+ )
+
+ # Update only provider1's base_url, provider2 included unchanged
+ new_config = merge_config(
+ prev_config,
+ PartialMarimoConfig(
+ ai={
+ "custom_providers": {
+ "provider1": {
+ "base_url": "https://new-api1.example.com",
+ },
+ "provider2": {
+ "api_key": "key2",
+ "base_url": "https://api2.example.com",
+ },
+ },
+ },
+ ),
+ )
+
+ custom_providers = new_config.get("ai", {}).get("custom_providers", {})
+
+ # provider1 should have updated base_url but preserved api_key
+ assert custom_providers["provider1"].get("api_key") == "key1", (
+ "provider1 api_key should be preserved"
+ )
+ assert custom_providers["provider1"].get("base_url") == (
+ "https://new-api1.example.com"
+ ), "provider1 base_url should be updated"
+
+ # provider2 should be completely unchanged
+ assert custom_providers["provider2"].get("api_key") == "key2", (
+ "provider2 should be unchanged"
+ )
+ assert custom_providers["provider2"].get("base_url") == (
+ "https://api2.example.com"
+ ), "provider2 should be unchanged"
diff --git a/tests/_utils/test_deep_merge.py b/tests/_utils/test_deep_merge.py
index 46c6317b2f..df2dbd02be 100644
--- a/tests/_utils/test_deep_merge.py
+++ b/tests/_utils/test_deep_merge.py
@@ -66,8 +66,8 @@ def test_deep_merge_nested_dicts() -> None:
}
-def test_deep_merge_replace_paths_replaces_instead_of_merging() -> None:
- """Test that paths in replace_paths are replaced, not merged."""
+def test_deep_merge_replace_paths_deletes_missing_keys() -> None:
+ """Test that replace_paths deletes keys not in update."""
original = {
"ai": {
"custom_providers": {
@@ -99,6 +99,45 @@ def test_deep_merge_replace_paths_replaces_instead_of_merging() -> None:
}
+def test_deep_merge_replace_paths_preserves_unmodified_fields() -> None:
+ """Test that replace_paths preserves fields not in update.
+
+ This is the key use case: editing base_url should preserve api_key
+ (which is filtered out as masked placeholder).
+ """
+ original = {
+ "ai": {
+ "custom_providers": {
+ "provider1": {"api_key": "secret", "base_url": "old_url"},
+ "provider2": {"api_key": "key2", "base_url": "url2"},
+ }
+ }
+ }
+ # Frontend sends all providers, but api_key filtered as placeholder
+ update = {
+ "ai": {
+ "custom_providers": {
+ "provider1": {"base_url": "new_url"}, # api_key missing
+ "provider2": {"api_key": "key2", "base_url": "url2"},
+ }
+ }
+ }
+
+ result = deep_merge(
+ original, update, replace_paths=frozenset({"ai.custom_providers"})
+ )
+
+ # api_key should be preserved from original
+ assert result["ai"]["custom_providers"]["provider1"] == {
+ "api_key": "secret",
+ "base_url": "new_url",
+ }
+ assert result["ai"]["custom_providers"]["provider2"] == {
+ "api_key": "key2",
+ "base_url": "url2",
+ }
+
+
def test_deep_merge_replace_paths_with_empty_dict() -> None:
"""Test that replace_paths works when update has empty dict."""
original = {