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.

update dropdown for model select (#6029)

Shahmir Varqhabb8c1917f461
diff --git a/frontend/src/components/ai/ai-model-dropdown.tsx b/frontend/src/components/ai/ai-model-dropdown.tsx
new file mode 100644
index 0000000000..f87e57f068
--- /dev/null
+++ b/frontend/src/components/ai/ai-model-dropdown.tsx
@@ -0,0 +1,288 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { Role } from "@marimo-team/llm-info";
+import { capitalize } from "lodash-es";
+import { ChevronDownIcon, CircleHelpIcon } from "lucide-react";
+import {
+ AiModelId,
+ isKnownAIProvider,
+ type ProviderId,
+ type QualifiedModelId,
+} from "@/core/ai/ids/ids";
+import { type AiModel, AiModelRegistry } from "@/core/ai/model-registry";
+import { useResolvedMarimoConfig } from "@/core/config/config";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "../ui/dropdown-menu";
+import { AiProviderIcon } from "./ai-provider-icon";
+
+interface AIModelDropdownProps {
+ value?: string;
+ placeholder?: string;
+ onSelect: (modelId: QualifiedModelId) => void;
+ triggerClassName?: string;
+ customDropdownContent?: React.ReactNode;
+ iconSize?: "medium" | "small";
+ showAddCustomModelDocs?: boolean;
+ forRole?: Role;
+}
+
+export const AIModelDropdown = ({
+ value,
+ placeholder,
+ onSelect,
+ triggerClassName,
+ customDropdownContent,
+ iconSize = "medium",
+ showAddCustomModelDocs = false,
+ forRole,
+}: AIModelDropdownProps) => {
+ const currentValue = value ? AiModelId.parse(value) : undefined;
+
+ const selectModel = (modelId: QualifiedModelId) => {
+ onSelect(modelId);
+ };
+
+ const [marimoConfig] = useResolvedMarimoConfig();
+ const configModels = marimoConfig.ai?.models;
+
+ // Only include autocompleteModel if copilot is set to "custom"
+ const autocompleteModel =
+ marimoConfig.completion.copilot === "custom"
+ ? configModels?.autocomplete_model
+ : undefined;
+
+ const aiModelRegistry = AiModelRegistry.create({
+ // We add all the custom models and the models used in the editor.
+ // If they among the known models, they won't overwrite them.
+ customModels: [
+ ...(configModels?.custom_models ?? []),
+ configModels?.chat_model,
+ autocompleteModel,
+ configModels?.edit_model,
+ ].filter(Boolean),
+ displayedModels: configModels?.displayed_models,
+ });
+ const modelsByProvider = aiModelRegistry.getGroupedModelsByProvider();
+
+ const activeModel =
+ forRole === "autocomplete"
+ ? configModels?.autocomplete_model
+ : forRole === "chat"
+ ? configModels?.chat_model
+ : forRole === "edit"
+ ? configModels?.edit_model
+ : undefined;
+
+ const iconSizeClass = iconSize === "medium" ? "h-4 w-4" : "h-3 w-3";
+
+ const renderModelWithRole = (modelId: AiModelId, role: Role) => {
+ const maybeModelMatch = aiModelRegistry.getModel(modelId.id);
+
+ return (
+ <div className="flex items-center gap-2 w-full px-2 py-1">
+ <AiProviderIcon
+ provider={modelId.providerId}
+ className={iconSizeClass}
+ />
+ <div className="flex flex-col">
+ <span>{maybeModelMatch?.name || modelId.shortModelId}</span>
+ <span className="text-xs text-muted-foreground">{modelId.id}</span>
+ </div>
+
+ <div className="ml-auto flex gap-1">
+ <span
+ key={role}
+ className={`text-xs px-1.5 py-0.5 rounded font-medium ${getTagColour(role)}`}
+ >
+ {role}
+ </span>
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className={`flex items-center justify-between px-2 py-0.5 border rounded-md
+ hover:bg-accent hover:text-accent-foreground ${triggerClassName}`}
+ >
+ <div className="flex items-center gap-2">
+ {currentValue ? (
+ <>
+ <AiProviderIcon
+ provider={currentValue.providerId}
+ className={iconSizeClass}
+ />
+ <span className="truncate">
+ {isKnownAIProvider(currentValue.providerId)
+ ? currentValue.shortModelId
+ : currentValue.id}
+ </span>
+ </>
+ ) : (
+ <span className="text-muted-foreground truncate">
+ {placeholder}
+ </span>
+ )}
+ </div>
+ <ChevronDownIcon className={`${iconSizeClass} ml-1`} />
+ </DropdownMenuTrigger>
+
+ <DropdownMenuContent className="w-[300px]">
+ {activeModel &&
+ forRole &&
+ renderModelWithRole(AiModelId.parse(activeModel), forRole)}
+ {activeModel && forRole && <DropdownMenuSeparator />}
+
+ {[...modelsByProvider.entries()].map(([provider, models]) => (
+ <ProviderDropdownContent
+ key={provider}
+ provider={provider}
+ onSelect={selectModel}
+ models={models}
+ iconSizeClass={iconSizeClass}
+ />
+ ))}
+
+ {customDropdownContent}
+
+ {showAddCustomModelDocs && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem className="flex items-center gap-2">
+ <a
+ className="flex items-center gap-1"
+ href="https://docs.marimo.io/guides/editor_features/ai_completion/?h=models#other-ai-providers"
+ target="_blank"
+ rel="noreferrer"
+ >
+ <CircleHelpIcon className="h-3 w-3" />
+ <span>How to add a custom model</span>
+ </a>
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
+
+const ProviderDropdownContent = ({
+ provider,
+ onSelect,
+ models,
+ customModelIcon,
+ iconSizeClass,
+}: {
+ provider: ProviderId;
+ onSelect: (modelId: QualifiedModelId) => void;
+ models: AiModel[];
+ customModelIcon?: React.ReactNode;
+ iconSizeClass: string;
+}) => {
+ const iconProvider = isKnownAIProvider(provider)
+ ? provider
+ : "openai-compatible";
+
+ const maybeProviderInfo = AiModelRegistry.getProviderInfo(provider);
+
+ if (models.length === 0) {
+ return null;
+ }
+
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <p className="flex items-center gap-2">
+ <AiProviderIcon provider={iconProvider} className={iconSizeClass} />
+ {getProviderLabel(provider)}
+ </p>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent
+ className="max-h-[40vh] overflow-y-auto"
+ alignOffset={-90}
+ >
+ {maybeProviderInfo && (
+ <>
+ <p className="text-sm text-muted-foreground p-2 max-w-[300px]">
+ {maybeProviderInfo.description}
+ <br />
+ </p>
+
+ <p className="text-sm text-muted-foreground p-2 pt-0">
+ You can find more information about this provider{" "}
+ <a
+ href={maybeProviderInfo.url}
+ target="_blank"
+ className="underline"
+ rel="noreferrer"
+ >
+ here
+ </a>
+ .
+ </p>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ {models.map((model) => {
+ const qualifiedModelId =
+ `${provider}/${model.model}` as QualifiedModelId;
+ return (
+ <DropdownMenuItem
+ key={qualifiedModelId}
+ className="flex items-center gap-2"
+ onSelect={(e) => {
+ onSelect(qualifiedModelId);
+ }}
+ onClick={(e) => {
+ e.preventDefault();
+ onSelect(qualifiedModelId);
+ }}
+ >
+ <AiProviderIcon provider={iconProvider} className="h-4 w-4" />
+ <div className="pl-1 flex flex-col">
+ <span>{model.name}</span>
+ <span className="text-xs text-muted-foreground">
+ {model.model}
+ </span>
+ </div>
+ {model.custom && customModelIcon}
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ );
+};
+
+function getProviderLabel(provider: ProviderId): string {
+ const providerInfo = AiModelRegistry.getProviderInfo(provider);
+ if (providerInfo) {
+ return providerInfo.name;
+ }
+ return capitalize(provider);
+}
+
+function getTagColour(role: Role): string {
+ switch (role) {
+ case "chat":
+ return "bg-[var(--purple-3)] text-[var(--purple-11)]";
+ case "autocomplete":
+ return "bg-[var(--green-3)] text-[var(--green-11)]";
+ case "edit":
+ return "bg-[var(--blue-3)] text-[var(--blue-11)]";
+ }
+ return "bg-[var(--mauve-3)] text-[var(--mauve-11)]";
+}
diff --git a/frontend/src/components/ai/ai-provider-icon.tsx b/frontend/src/components/ai/ai-provider-icon.tsx
index a177be0c64..581b7ef735 100644
--- a/frontend/src/components/ai/ai-provider-icon.tsx
+++ b/frontend/src/components/ai/ai-provider-icon.tsx
@@ -3,20 +3,23 @@
import AnthropicIcon from "@marimo-team/llm-info/icons/anthropic.svg?inline";
import BedrockIcon from "@marimo-team/llm-info/icons/aws.svg?inline";
import AzureIcon from "@marimo-team/llm-info/icons/azure.svg?inline";
-import GoogleIcon from "@marimo-team/llm-info/icons/google.svg?inline";
+import DeepseekIcon from "@marimo-team/llm-info/icons/deepseek.svg?inline";
+import GeminiIcon from "@marimo-team/llm-info/icons/googlegemini.svg?inline";
import OllamaIcon from "@marimo-team/llm-info/icons/ollama.svg?inline";
import OpenAIIcon from "@marimo-team/llm-info/icons/openai.svg?inline";
import { BotIcon } from "lucide-react";
import * as React from "react";
+import type { ProviderId } from "@/core/ai/ids/ids";
import { cn } from "@/utils/cn";
-const icons = {
+const icons: Record<ProviderId, string> = {
openai: OpenAIIcon,
anthropic: AnthropicIcon,
- google: GoogleIcon,
+ google: GeminiIcon,
ollama: OllamaIcon,
azure: AzureIcon,
bedrock: BedrockIcon,
+ deepseek: DeepseekIcon,
};
export interface AiProviderIconProps
@@ -30,7 +33,7 @@ export const AiProviderIcon: React.FC<AiProviderIconProps> = ({
className = "",
...props
}) => {
- if (provider === "openai-compatible") {
+ if (provider === "openai-compatible" || !(provider in icons)) {
return <BotIcon className={cn("h-4 w-4", className)} />;
}
diff --git a/frontend/src/components/app-config/ai-config.tsx b/frontend/src/components/app-config/ai-config.tsx
index ade4b15976..9d389ff750 100644
--- a/frontend/src/components/app-config/ai-config.tsx
+++ b/frontend/src/components/app-config/ai-config.tsx
@@ -1,10 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import React, { useId } from "react";
+import { InfoIcon } from "lucide-react";
+import React from "react";
import type { FieldPath, UseFormReturn } from "react-hook-form";
import {
FormControl,
FormDescription,
+ FormErrorsBanner,
FormField,
FormItem,
FormLabel,
@@ -14,9 +16,12 @@ 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 type { QualifiedModelId } from "@/core/ai/ids/ids";
import { CopilotConfig } from "@/core/codemirror/copilot/copilot-config";
import { DEFAULT_AI_MODEL, type UserConfig } from "@/core/config/config-schema";
import { isWasm } from "@/core/wasm/utils";
+import { Events } from "@/utils/events";
+import { AIModelDropdown } from "../ai/ai-model-dropdown";
import {
AiProviderIcon,
type AiProviderIconProps,
@@ -27,10 +32,12 @@ import {
AccordionItem,
AccordionTrigger,
} from "../ui/accordion";
+import { DropdownMenuSeparator } from "../ui/dropdown-menu";
import { ExternalLink } from "../ui/links";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
+import { Tooltip } from "../ui/tooltip";
import { SettingSubtitle } from "./common";
-import { AWS_REGIONS, KNOWN_AI_MODELS } from "./constants";
+import { AWS_REGIONS } from "./constants";
import { IncorrectModelId } from "./incorrect-model-id";
import { IsOverridden } from "./is-overridden";
@@ -182,6 +189,7 @@ interface ModelSelectorProps {
description?: React.ReactNode;
disabled?: boolean;
label: string;
+ onSubmit: (values: UserConfig) => Promise<void>;
}
export const ModelSelector: React.FC<ModelSelectorProps> = ({
@@ -193,42 +201,72 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
description,
disabled = false,
label,
+ onSubmit,
}) => {
- const modelInputId = useId();
-
return (
<FormField
control={form.control}
name={name}
disabled={disabled}
- render={({ field }) => (
- <div className="flex flex-col space-y-1">
+ render={({ field }) => {
+ const value = asStringOrUndefined(field.value);
+
+ const selectModel = (modelId: QualifiedModelId) => {
+ field.onChange(modelId);
+ onSubmit(form.getValues());
+ };
+
+ const renderFormItem = () => (
<FormItem className={formItemClasses}>
<FormLabel>{label}</FormLabel>
<FormControl>
- <Input
- list={modelInputId}
- data-testid={testId}
- className="m-0 inline-flex"
+ <AIModelDropdown
+ value={value}
placeholder={placeholder}
- {...field}
- value={asStringOrUndefined(field.value)}
+ onSelect={selectModel}
+ triggerClassName="text-sm"
+ customDropdownContent={
+ <>
+ <DropdownMenuSeparator />
+ <p className="px-2 py-1.5 text-sm text-muted-secondary flex items-center gap-1">
+ Enter a custom model
+ <Tooltip content="Models should include the provider prefix, e.g. 'openai/gpt-4o'">
+ <InfoIcon className="h-3 w-3" />
+ </Tooltip>
+ </p>
+ <div className="px-2 py-1">
+ <Input
+ data-testid={testId}
+ className="w-full border-border shadow-none focus-visible:shadow-xs"
+ placeholder={placeholder}
+ {...field}
+ value={asStringOrUndefined(field.value)}
+ onKeyDown={Events.stopPropagation()}
+ />
+ {value && (
+ <IncorrectModelId
+ value={value}
+ includeSuggestion={false}
+ />
+ )}
+ </div>
+ </>
+ }
/>
</FormControl>
<FormMessage />
- <IsOverridden userConfig={config} name={name} />
</FormItem>
- <datalist id={modelInputId}>
- {KNOWN_AI_MODELS.map((model) => (
- <option value={model} key={model}>
- {model}
- </option>
- ))}
- </datalist>
- <IncorrectModelId value={asStringOrUndefined(field.value)} />
- {description && <FormDescription>{description}</FormDescription>}
- </div>
- )}
+ );
+
+ return (
+ <div className="flex flex-col space-y-1">
+ {renderFormItem()}
+ <IsOverridden userConfig={config} name={name} />
+ <IncorrectModelId value={value} />
+ {description && <FormDescription>{description}</FormDescription>}
+ </div>
+ );
+ }}
/>
);
};
@@ -297,6 +335,7 @@ export const ProviderSelect: React.FC<ProviderSelectProps> = ({
const renderCopilotProvider = (
form: UseFormReturn<UserConfig>,
+ onSubmit: (values: UserConfig) => Promise<void>,
config: UserConfig,
) => {
const copilot = form.getValues("completion.copilot");
@@ -331,27 +370,16 @@ const renderCopilotProvider = (
if (copilot === "custom") {
return (
- <>
- <p className="text-sm text-muted-secondary">
- Configure your custom AI completion provider with the following
- settings.
- </p>
- <ModelSelector
- label="Autocomplete Model"
- form={form}
- config={config}
- name="ai.models.autocomplete_model"
- placeholder="ollama/qwen2.5-coder:1.5b"
- testId="custom-model-input"
- description={
- <>
- Model to use for code completion when using a custom provider.
- Models should include the provider name and model name separated
- by a slash.
- </>
- }
- />
- </>
+ <ModelSelector
+ label="Autocomplete Model"
+ form={form}
+ config={config}
+ name="ai.models.autocomplete_model"
+ placeholder="ollama/qwen2.5-coder:1.5b"
+ testId="custom-model-input"
+ description="Model to use for code completion when using a custom provider."
+ onSubmit={onSubmit}
+ />
);
}
};
@@ -363,6 +391,7 @@ const SettingGroup = ({ children }: { children: React.ReactNode }) => {
export const AiCodeCompletionConfig: React.FC<AiConfigProps> = ({
form,
config,
+ onSubmit,
}) => {
return (
<SettingGroup>
@@ -380,7 +409,7 @@ export const AiCodeCompletionConfig: React.FC<AiConfigProps> = ({
testId="copilot-select"
/>
- {renderCopilotProvider(form, config)}
+ {renderCopilotProvider(form, onSubmit, config)}
</SettingGroup>
);
};
@@ -645,17 +674,17 @@ export const AiProvidersConfig: React.FC<AiConfigProps> = ({
);
};
-export const AiAssistConfig: React.FC<AiConfigProps> = ({ form, config }) => {
+export const AiAssistConfig: React.FC<AiConfigProps> = ({
+ form,
+ config,
+ onSubmit,
+}) => {
const isWasmRuntime = isWasm();
return (
<SettingGroup>
<SettingSubtitle>AI Assistant</SettingSubtitle>
- <p className="text-sm text-muted-secondary">
- Use the Chat panel to talk to your codebase, or make edits using the{" "}
- <Kbd className="inline">Generate with AI</Kbd> button.
- </p>
-
+ <FormErrorsBanner />
<ModelSelector
label="Chat Model"
form={form}
@@ -665,21 +694,10 @@ export const AiAssistConfig: React.FC<AiConfigProps> = ({ form, config }) => {
testId="ai-chat-model-input"
disabled={isWasmRuntime}
description={
- <>
- <p>
- Model to use for chat conversations in the Chat panel. Models
- should include the provider name and model name separated by a
- slash. For example, "anthropic/claude-3-5-sonnet-latest" or
- "google/gemini-2.0-flash-exp".
- </p>
- <p className="pt-1">
- Depending on the provider, we will use the respective API key and
- additional configuration.
- </p>
- </>
+ <span>Model to use for chat conversations in the Chat panel.</span>
}
+ onSubmit={onSubmit}
/>
-
<ModelSelector
label="Edit Model"
form={form}
@@ -689,20 +707,26 @@ export const AiAssistConfig: React.FC<AiConfigProps> = ({ form, config }) => {
testId="ai-edit-model-input"
disabled={isWasmRuntime}
description={
- <>
- <p>
- Model to use for code editing with the{" "}
- <Kbd className="inline">Generate with AI</Kbd> button. Models
- should include the provider name and model name separated by a
- slash.
- </p>
- <p className="pt-1">
- You can use a faster, cheaper model for edits if desired.
- </p>
- </>
+ <span>
+ Model to use for code editing with the{" "}
+ <Kbd className="inline">Generate with AI</Kbd> button.
+ </span>
}
+ onSubmit={onSubmit}
/>
+ <ul className="bg-muted p-2 rounded-md list-disc space-y-1 pl-6">
+ <li className="text-xs text-muted-secondary">
+ Models should include the provider name and model name separated by a
+ slash. For example, "anthropic/claude-3-5-sonnet-latest" or
+ "google/gemini-2.0-flash-exp"
+ </li>
+ <li className="text-xs text-muted-secondary">
+ Depending on the provider, we will use the respective API key and
+ additional configuration.
+ </li>
+ </ul>
+
<FormField
control={form.control}
name="ai.rules"
diff --git a/frontend/src/components/app-config/app-config-button.tsx b/frontend/src/components/app-config/app-config-button.tsx
index aaf47ac673..f4e83ca222 100644
--- a/frontend/src/components/app-config/app-config-button.tsx
+++ b/frontend/src/components/app-config/app-config-button.tsx
@@ -2,6 +2,7 @@
import { useAtom } from "jotai";
import { SettingsIcon } from "lucide-react";
+import { VisuallyHidden } from "react-aria";
import { AppConfigForm } from "@/components/app-config/app-config-form";
import {
Popover,
@@ -10,7 +11,12 @@ import {
} from "@/components/ui/popover";
import { Button as EditorButton } from "../editor/inputs/Inputs";
import { Button } from "../ui/button";
-import { Dialog, DialogContent, DialogTrigger } from "../ui/dialog";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from "../ui/dialog";
import { Tooltip } from "../ui/tooltip";
import { settingDialogAtom } from "./state";
import { UserConfigForm } from "./user-config-form";
@@ -46,6 +52,9 @@ export const ConfigButton: React.FC<Props> = ({
const userSettingsDialog = (
<DialogContent className="w-[80vw] h-[70vh] overflow-hidden sm:max-w-5xl top-[15vh] p-0">
+ <VisuallyHidden>
+ <DialogTitle>User settings</DialogTitle>
+ </VisuallyHidden>
<UserConfigForm />
</DialogContent>
);
diff --git a/frontend/src/components/app-config/constants.ts b/frontend/src/components/app-config/constants.ts
index 912815df6b..192df4e0c5 100644
--- a/frontend/src/components/app-config/constants.ts
+++ b/frontend/src/components/app-config/constants.ts
@@ -1,38 +1,4 @@
/* Copyright 2024 Marimo. All rights reserved. */
-export const KNOWN_AI_MODELS = [
- // Anthropic
- "anthropic/claude-opus-4-1-20250805",
- "anthropic/claude-opus-4-20250514",
- "anthropic/claude-sonnet-4-20250514",
- "anthropic/claude-3-7-sonnet-latest",
- "anthropic/claude-3-5-sonnet-latest",
- "anthropic/claude-3-5-haiku-latest",
-
- // DeepSeek
- "deepseek/deepseek-v3",
- "deepseek/deepseek-r1",
-
- // Google
- "google/gemini-2.5-flash-preview-05-20",
- "google/gemini-2.5-pro-preview-06-05",
- "google/gemini-2.0-flash",
- "google/gemini-2.0-flash-lite",
-
- // OpenAI
- "openai/o3",
- "openai/o4-mini",
- "openai/gpt-4.5-preview",
- "openai/gpt-4.1",
- "openai/gpt-4o",
- "openai/gpt-3.5-turbo",
-
- // AWS Bedrock Models
- "bedrock/anthropic.claude-3-5-haiku-20241022-v1:0",
- "bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
- "bedrock/anthropic.claude-3-7-sonnet-20250219-v1:0",
- "bedrock/meta.llama3-3-70b-instruct-v1:0",
- "bedrock/cohere.command-r-plus-v1",
-] as const;
/**
* AWS regions where the Bedrock service is available
diff --git a/frontend/src/components/app-config/incorrect-model-id.tsx b/frontend/src/components/app-config/incorrect-model-id.tsx
index 2ecb0bd2fc..99630ec3c8 100644
--- a/frontend/src/components/app-config/incorrect-model-id.tsx
+++ b/frontend/src/components/app-config/incorrect-model-id.tsx
@@ -1,14 +1,16 @@
/* Copyright 2024 Marimo. All rights reserved. */
import React from "react";
+import { AiModelId, type QualifiedModelId } from "@/core/ai/ids/ids";
import { Banner } from "@/plugins/impl/common/error-banner";
-import { AiModelId, type QualifiedModelId } from "@/utils/ai/ids";
interface IncorrectModelIdProps {
value: string | null | undefined;
+ includeSuggestion?: boolean;
}
export const IncorrectModelId: React.FC<IncorrectModelIdProps> = ({
value,
+ includeSuggestion = true,
}) => {
if (!value) {
return null;
@@ -31,7 +33,7 @@ export const IncorrectModelId: React.FC<IncorrectModelIdProps> = ({
provider.
</span>
<br />
- {suggestion && (
+ {includeSuggestion && suggestion && (
<span>
Did you mean <code className="font-bold">{suggestion}</code>?
</span>
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 479b58d20b..cc185141a4 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -12,7 +12,7 @@ import {
MonitorIcon,
PackageIcon,
} from "lucide-react";
-import React, { useRef } from "react";
+import React, { useId, useRef } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
@@ -130,6 +130,8 @@ export const UserConfigForm: React.FC = () => {
};
const isWasmRuntime = isWasm();
+ const htmlCheckboxId = useId();
+ const ipynbCheckboxId = useId();
const renderBody = () => {
switch (activeCategory) {
@@ -168,6 +170,7 @@ export const UserConfigForm: React.FC = () => {
<FormLabel>Autosave delay (seconds)</FormLabel>
<FormControl>
<NumberField
+ aria-label="Autosave delay"
data-testid="autosave-delay-input"
className="m-0 w-24"
isDisabled={
@@ -205,7 +208,7 @@ export const UserConfigForm: React.FC = () => {
<div className="flex gap-4">
<div className="flex items-center space-x-2">
<Checkbox
- id="html-checkbox"
+ id={htmlCheckboxId}
checked={
Array.isArray(field.value) &&
field.value.includes("html")
@@ -219,11 +222,11 @@ export const UserConfigForm: React.FC = () => {
);
}}
/>
- <FormLabel htmlFor="html-checkbox">HTML</FormLabel>
+ <FormLabel htmlFor={htmlCheckboxId}>HTML</FormLabel>
</div>
<div className="flex items-center space-x-2">
<Checkbox
- id="ipynb-checkbox"
+ id={ipynbCheckboxId}
checked={
Array.isArray(field.value) &&
field.value.includes("ipynb")
@@ -237,7 +240,7 @@ export const UserConfigForm: React.FC = () => {
);
}}
/>
- <FormLabel htmlFor="ipynb-checkbox">
+ <FormLabel htmlFor={ipynbCheckboxId}>
IPYNB
</FormLabel>
</div>
@@ -295,6 +298,7 @@ export const UserConfigForm: React.FC = () => {
<FormLabel>Line length</FormLabel>
<FormControl>
<NumberField
+ aria-label="Line length"
data-testid="line-length-input"
className="m-0 w-24"
{...field}
@@ -716,6 +720,7 @@ export const UserConfigForm: React.FC = () => {
<FormControl>
<span className="inline-flex mr-2">
<NumberField
+ aria-label="Code editor font size"
data-testid="code-editor-font-size-input"
className="m-0 w-24"
{...field}
@@ -848,6 +853,7 @@ export const UserConfigForm: React.FC = () => {
<FormLabel>Default table page size</FormLabel>
<FormControl>
<NumberField
+ aria-label="Default table page size"
data-testid="default-table-page-size-input"
className="m-0 w-24"
{...field}
@@ -884,6 +890,7 @@ export const UserConfigForm: React.FC = () => {
<FormLabel>Default table max columns</FormLabel>
<FormControl>
<NumberField
+ aria-label="Default table max columns"
data-testid="default-table-max-columns-input"
className="m-0 w-24"
{...field}
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index 5fea9c3114..56655bc3ae 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -36,6 +36,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { addMessageToChat } from "@/core/ai/chat-utils";
+import type { QualifiedModelId } from "@/core/ai/ids/ids";
import {
activeChatAtom,
type Chat,
@@ -54,7 +55,7 @@ import { cn } from "@/utils/cn";
import { timeAgo } from "@/utils/dates";
import { Logger } from "@/utils/Logger";
import { generateUUID } from "@/utils/uuid";
-import { KNOWN_AI_MODELS } from "../app-config/constants";
+import { AIModelDropdown } from "../ai/ai-model-dropdown";
import { useOpenSettingsToTab } from "../app-config/state";
import { PromptInput } from "../editor/ai/add-cell-with-ai";
import { getAICompletionBody } from "../editor/ai/completion-utils";
@@ -276,7 +277,7 @@ const ChatInputFooter: React.FC<ChatInputFooterProps> = memo(
saveConfig(newConfig);
};
- const handleModelChange = async (newModel: string) => {
+ const handleModelChange = async (newModel: QualifiedModelId) => {
const newConfig: UserConfig = {
...userConfig,
ai: {
@@ -324,30 +325,15 @@ const ChatInputFooter: React.FC<ChatInputFooterProps> = memo(
</SelectContent>
</Select>
</FeatureFlagged>
- <Select value={currentModel} onValueChange={handleModelChange}>
- <SelectTrigger className="h-6 text-xs border-border shadow-none! ring-0! bg-muted hover:bg-muted/30 py-0 px-2 gap-1">
- <SelectValue placeholder="Model" />
- </SelectTrigger>
- <SelectContent>
- {/* Show current model if it's not in the known models list */}
- {!(KNOWN_AI_MODELS as readonly string[]).includes(
- currentModel,
- ) && (
- <SelectItem
- key={currentModel}
- value={currentModel}
- className="text-sm"
- >
- {currentModel}
- </SelectItem>
- )}
- {KNOWN_AI_MODELS.map((model) => (
- <SelectItem key={model} value={model} className="text-sm">
- {model}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <AIModelDropdown
+ value={currentModel}
+ placeholder="Model"
+ onSelect={handleModelChange}
+ triggerClassName="h-6 text-xs shadow-none! ring-0! bg-muted hover:bg-muted/30 rounded-sm"
+ iconSize="small"
+ showAddCustomModelDocs={true}
+ forRole="chat"
+ />
</div>
<Button
variant="ghost"
diff --git a/frontend/src/core/ai/__tests__/model-registry.test.ts b/frontend/src/core/ai/__tests__/model-registry.test.ts
new file mode 100644
index 0000000000..c8a1a2db15
--- /dev/null
+++ b/frontend/src/core/ai/__tests__/model-registry.test.ts
@@ -0,0 +1,357 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// 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: "Multi Provider Model",
+ model: "multi-model",
+ description: "Model available on multiple providers",
+ providers: ["openai", "anthropic"],
+ roles: ["chat", "edit"],
+ thinking: false,
+ },
+ ];
+
+ return {
+ models: models,
+ };
+});
+
+import type { AiModel } from "@marimo-team/llm-info";
+import { AiModelRegistry } from "../model-registry";
+
+describe("AiModelRegistry", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("create", () => {
+ it("should create registry with no custom or displayed models", () => {
+ const registry = AiModelRegistry.create({});
+
+ expect(registry).toBeInstanceOf(AiModelRegistry);
+ expect(registry.getCustomModels()).toEqual(new Set());
+ expect(registry.getDisplayedModels()).toEqual(new Set());
+ });
+
+ it("should create registry with custom models", () => {
+ const customModels = ["openai/custom-gpt", "anthropic/custom-claude"];
+ const registry = AiModelRegistry.create({ customModels });
+
+ expect(registry.getCustomModels()).toEqual(new Set(customModels));
+ expect(registry.getDisplayedModels()).toEqual(new Set());
+ });
+
+ it("should create registry with displayed models", () => {
+ const displayedModels = ["openai/gpt-4", "anthropic/claude-3-sonnet"];
+ const registry = AiModelRegistry.create({ displayedModels });
+
+ expect(registry.getCustomModels()).toEqual(new Set());
+ expect(registry.getDisplayedModels()).toEqual(new Set(displayedModels));
+ });
+
+ it("should create registry with both custom and displayed models", () => {
+ const customModels = ["openai/custom-gpt"];
+ const displayedModels = ["openai/gpt-4", "anthropic/claude-3-sonnet"];
+ const registry = AiModelRegistry.create({
+ customModels,
+ displayedModels,
+ });
+
+ expect(registry.getCustomModels()).toEqual(new Set(customModels));
+ expect(registry.getDisplayedModels()).toEqual(new Set(displayedModels));
+ });
+ });
+
+ describe("getModelsByProvider", () => {
+ it("should return models for a specific provider", () => {
+ const registry = AiModelRegistry.create({});
+ const openaiModels = registry.getModelsByProvider("openai");
+
+ expect(openaiModels).toHaveLength(2); // gpt-4 and multi-model
+ expect(
+ openaiModels.every((model) => model.providers.includes("openai")),
+ ).toBe(true);
+ });
+
+ it("should return empty array for provider with no models", () => {
+ const registry = AiModelRegistry.create({});
+ const azureModels = registry.getModelsByProvider("azure");
+
+ expect(azureModels).toEqual([]);
+ });
+
+ it("should include custom models for the provider", () => {
+ const customModels = ["openai/custom-gpt"];
+ const registry = AiModelRegistry.create({ customModels });
+ const openaiModels = registry.getModelsByProvider("openai");
+
+ const customModel = openaiModels.find((model) => model.custom);
+ expect(customModel).toBeDefined();
+ expect(customModel?.name).toBe("openai/custom-gpt");
+ expect(customModel?.model).toBe("custom-gpt");
+ expect(customModel?.description).toBe("Custom model");
+ expect(customModel?.providers).toEqual(["openai"]);
+ expect(customModel?.roles).toEqual([]);
+ expect(customModel?.thinking).toBe(false);
+ });
+
+ it("should filter models based on displayed models", () => {
+ const displayedModels = ["openai/gpt-4"];
+ const registry = AiModelRegistry.create({ displayedModels });
+ const openaiModels = registry.getModelsByProvider("openai");
+
+ expect(openaiModels).toHaveLength(1);
+ expect(openaiModels[0].model).toBe("gpt-4");
+ });
+
+ it("should filter custom models based on displayed models", () => {
+ const customModels = ["openai/custom-gpt", "anthropic/custom-claude"];
+ const displayedModels = ["openai/custom-gpt"];
+ const registry = AiModelRegistry.create({
+ customModels,
+ displayedModels,
+ });
+
+ const openaiModels = registry.getModelsByProvider("openai");
+ const anthropicModels = registry.getModelsByProvider("anthropic");
+
+ expect(
+ openaiModels.some(
+ (model) => model.custom && model.model === "custom-gpt",
+ ),
+ ).toBe(true);
+ expect(
+ anthropicModels.some(
+ (model) => model.custom && model.model === "custom-claude",
+ ),
+ ).toBe(false);
+ });
+ });
+
+ describe("getGroupedModelsByProvider", () => {
+ it("should return all models grouped by provider", () => {
+ const registry = AiModelRegistry.create({});
+ const groupedModels = registry.getGroupedModelsByProvider();
+
+ expect(groupedModels.has("openai")).toBe(true);
+ expect(groupedModels.has("anthropic")).toBe(true);
+ expect(groupedModels.has("google")).toBe(true);
+
+ const openaiModels = groupedModels.get("openai") || [];
+ const anthropicModels = groupedModels.get("anthropic") || [];
+ const googleModels = groupedModels.get("google") || [];
+
+ expect(openaiModels.length).toEqual(2);
+ expect(anthropicModels.length).toEqual(2);
+ expect(googleModels.length).toEqual(1);
+ });
+
+ it("should include custom models in the grouped results", () => {
+ const customModels = ["openai/custom-gpt", "anthropic/custom-claude"];
+ const registry = AiModelRegistry.create({ customModels });
+ const groupedModels = registry.getGroupedModelsByProvider();
+
+ const openaiModels = groupedModels.get("openai") || [];
+ const anthropicModels = groupedModels.get("anthropic") || [];
+
+ expect(
+ openaiModels.some(
+ (model) => model.custom && model.model === "custom-gpt",
+ ),
+ ).toBe(true);
+ expect(
+ anthropicModels.some(
+ (model) => model.custom && model.model === "custom-claude",
+ ),
+ ).toBe(true);
+ });
+
+ it("should respect displayed models filter", () => {
+ const displayedModels = ["openai/gpt-4", "anthropic/claude-3-sonnet"];
+ const registry = AiModelRegistry.create({ displayedModels });
+ const groupedModels = registry.getGroupedModelsByProvider();
+
+ const openaiModels = groupedModels.get("openai") || [];
+ const anthropicModels = groupedModels.get("anthropic") || [];
+ const googleModels = groupedModels.get("google") || [];
+
+ expect(openaiModels.length).toBe(1);
+ expect(openaiModels[0].model).toBe("gpt-4");
+ expect(anthropicModels.length).toBe(1);
+ expect(anthropicModels[0].model).toBe("claude-3-sonnet");
+ expect(googleModels.length).toBe(0);
+ });
+ });
+
+ describe("getCustomModels", () => {
+ it("should return empty set when no custom models", () => {
+ const registry = AiModelRegistry.create({});
+ expect(registry.getCustomModels()).toEqual(new Set());
+ });
+
+ it("should return set of custom model IDs", () => {
+ const customModels = ["openai/custom-gpt", "anthropic/custom-claude"];
+ const registry = AiModelRegistry.create({ customModels });
+ expect(registry.getCustomModels()).toEqual(new Set(customModels));
+ });
+ });
+
+ describe("getDisplayedModels", () => {
+ it("should return empty set when no displayed models specified", () => {
+ const registry = AiModelRegistry.create({});
+ expect(registry.getDisplayedModels()).toEqual(new Set());
+ });
+
+ it("should return set of displayed model IDs", () => {
+ const displayedModels = ["openai/gpt-4", "anthropic/claude-3-sonnet"];
+ const registry = AiModelRegistry.create({ displayedModels });
+ expect(registry.getDisplayedModels()).toEqual(new Set(displayedModels));
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle empty arrays for custom and displayed models", () => {
+ const registry = AiModelRegistry.create({
+ customModels: [],
+ displayedModels: [],
+ });
+
+ expect(registry.getCustomModels()).toEqual(new Set());
+ expect(registry.getDisplayedModels()).toEqual(new Set());
+
+ // Should still load default models
+ const openaiModels = registry.getModelsByProvider("openai");
+ expect(openaiModels.length).toBeGreaterThan(0);
+ });
+
+ it("should handle models with multiple providers", () => {
+ const registry = AiModelRegistry.create({});
+
+ const openaiModels = registry.getModelsByProvider("openai");
+ const anthropicModels = registry.getModelsByProvider("anthropic");
+
+ // The multi-model should appear in both providers
+ const multiModelInOpenai = openaiModels.find(
+ (model) => model.model === "multi-model",
+ );
+ const multiModelInAnthropic = anthropicModels.find(
+ (model) => model.model === "multi-model",
+ );
+
+ expect(multiModelInOpenai).toBeDefined();
+ expect(multiModelInAnthropic).toBeDefined();
+ expect(multiModelInOpenai).toEqual(multiModelInAnthropic);
+ });
+
+ it("should handle displayed models filter with non-existent models", () => {
+ const displayedModels = [
+ "openai/non-existent-model",
+ "anthropic/claude-3-sonnet",
+ ];
+ const registry = AiModelRegistry.create({ displayedModels });
+
+ const openaiModels = registry.getModelsByProvider("openai");
+ const anthropicModels = registry.getModelsByProvider("anthropic");
+
+ // Should only show the existing model
+ expect(openaiModels.length).toBe(0);
+ expect(anthropicModels.length).toBe(1);
+ expect(anthropicModels[0].model).toBe("claude-3-sonnet");
+ });
+ });
+
+ describe("model properties", () => {
+ it("should ensure all models have required properties", () => {
+ const registry = AiModelRegistry.create({});
+ const groupedModels = registry.getGroupedModelsByProvider();
+
+ for (const [provider, models] of groupedModels.entries()) {
+ for (const model of models) {
+ expect(model).toHaveProperty("name");
+ expect(model).toHaveProperty("model");
+ expect(model).toHaveProperty("description");
+ expect(model).toHaveProperty("providers");
+ expect(model).toHaveProperty("roles");
+ expect(model).toHaveProperty("thinking");
+ expect(model).toHaveProperty("custom");
+
+ expect(typeof model.name).toBe("string");
+ expect(typeof model.model).toBe("string");
+ expect(typeof model.description).toBe("string");
+ expect(Array.isArray(model.providers)).toBe(true);
+ expect(Array.isArray(model.roles)).toBe(true);
+ expect(typeof model.thinking).toBe("boolean");
+ expect(typeof model.custom).toBe("boolean");
+
+ expect(model.providers).toContain(provider);
+ }
+ }
+ });
+
+ it("should ensure custom models have correct custom property", () => {
+ const customModels = ["openai/custom-gpt"];
+ const registry = AiModelRegistry.create({ customModels });
+ const openaiModels = registry.getModelsByProvider("openai");
+
+ const customModel = openaiModels.find((model) => model.custom);
+ const defaultModel = openaiModels.find((model) => !model.custom);
+
+ expect(customModel).toMatchInlineSnapshot(`
+ {
+ "custom": true,
+ "description": "Custom model",
+ "model": "custom-gpt",
+ "name": "openai/custom-gpt",
+ "providers": [
+ "openai",
+ ],
+ "roles": [],
+ "thinking": false,
+ }
+ `);
+ expect(defaultModel).toMatchInlineSnapshot(`
+ {
+ "custom": false,
+ "description": "OpenAI GPT-4 model",
+ "model": "gpt-4",
+ "name": "GPT-4",
+ "providers": [
+ "openai",
+ ],
+ "roles": [
+ "chat",
+ "edit",
+ ],
+ "thinking": false,
+ }
+ `);
+ });
+ });
+});
diff --git a/frontend/src/utils/ai/__tests__/ids.test.ts b/frontend/src/core/ai/ids/__tests__/ids.test.ts
similarity index 98%
rename from frontend/src/utils/ai/__tests__/ids.test.ts
rename to frontend/src/core/ai/ids/__tests__/ids.test.ts
index 231212dadc..8ff8683f11 100644
--- a/frontend/src/utils/ai/__tests__/ids.test.ts
+++ b/frontend/src/core/ai/ids/__tests__/ids.test.ts
@@ -1,7 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { AiModelId, type ProviderId, type ShortModelId } from "../ids";
+import type { ProviderId } from "../ids";
+import { AiModelId, type ShortModelId } from "../ids";
describe("AiModelId", () => {
describe("constructor", () => {
diff --git a/frontend/src/utils/ai/ids.ts b/frontend/src/core/ai/ids/ids.ts
similarity index 75%
rename from frontend/src/utils/ai/ids.ts
rename to frontend/src/core/ai/ids/ids.ts
index 369ec3826e..660aee3b6e 100644
--- a/frontend/src/utils/ai/ids.ts
+++ b/frontend/src/core/ai/ids/ids.ts
@@ -1,16 +1,17 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { TypedString } from "../typed";
+import type { TypedString } from "@/utils/typed";
-/**
- * Supported providers by the marimo server.
- */
-export type ProviderId =
- | "openai"
- | "anthropic"
- | "google"
- | "ollama"
- | "bedrock";
+export const PROVIDERS = [
+ "openai",
+ "anthropic",
+ "google",
+ "ollama",
+ "bedrock",
+ "deepseek",
+ "azure",
+] as const;
+export type ProviderId = (typeof PROVIDERS)[number];
export type ShortModelId = TypedString<"ShortModelId">;
@@ -57,5 +58,12 @@ function guessProviderId(id: string): ProviderId {
if (id.startsWith("gemini") || id.startsWith("google")) {
return "google";
}
+ if (id.startsWith("deepseek")) {
+ return "deepseek";
+ }
return "ollama";
}
+
+export function isKnownAIProvider(providerId: ProviderId): boolean {
+ return PROVIDERS.includes(providerId);
+}
diff --git a/frontend/src/core/ai/model-registry.ts b/frontend/src/core/ai/model-registry.ts
new file mode 100644
index 0000000000..18c7b65c1d
--- /dev/null
+++ b/frontend/src/core/ai/model-registry.ts
@@ -0,0 +1,164 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type {
+ AiModel as AiModelType,
+ AiProvider,
+ Role,
+} from "@marimo-team/llm-info";
+import { models } from "@marimo-team/llm-info/models.json";
+import { providers } from "@marimo-team/llm-info/providers.json";
+import { MultiMap } from "@/utils/multi-map";
+import { once } from "@/utils/once";
+import type { ProviderId } from "./ids/ids";
+import { AiModelId, type QualifiedModelId, type ShortModelId } from "./ids/ids";
+
+export interface AiModel extends AiModelType {
+ roles: Role[];
+ providers: ProviderId[];
+ /** Whether this is a custom model. */
+ custom: boolean;
+}
+
+const getKnownModelMap = once((): ReadonlyMap<QualifiedModelId, AiModel> => {
+ const modelMap = new Map<QualifiedModelId, AiModel>();
+ for (const model of models) {
+ const modelId = model.model as ShortModelId;
+ const modelInfo: AiModel = {
+ ...model,
+ roles: model.roles.map((role) => role as Role),
+ providers: model.providers as ProviderId[],
+ custom: false,
+ };
+
+ for (const provider of modelInfo.providers) {
+ const qualifiedModelId: QualifiedModelId = `${provider}/${modelId}`;
+ modelMap.set(qualifiedModelId, modelInfo);
+ }
+ }
+ return modelMap;
+});
+
+const getProviderMap = once((): ReadonlyMap<ProviderId, AiProvider> => {
+ const providerMap = new Map<ProviderId, AiProvider>();
+ for (const provider of providers) {
+ providerMap.set(provider.id as ProviderId, provider);
+ }
+ return providerMap;
+});
+
+export class AiModelRegistry {
+ private modelsByProviderMap = new MultiMap<ProviderId, AiModel>();
+ private modelsMap: ReadonlyMap<QualifiedModelId, AiModel>;
+ private customModels: ReadonlySet<QualifiedModelId>;
+ private displayedModels: ReadonlySet<QualifiedModelId>;
+
+ private constructor(
+ customModels: QualifiedModelId[],
+ displayedModels: QualifiedModelId[],
+ ) {
+ this.customModels = new Set(customModels);
+ this.displayedModels = new Set(displayedModels);
+ this.modelsMap = new Map<QualifiedModelId, AiModel>();
+ this.buildMaps();
+ }
+
+ static getProviderInfo(providerId: ProviderId) {
+ return getProviderMap().get(providerId);
+ }
+
+ /**
+ * @param customModels - A list of custom models to use that are not from the default list.
+ * @param displayedModels - A list of models to display in the UI. If empty, all models will be displayed.
+ *
+ * Models should be in the format of `provider_id/short_model_id`.
+ */
+ static create(opts: { customModels?: string[]; displayedModels?: string[] }) {
+ const { customModels = [], displayedModels = [] } = opts;
+ return new AiModelRegistry(
+ customModels.map((model) => AiModelId.parse(model).id),
+ displayedModels.map((model) => AiModelId.parse(model).id),
+ );
+ }
+
+ /**
+ * Builds the maps of models by provider and custom models.
+ * Custom models are added first as they are specified by the user, so we want to surface them first.
+ */
+ private buildMaps() {
+ const displayedModels = this.displayedModels;
+ const hasDisplayedModels = displayedModels.size > 0;
+ const knownModelMap = getKnownModelMap();
+ let modelsMap = new Map<QualifiedModelId, AiModel>();
+
+ // Start with known models
+ if (hasDisplayedModels) {
+ for (const model of displayedModels) {
+ if (knownModelMap.has(model)) {
+ const knownModel = knownModelMap.get(model);
+ if (knownModel) {
+ modelsMap.set(model, knownModel);
+ }
+ }
+ }
+ } else {
+ modelsMap = new Map(knownModelMap);
+ }
+
+ // Add custom models
+ for (const model of this.customModels) {
+ // Skip custom models that are not displayed
+ if (hasDisplayedModels && !displayedModels.has(model)) {
+ continue;
+ }
+
+ // If custom model conflicts with a known model, skip it
+ if (modelsMap.has(model)) {
+ continue;
+ }
+
+ const modelId = AiModelId.parse(model);
+ const modelInfo: AiModel = {
+ name: modelId.id,
+ model: modelId.shortModelId,
+ description: "Custom model",
+ providers: [modelId.providerId],
+ roles: [],
+ thinking: false,
+ custom: true,
+ };
+ modelsMap.set(model, modelInfo);
+ }
+
+ // Group by provider
+ for (const [qualifiedModelId, model] of modelsMap.entries()) {
+ const modelId = AiModelId.parse(qualifiedModelId);
+ this.modelsByProviderMap.add(modelId.providerId, model);
+ }
+
+ this.modelsMap = modelsMap;
+ }
+
+ getDisplayedModels() {
+ return this.displayedModels;
+ }
+
+ getCustomModels() {
+ return this.customModels;
+ }
+
+ getModelsByProvider(provider: ProviderId) {
+ return this.modelsByProviderMap.get(provider) || [];
+ }
+
+ getGroupedModelsByProvider() {
+ return this.modelsByProviderMap;
+ }
+
+ getModelsMap() {
+ return this.modelsMap;
+ }
+
+ getModel(qualifiedModelId: QualifiedModelId) {
+ return this.modelsMap.get(qualifiedModelId);
+ }
+}
diff --git a/frontend/src/core/cells/effects.ts b/frontend/src/core/cells/effects.ts
index 4640c9dde5..154eeaa956 100644
--- a/frontend/src/core/cells/effects.ts
+++ b/frontend/src/core/cells/effects.ts
@@ -9,7 +9,7 @@ import { store } from "../state/jotai";
import type { CellId } from "./ids";
const debounceSyncCellIds = debounce((request: UpdateCellIdsRequest) => {
- getRequestClient().syncCellIds(request);
+ return getRequestClient().syncCellIds(request);
}, 400);
export const CellEffects = {
diff --git a/frontend/src/utils/__tests__/multi-map.test.ts b/frontend/src/utils/__tests__/multi-map.test.ts
new file mode 100644
index 0000000000..78d91defa1
--- /dev/null
+++ b/frontend/src/utils/__tests__/multi-map.test.ts
@@ -0,0 +1,295 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MultiMap } from "../multi-map";
+
+describe("MultiMap", () => {
+ let multiMap: MultiMap<string, number>;
+
+ beforeEach(() => {
+ multiMap = new MultiMap<string, number>();
+ });
+
+ describe("constructor", () => {
+ it("should create an empty MultiMap", () => {
+ expect(multiMap.size).toBe(0);
+ });
+ });
+
+ describe("get", () => {
+ it("should return empty array for non-existent key", () => {
+ expect(multiMap.get("nonexistent")).toEqual([]);
+ });
+
+ it("should return values for existing key", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key1", 2);
+ expect(multiMap.get("key1")).toEqual([1, 2]);
+ });
+ });
+
+ describe("set", () => {
+ it("should set values for a key", () => {
+ multiMap.set("key1", [1, 2, 3]);
+ expect(multiMap.get("key1")).toEqual([1, 2, 3]);
+ });
+
+ it("should overwrite existing values", () => {
+ multiMap.add("key1", 1);
+ multiMap.set("key1", [4, 5, 6]);
+ expect(multiMap.get("key1")).toEqual([4, 5, 6]);
+ });
+
+ it("should set empty array", () => {
+ multiMap.set("key1", []);
+ expect(multiMap.get("key1")).toEqual([]);
+ expect(multiMap.has("key1")).toBe(true);
+ });
+ });
+
+ describe("add", () => {
+ it("should add value to new key", () => {
+ multiMap.add("key1", 1);
+ expect(multiMap.get("key1")).toEqual([1]);
+ });
+
+ it("should add value to existing key", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key1", 2);
+ expect(multiMap.get("key1")).toEqual([1, 2]);
+ });
+
+ it("should handle multiple keys", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key2", 2);
+ multiMap.add("key1", 3);
+ expect(multiMap.get("key1")).toEqual([1, 3]);
+ expect(multiMap.get("key2")).toEqual([2]);
+ });
+ });
+
+ describe("has", () => {
+ it("should return false for non-existent key", () => {
+ expect(multiMap.has("nonexistent")).toBe(false);
+ });
+
+ it("should return true for existing key", () => {
+ multiMap.add("key1", 1);
+ expect(multiMap.has("key1")).toBe(true);
+ });
+
+ it("should return true for key with empty array", () => {
+ multiMap.set("key1", []);
+ expect(multiMap.has("key1")).toBe(true);
+ });
+ });
+
+ describe("delete", () => {
+ it("should return false for non-existent key", () => {
+ expect(multiMap.delete("nonexistent")).toBe(false);
+ });
+
+ it("should delete existing key and return true", () => {
+ multiMap.add("key1", 1);
+ expect(multiMap.delete("key1")).toBe(true);
+ expect(multiMap.has("key1")).toBe(false);
+ expect(multiMap.get("key1")).toEqual([]);
+ });
+
+ it("should not affect other keys", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key2", 2);
+ multiMap.delete("key1");
+ expect(multiMap.has("key2")).toBe(true);
+ expect(multiMap.get("key2")).toEqual([2]);
+ });
+ });
+
+ describe("clear", () => {
+ it("should clear empty MultiMap", () => {
+ multiMap.clear();
+ expect(multiMap.size).toBe(0);
+ });
+
+ it("should clear all keys and values", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key2", 2);
+ multiMap.clear();
+ expect(multiMap.size).toBe(0);
+ expect(multiMap.has("key1")).toBe(false);
+ expect(multiMap.has("key2")).toBe(false);
+ });
+ });
+
+ describe("keys", () => {
+ it("should return empty iterator for empty MultiMap", () => {
+ const keys = [...multiMap.keys()];
+ expect(keys).toEqual([]);
+ });
+
+ it("should return all keys", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key2", 2);
+ multiMap.add("key3", 3);
+ const keys = [...multiMap.keys()];
+ expect(keys.sort()).toEqual(["key1", "key2", "key3"]);
+ });
+ });
+
+ describe("values", () => {
+ it("should return empty iterator for empty MultiMap", () => {
+ const values = [...multiMap.values()];
+ expect(values).toEqual([]);
+ });
+
+ it("should return all value arrays", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key1", 2);
+ multiMap.add("key2", 3);
+ const values = [...multiMap.values()];
+ expect(values).toHaveLength(2);
+ expect(values).toContainEqual([1, 2]);
+ expect(values).toContainEqual([3]);
+ });
+ });
+
+ describe("entries", () => {
+ it("should return empty iterator for empty MultiMap", () => {
+ const entries = [...multiMap.entries()];
+ expect(entries).toEqual([]);
+ });
+
+ it("should return all key-value pairs", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key1", 2);
+ multiMap.add("key2", 3);
+ const entries = [...multiMap.entries()];
+ expect(entries).toHaveLength(2);
+ expect(entries).toContainEqual(["key1", [1, 2]]);
+ expect(entries).toContainEqual(["key2", [3]]);
+ });
+ });
+
+ describe("forEach", () => {
+ it("should not call callback for empty MultiMap", () => {
+ const callback = vi.fn();
+ multiMap.forEach(callback);
+ expect(callback).not.toHaveBeenCalled();
+ });
+
+ it("should call callback for each key-value pair", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key1", 2);
+ multiMap.add("key2", 3);
+
+ const callback = vi.fn();
+ multiMap.forEach(callback);
+
+ expect(callback).toHaveBeenCalledTimes(2);
+ expect(callback).toHaveBeenCalledWith([1, 2], "key1", expect.any(Map));
+ expect(callback).toHaveBeenCalledWith([3], "key2", expect.any(Map));
+ });
+ });
+
+ describe("flatValues", () => {
+ it("should return empty array for empty MultiMap", () => {
+ expect(multiMap.flatValues()).toEqual([]);
+ });
+
+ it("should flatten all values into single array", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key1", 2);
+ multiMap.add("key2", 3);
+ multiMap.add("key3", 4);
+ multiMap.add("key3", 5);
+
+ const flattened = multiMap.flatValues();
+ expect(flattened.sort()).toEqual([1, 2, 3, 4, 5]);
+ });
+
+ it("should handle empty arrays in values", () => {
+ multiMap.set("key1", []);
+ multiMap.add("key2", 1);
+ multiMap.add("key2", 2);
+
+ const flattened = multiMap.flatValues();
+ expect(flattened.sort()).toEqual([1, 2]);
+ });
+ });
+
+ describe("size", () => {
+ it("should return 0 for empty MultiMap", () => {
+ expect(multiMap.size).toBe(0);
+ });
+
+ it("should return number of keys", () => {
+ multiMap.add("key1", 1);
+ expect(multiMap.size).toBe(1);
+
+ multiMap.add("key1", 2);
+ expect(multiMap.size).toBe(1);
+
+ multiMap.add("key2", 3);
+ expect(multiMap.size).toBe(2);
+ });
+
+ it("should update when keys are deleted", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key2", 2);
+ expect(multiMap.size).toBe(2);
+
+ multiMap.delete("key1");
+ expect(multiMap.size).toBe(1);
+
+ multiMap.clear();
+ expect(multiMap.size).toBe(0);
+ });
+ });
+
+ describe("different key and value types", () => {
+ it("should work with number keys and string values", () => {
+ const numberKeyMap = new MultiMap<number, string>();
+ numberKeyMap.add(1, "one");
+ numberKeyMap.add(1, "uno");
+ numberKeyMap.add(2, "two");
+
+ expect(numberKeyMap.get(1)).toEqual(["one", "uno"]);
+ expect(numberKeyMap.get(2)).toEqual(["two"]);
+ expect(numberKeyMap.flatValues()).toEqual(["one", "uno", "two"]);
+ });
+
+ it("should work with object keys and values", () => {
+ interface TestObj {
+ id: number;
+ name: string;
+ }
+
+ const objMap = new MultiMap<string, TestObj>();
+ const obj1 = { id: 1, name: "test1" };
+ const obj2 = { id: 2, name: "test2" };
+
+ objMap.add("group1", obj1);
+ objMap.add("group1", obj2);
+
+ expect(objMap.get("group1")).toEqual([obj1, obj2]);
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle undefined and null values", () => {
+ const nullMap = new MultiMap<string, null | undefined>();
+ nullMap.add("key1", null);
+ nullMap.add("key1", undefined);
+
+ expect(nullMap.get("key1")).toEqual([null, undefined]);
+ });
+
+ it("should handle duplicate values", () => {
+ multiMap.add("key1", 1);
+ multiMap.add("key1", 1);
+ multiMap.add("key1", 1);
+
+ expect(multiMap.get("key1")).toEqual([1, 1, 1]);
+ });
+ });
+});
diff --git a/frontend/src/utils/multi-map.ts b/frontend/src/utils/multi-map.ts
new file mode 100644
index 0000000000..0f4ec98a34
--- /dev/null
+++ b/frontend/src/utils/multi-map.ts
@@ -0,0 +1,71 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+/**
+ * MultiMap: a Map<K, V[]> with convenient helpers.
+ */
+export class MultiMap<K, V> {
+ private map = new Map<K, V[]>();
+
+ get(key: K): V[] {
+ return this.map.get(key) ?? [];
+ }
+
+ set(key: K, values: V[]): void {
+ this.map.set(key, values);
+ }
+
+ add(key: K, value: V): void {
+ if (this.map.has(key)) {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ this.map.get(key)!.push(value);
+ } else {
+ this.map.set(key, [value]);
+ }
+ }
+
+ has(key: K): boolean {
+ return this.map.has(key);
+ }
+
+ delete(key: K): boolean {
+ return this.map.delete(key);
+ }
+
+ clear(): void {
+ this.map.clear();
+ }
+
+ keys(): IterableIterator<K> {
+ return this.map.keys();
+ }
+
+ values(): IterableIterator<V[]> {
+ return this.map.values();
+ }
+
+ entries(): IterableIterator<[K, V[]]> {
+ return this.map.entries();
+ }
+
+ forEach(callback: (values: V[], key: K, map: Map<K, V[]>) => void): void {
+ this.map.forEach(callback);
+ }
+
+ /**
+ * Flatten all values into a single array.
+ */
+ flatValues(): V[] {
+ const result: V[] = [];
+ for (const arr of this.map.values()) {
+ result.push(...arr);
+ }
+ return result;
+ }
+
+ /**
+ * Number of keys in the MultiMap.
+ */
+ get size(): number {
+ return this.map.size;
+ }
+}
diff --git a/packages/llm-info/README.md b/packages/llm-info/README.md
new file mode 100644
index 0000000000..a4ee0446e8
--- /dev/null
+++ b/packages/llm-info/README.md
@@ -0,0 +1,11 @@
+# LLM Info
+
+This package contains data for the LLM info.
+
+## Data
+
+Models and providers are stored in the `data` directory.
+
+## Adding a New LLM Model
+
+If you want to add a new LLM model or provider, you can do so by editing the YAML files in the `data` directory (`models.yaml` or `providers.yaml`) and running `pnpm codegen`.
\ No newline at end of file
diff --git a/packages/llm-info/icons/deepseek.svg b/packages/llm-info/icons/deepseek.svg
new file mode 100644
index 0000000000..dc224e43a4
--- /dev/null
+++ b/packages/llm-info/icons/deepseek.svg
@@ -0,0 +1 @@
+<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>DeepSeek</title><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z"></path></svg>
\ No newline at end of file
diff --git a/packages/llm-info/package.json b/packages/llm-info/package.json
index 5d072987b8..679187c00a 100644
--- a/packages/llm-info/package.json
+++ b/packages/llm-info/package.json
@@ -4,6 +4,9 @@
"private": true,
"type": "module",
"sideEffects": false,
+ "files": [
+ "data/generated/*.json"
+ ],
"exports": {
".": "./src/index.ts",
"./icons/*": "./icons/*",
diff --git a/packages/llm-info/src/__tests__/json-structure.test.ts b/packages/llm-info/src/__tests__/json-structure.test.ts
new file mode 100644
index 0000000000..522c9e49ff
--- /dev/null
+++ b/packages/llm-info/src/__tests__/json-structure.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+
+describe("JSON structure should be correct", async () => {
+ it("should have the correct structure, models should be an object", async () => {
+ const models = await import("../../data/generated/models.json");
+ expect(Array.isArray(models.models)).toBe(true);
+ });
+
+ it("should have the correct structure, providers should be an object", async () => {
+ const providers = await import("../../data/generated/providers.json");
+ expect(Array.isArray(providers.providers)).toBe(true);
+ });
+});
diff --git a/packages/llm-info/src/generate.ts b/packages/llm-info/src/generate.ts
index c833956cb5..4a2eea315e 100644
--- a/packages/llm-info/src/generate.ts
+++ b/packages/llm-info/src/generate.ts
@@ -6,12 +6,14 @@ import { fileURLToPath } from "node:url";
import { parse } from "yaml";
import { z } from "zod";
+const ROLES = ["chat", "edit", "rerank", "embed"] as const;
+
export const LLMInfoSchema = z.object({
name: z.string(),
model: z.string(),
description: z.string(),
providers: z.array(z.string()),
- roles: z.array(z.enum(["chat", "edit", "embed", "rerank"])),
+ roles: z.array(z.enum(ROLES)),
thinking: z.boolean().default(false),
});
@@ -29,8 +31,12 @@ function ensureDirectoryExists(filePath: string): void {
const dir = dirname(filePath);
try {
mkdirSync(dir, { recursive: true });
- } catch (error) {
- // Directory might already exist, that's okay
+ } catch (error: any) {
+ // Ignore error if directory already exists, otherwise rethrow
+ if (error?.code !== "EEXIST") {
+ console.error("Failed to create directory:", error);
+ throw error;
+ }
}
}
@@ -95,13 +101,17 @@ async function main(): Promise<void> {
const modelsJsonPath = join(generatedDir, "models.json");
const providersJsonPath = join(generatedDir, "providers.json");
+ // For compatibility with Vite and other bundlers, `import` returns a JS module and not a JSON object.
+ // So we need to nest the models and providers data under a json key to access them,
+ // otherwise a keyword can conflict with a JS reserved keyword (e.g. `default` or `with`).
+
// Load and validate models
const models = loadAndValidateModels(modelsYamlPath);
- writeJsonFile(modelsJsonPath, models);
+ writeJsonFile(modelsJsonPath, { models: models });
// Load and validate providers
const providers = loadAndValidateProviders(providersYamlPath);
- writeJsonFile(providersJsonPath, providers);
+ writeJsonFile(providersJsonPath, { providers: providers });
console.log(
`Generated ${models.length} models and ${providers.length} providers`,
diff --git a/packages/llm-info/src/index.ts b/packages/llm-info/src/index.ts
index 0a95af567d..730035e536 100644
--- a/packages/llm-info/src/index.ts
+++ b/packages/llm-info/src/index.ts
@@ -1,9 +1,18 @@
+export const ROLES = [
+ "chat",
+ "edit",
+ "rerank",
+ "embed",
+ "autocomplete",
+] as const;
+export type Role = (typeof ROLES)[number];
+
export interface AiModel {
name: string;
model: string;
description: string;
providers: string[];
- roles: string[];
+ roles: Role[];
thinking: boolean;
}
diff --git a/turbo.json b/turbo.json
index 42ca8c70b8..d8612accee 100644
--- a/turbo.json
+++ b/turbo.json
@@ -5,7 +5,9 @@
"dependsOn": ["^build", "codegen"],
"outputs": ["dist/**"]
},
- "typecheck": {},
+ "typecheck": {
+ "dependsOn": ["codegen", "^codegen"]
+ },
"test": {
"dependsOn": ["build"]
},