Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
settings_ui: Add OpenAI/Anthropic API-compatible provider form (#60195)
Bennet Bo Fenner15c31d4147fe
diff --git a/crates/language_models/src/provider/anthropic_compatible.rs b/crates/language_models/src/provider/anthropic_compatible.rsindex 38f31d2d7a8..b0790045324 100644--- a/crates/language_models/src/provider/anthropic_compatible.rs+++ b/crates/language_models/src/provider/anthropic_compatible.rs@@ -199,6 +199,11 @@ impl LanguageModelProvider for AnthropicCompatibleLanguageModelProvider {.into()}+ fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {+ self.state+ .update(cx, |state, cx| state.set_api_key(Some(key), cx))+ }+fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {self.state.update(cx, |state, cx| state.set_api_key(None, cx))diff --git a/crates/language_models/src/provider/api_compatible.rs b/crates/language_models/src/provider/api_compatible.rsindex e186f0baf95..f8b4e731c8f 100644--- a/crates/language_models/src/provider/api_compatible.rs+++ b/crates/language_models/src/provider/api_compatible.rs@@ -178,6 +178,23 @@ impl<S: ApiCompatibleProviderSettings> ApiCompatibleProviderConfigurationView<S>.detach_and_log_err(cx);}+ fn remove_provider(&mut self, _: &mut Window, cx: &mut Context<Self>) {+ let id = self.state.read(cx).id.clone();+ let fs = <dyn fs::Fs>::global(cx);+ settings::update_settings_file(fs, cx, move |settings, _| {+ let Some(language_models) = settings.language_models.as_mut() else {+ return;+ };++ if let Some(providers) = language_models.openai_compatible.as_mut() {+ providers.remove(id.as_ref());+ }+ if let Some(providers) = language_models.anthropic_compatible.as_mut() {+ providers.remove(id.as_ref());+ }+ });+ }+fn should_render_editor(&self, cx: &Context<Self>) -> bool {!self.state.read(cx).is_authenticated()}@@ -256,7 +273,26 @@ impl<S: ApiCompatibleProviderSettings> Render for ApiCompatibleProviderConfiguraif self.load_credentials_task.is_some() {div().child(Label::new("Loading credentials…")).into_any()} else {- v_flex().size_full().child(api_key_section).into_any()+ v_flex()+ .size_full()+ .gap_4()+ .child(api_key_section)+ .child(+ h_flex().w_full().justify_end().child(+ Button::new("remove-compatible-provider", "Remove Provider")+ .style(ButtonStyle::OutlinedGhost)+ .label_size(LabelSize::Small)+ .start_icon(+ Icon::new(IconName::Trash)+ .size(IconSize::Small)+ .color(Color::Muted),+ )+ .on_click(cx.listener(|this, _event, window, cx| {+ this.remove_provider(window, cx)+ })),+ ),+ )+ .into_any()}}}diff --git a/crates/language_models/src/provider/open_ai_compatible.rs b/crates/language_models/src/provider/open_ai_compatible.rsindex 847978b7955..e0c6f1f16ea 100644--- a/crates/language_models/src/provider/open_ai_compatible.rs+++ b/crates/language_models/src/provider/open_ai_compatible.rs@@ -162,6 +162,11 @@ impl LanguageModelProvider for OpenAiCompatibleLanguageModelProvider {.into()}+ fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {+ self.state+ .update(cx, |state, cx| state.set_api_key(Some(key), cx))+ }+fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {self.state.update(cx, |state, cx| state.set_api_key(None, cx))diff --git a/crates/settings_ui/src/pages.rs b/crates/settings_ui/src/pages.rsindex 407343365ea..6038a5eaa16 100644--- a/crates/settings_ui/src/pages.rs+++ b/crates/settings_ui/src/pages.rs@@ -19,7 +19,9 @@ pub(crate) use external_agents_page::{CustomAgentForm, render_add_agent_popover, render_external_agents_page,};pub(crate) use feature_flags::render_feature_flags_page;-pub(crate) use llm_providers_page::render_llm_providers_page;+pub(crate) use llm_providers_page::{+ LlmProviderForm, render_add_llm_provider_popover, render_llm_providers_page,+};pub(crate) use mcp_servers_page::{McpServerForm, render_add_server_popover, render_mcp_servers_page,};diff --git a/crates/settings_ui/src/pages/llm_providers_page.rs b/crates/settings_ui/src/pages/llm_providers_page.rsindex cb0b0a95b99..f888b031eb8 100644--- a/crates/settings_ui/src/pages/llm_providers_page.rs+++ b/crates/settings_ui/src/pages/llm_providers_page.rs@@ -1,12 +1,23 @@-use std::sync::Arc;+use std::{collections::HashSet, sync::Arc};-use gpui::{AnyView, ScrollHandle, prelude::*};+use editor::Editor;+use gpui::{AnyView, Entity, Focusable as _, ScrollHandle, prelude::*};use language_model::{ApiKeyConfiguration, ConfigurationViewTargetAgent, IconOrSvg, InlineDescription,LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry,ProviderConfigurationView,};-use ui::{ButtonLink, ConfiguredApiCard, Divider, DividerColor, prelude::*};++use settings::{+ AnthropicCompatibleAvailableModel, AnthropicCompatibleModelCapabilities,+ AnthropicCompatibleSettingsContent, OpenAiCompatibleAvailableModel,+ OpenAiCompatibleModelCapabilities, OpenAiCompatibleSettingsContent, OpenAiReasoningEffort,+};+use ui::{+ ButtonLink, Checkbox, ConfiguredApiCard, ContextMenu, Divider, DividerColor, DropdownMenu,+ DropdownStyle, IconPosition, PopoverMenu, ToggleState, prelude::*,+};+use util::ResultExt as _;use crate::SettingsWindow;use crate::components::SettingsInputField;@@ -38,6 +49,96 @@ pub(crate) fn render_llm_providers_page(.into_any_element()}+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum CompatibleProviderKind {+ OpenAi,+ Anthropic,+}++impl CompatibleProviderKind {+ fn label(self) -> &'static str {+ match self {+ Self::OpenAi => "OpenAI",+ Self::Anthropic => "Anthropic",+ }+ }++ fn default_api_url(self) -> &'static str {+ match self {+ Self::OpenAi => "https://api.openai.com/v1",+ Self::Anthropic => "https://api.anthropic.com",+ }+ }+}++pub(crate) fn render_add_llm_provider_popover(+ settings_window: &SettingsWindow,+ _window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) -> impl IntoElement {+ let focus_handle = settings_window+ .llm_provider_add_focus_handle+ .clone()+ .tab_index(0)+ .tab_stop(true);++ let settings_window = cx.entity().downgrade();++ PopoverMenu::new("add-llm-provider-popover")+ .trigger(+ Button::new("add-llm-provider", "Add Provider")+ .style(ButtonStyle::Outlined)+ .track_focus(&focus_handle)+ .label_size(LabelSize::Small)+ .start_icon(+ Icon::new(IconName::Plus)+ .size(IconSize::Small)+ .color(Color::Muted),+ ),+ )+ .anchor(gpui::Anchor::TopRight)+ .offset(gpui::Point {+ x: px(0.0),+ y: px(2.0),+ })+ .menu(move |window, cx| {+ let settings_window = settings_window.clone();+ Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {+ menu.header("Compatible APIs")+ .entry("OpenAI", None, {+ let settings_window = settings_window.clone();+ move |window, cx| {+ settings_window+ .update(cx, |this, cx| {+ open_llm_provider_form(+ this,+ CompatibleProviderKind::OpenAi,+ window,+ cx,+ );+ })+ .log_err();+ }+ })+ .entry("Anthropic", None, {+ let settings_window = settings_window;+ move |window, cx| {+ settings_window+ .update(cx, |this, cx| {+ open_llm_provider_form(+ this,+ CompatibleProviderKind::Anthropic,+ window,+ cx,+ );+ })+ .log_err();+ }+ })+ }))+ })+}+fn render_provider_section(settings_window: &SettingsWindow,provider: &Arc<dyn LanguageModelProvider>,@@ -49,7 +150,7 @@ fn render_provider_section(let provider_name = provider.name().0;let body = if let Some(config) = provider.api_key_configuration(cx) {- render_api_key_providers_item(provider, provider_name.clone(), config)+ render_api_key_providers_item(settings_window, provider, provider_name.clone(), config, cx)} else {match get_or_create_configuration_view(settings_window, &provider_id, provider, window, cx){@@ -95,9 +196,11 @@ fn render_provider_header(}fn render_api_key_providers_item(+ _settings_window: &SettingsWindow,provider: &Arc<dyn LanguageModelProvider>,provider_name: SharedString,config: ApiKeyConfiguration,+ _cx: &mut Context<SettingsWindow>,) -> AnyElement {let ApiKeyConfiguration {has_key,@@ -113,83 +216,95 @@ fn render_api_key_providers_item("API Key Configured"};let button_id = format!("reset-api-key-{}", provider.id().0);- let provider = provider.clone();- let env_var_name_for_tooltip = env_var_name;- return ConfiguredApiCard::new(button_id, configured_label)+ let card = ConfiguredApiCard::new(button_id, configured_label).button_label("Reset Key").button_tab_index(0).disabled(is_from_env_var).when(is_from_env_var, |this| {this.tooltip_label(format!(- "To reset your API key, unset the {env_var_name_for_tooltip} environment variable."+ "To reset your API key, unset the {env_var_name} environment variable."))})- .on_click(move |_, _, cx| {- provider.reset_credentials(cx).detach_and_log_err(cx);+ .on_click({+ let provider = provider.clone();+ move |_, _, cx| {+ provider.reset_credentials(cx).detach_and_log_err(cx);+ }}).into_any_element();++ return v_flex().gap_2().child(card).into_any_element();}let input_id = format!("{}-api-key-input", provider.id().0);let aria_label = format!("{provider_name} API Key");- let provider = provider.clone();- h_flex()- .pt_2p5()- .w_full()- .min_w_0()- .gap_4()- .justify_between()+ v_flex()+ .gap_2().child(- v_flex()+ h_flex()+ .pt_2p5().w_full().min_w_0()- .max_w_1_2()- .gap_0p5()- .child(Label::new("API Key"))+ .gap_4()+ .justify_between().child(- h_flex()+ v_flex().w_full().min_w_0()- .flex_wrap()+ .max_w_1_2().gap_0p5()+ .child(Label::new("API Key")).child(- Label::new("Visit the")- .size(LabelSize::Small)- .color(Color::Muted),- )- .child(- ButtonLink::new(format!("{provider_name} dashboard"), api_key_url)- .no_icon(true)- .label_size(LabelSize::Small)- .label_color(Color::Muted),+ h_flex()+ .w_full()+ .min_w_0()+ .flex_wrap()+ .gap_0p5()+ .child(+ Label::new("Visit the")+ .size(LabelSize::Small)+ .color(Color::Muted),+ )+ .child(+ ButtonLink::new(+ format!("{provider_name} dashboard"),+ api_key_url,+ )+ .no_icon(true)+ .label_size(LabelSize::Small)+ .label_color(Color::Muted),+ )+ .child(+ Label::new("to generate an API key.")+ .size(LabelSize::Small)+ .color(Color::Muted),+ ),).child(- Label::new("to generate an API key.")- .size(LabelSize::Small)- .color(Color::Muted),+ Label::new(format!(+ "Or set the {env_var_name} env var and restart Zed for it to take effect."+ ))+ .size(LabelSize::XSmall)+ .color(Color::Muted),),).child(- Label::new(format!(- "Or set the {env_var_name} env var and restart Zed for it to take effect."- ))- .size(LabelSize::XSmall)- .color(Color::Muted),+ SettingsInputField::new(input_id)+ .tab_index(0)+ .with_placeholder("xxxxxxxxxxxxxxxxxxxx")+ .aria_label(aria_label)+ .on_confirm({+ let provider = provider.clone();+ move |api_key, _window, cx| {+ if let Some(key) = api_key.filter(|key| !key.is_empty()) {+ provider.set_api_key(key, cx).detach_and_log_err(cx);+ }+ }+ }),),)- .child(- SettingsInputField::new(input_id)- .tab_index(0)- .with_placeholder("xxxxxxxxxxxxxxxxxxxx")- .aria_label(aria_label)- .on_confirm(move |api_key, _window, cx| {- if let Some(key) = api_key.filter(|key| !key.is_empty()) {- provider.set_api_key(key, cx).detach_and_log_err(cx);- }- }),- ).into_any_element()}@@ -314,7 +429,7 @@ fn open_provider_configuration(title,"Agent Configuration",Some("llm_providers"),- false,+ true,render_provider_config_sub_page,window,cx,@@ -385,3 +500,807 @@ fn get_or_create_configuration_view(view}++pub(crate) struct LlmProviderForm {+ kind: CompatibleProviderKind,+ provider_name: Entity<Editor>,+ api_url: Entity<Editor>,+ api_key: Entity<Editor>,+ models: Vec<ModelInput>,+ error: Option<SharedString>,+}++impl LlmProviderForm {+ fn new(+ kind: CompatibleProviderKind,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+ ) -> Self {+ Self {+ kind,+ provider_name: new_input(kind.label(), None, false, window, cx),+ api_url: new_input(kind.default_api_url(), None, false, window, cx),+ api_key: new_input(+ "000000000000000000000000000000000000000000000000",+ None,+ true,+ window,+ cx,+ ),+ models: vec![ModelInput::new(0, window, cx)],+ error: None,+ }+ }+}++struct ModelInput {+ name: Entity<Editor>,+ max_completion_tokens: Entity<Editor>,+ max_output_tokens: Entity<Editor>,+ max_tokens: Entity<Editor>,+ reasoning_effort: OpenAiReasoningEffort,+ supports_tools: ToggleState,+ supports_images: ToggleState,+ supports_parallel_tool_calls: ToggleState,+ supports_prompt_cache_key: ToggleState,+ supports_chat_completions: ToggleState,+ supports_thinking: ToggleState,+ interleaved_reasoning: ToggleState,+ max_tokens_parameter: ToggleState,+}++impl ModelInput {+ fn new(_index: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) -> Self {+ let OpenAiCompatibleModelCapabilities {+ tools,+ images,+ parallel_tool_calls,+ prompt_cache_key,+ chat_completions,+ interleaved_reasoning,+ max_tokens_parameter,+ } = OpenAiCompatibleModelCapabilities::default();++ Self {+ name: new_input(+ "e.g. gpt-5, claude-opus-4, gemini-2.5-pro",+ None,+ false,+ window,+ cx,+ ),+ max_completion_tokens: new_input("200000", Some("200000"), false, window, cx),+ max_output_tokens: new_input("Max Output Tokens", Some("32000"), false, window, cx),+ max_tokens: new_input("Max Tokens", Some("200000"), false, window, cx),+ reasoning_effort: OpenAiReasoningEffort::Medium,+ supports_tools: tools.into(),+ supports_images: images.into(),+ supports_parallel_tool_calls: parallel_tool_calls.into(),+ supports_prompt_cache_key: prompt_cache_key.into(),+ supports_chat_completions: chat_completions.into(),+ supports_thinking: ToggleState::Unselected,+ interleaved_reasoning: interleaved_reasoning.into(),+ max_tokens_parameter: max_tokens_parameter.into(),+ }+ }+}++fn new_input(+ placeholder: &str,+ initial: Option<&str>,+ masked: bool,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) -> Entity<Editor> {+ let placeholder = placeholder.to_string();+ let initial = initial.map(str::to_string);+ cx.new(|cx| {+ let mut editor = Editor::single_line(window, cx);+ editor.set_placeholder_text(placeholder.as_str(), window, cx);+ editor.set_masked(masked, cx);+ if let Some(text) = initial {+ editor.set_text(text, window, cx);+ }+ editor+ })+}++fn open_llm_provider_form(+ settings_window: &mut SettingsWindow,+ kind: CompatibleProviderKind,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) {+ settings_window.llm_provider_form = Some(LlmProviderForm::new(kind, window, cx));+ settings_window.push_dynamic_sub_page(+ format!("Add {}-Compatible Provider", kind.label()),+ "Agent Configuration",+ Some("llm_providers"),+ true,+ render_llm_provider_form_page,+ window,+ cx,+ );+}++fn render_llm_provider_form_page(+ settings_window: &SettingsWindow,+ scroll_handle: &ScrollHandle,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) -> AnyElement {+ let Some(form) = settings_window.llm_provider_form.as_ref() else {+ return div().into_any_element();+ };++ v_flex()+ .size_full()+ .child(+ v_flex()+ .id("llm-provider-form-page")+ .track_scroll(scroll_handle)+ .pt_2p5()+ .px_8()+ .pb_16()+ .gap_4()+ .overflow_y_scroll()+ .child(Label::new(match form.kind {+ CompatibleProviderKind::OpenAi => {+ "This provider will use an OpenAI-compatible API."+ }+ CompatibleProviderKind::Anthropic => {+ "This provider will use an Anthropic Messages-compatible API."+ }+ }))+ .child(Divider::horizontal().flex_shrink_0())+ .child(render_form_field(+ "Provider Name",+ "A unique name used to identify this provider.",+ &form.provider_name,+ cx,+ ))+ .child(render_form_field(+ "API URL",+ "The base URL for the compatible API.",+ &form.api_url,+ cx,+ ))+ .child(render_form_field(+ "API Key",+ "Stored in the system keychain, not in settings.json.",+ &form.api_key,+ cx,+ ))+ .child(render_models_section(form, window, cx)),+ )+ .child(+ v_flex()+ .px_8()+ .py_2p5()+ .gap_1()+ .border_t_1()+ .border_color(cx.theme().colors().border_variant)+ .when_some(form.error.clone(), |this, error| {+ this.child(render_form_error(error))+ })+ .child(render_form_actions(cx)),+ )+ .into_any_element()+}++fn render_form_field(+ title: &'static str,+ description: &'static str,+ editor: &Entity<Editor>,+ cx: &mut Context<SettingsWindow>,+) -> AnyElement {+ let colors = cx.theme().colors();+ let focus_handle = editor.focus_handle(cx).tab_index(0).tab_stop(true);+ v_flex()+ .w_full()+ .gap_1p5()+ .child(+ v_flex()+ .gap_0p5()+ .child(+ h_flex().gap_0p5().child(Label::new(title)).child(+ Label::new("*")+ .size(LabelSize::Small)+ .color(Color::Error)+ .mb_2(),+ ),+ )+ .child(+ Label::new(description)+ .size(LabelSize::Small)+ .color(Color::Muted),+ ),+ )+ .child(+ h_flex()+ .w_full()+ .min_w_64()+ .h_8()+ .px_2()+ .rounded_md()+ .border_1()+ .border_color(colors.border)+ .bg(colors.editor_background)+ .track_focus(&focus_handle)+ .focus(|style| style.border_color(colors.border_focused))+ .child(editor.clone()),+ )+ .into_any_element()+}++fn render_models_section(+ form: &LlmProviderForm,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) -> impl IntoElement {+ v_flex()+ .mt_1()+ .gap_2()+ .child(+ h_flex()+ .justify_between()+ .child(Label::new("Models"))+ .child(+ Button::new("add-model", "Add Model")+ .start_icon(+ Icon::new(IconName::Plus)+ .size(IconSize::XSmall)+ .color(Color::Muted),+ )+ .label_size(LabelSize::Small)+ .on_click(cx.listener(|this, _, window, cx| {+ if let Some(form) = this.llm_provider_form.as_mut() {+ let index = form.models.len();+ form.models.push(ModelInput::new(index, window, cx));+ }+ cx.notify();+ })),+ ),+ )+ .children(form.models.iter().enumerate().map(|(index, model)| {+ render_model(form.kind, model, index, form.models.len(), window, cx)+ }))+}++fn render_model(+ kind: CompatibleProviderKind,+ model: &ModelInput,+ index: usize,+ model_count: usize,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) -> AnyElement {+ v_flex()+ .p_2()+ .gap_2()+ .rounded_sm()+ .border_1()+ .border_dashed()+ .border_color(cx.theme().colors().border.opacity(0.6))+ .bg(cx.theme().colors().element_active.opacity(0.15))+ .child(render_form_field(+ "Model Name",+ "The model's name in the provider's API.",+ &model.name,+ cx,+ ))+ .when(matches!(kind, CompatibleProviderKind::OpenAi), |this| {+ this.child(render_form_field(+ "Max Completion Tokens",+ "Maximum completion tokens for OpenAI-compatible requests.",+ &model.max_completion_tokens,+ cx,+ ))+ })+ .child(render_form_field(+ "Max Output Tokens",+ "The maximum number of tokens the model can output.",+ &model.max_output_tokens,+ cx,+ ))+ .child(render_form_field(+ "Max Tokens",+ "The model context window size.",+ &model.max_tokens,+ cx,+ ))+ .child(render_model_capabilities(kind, model, index, window, cx))+ .when(model_count > 1, |this| {+ this.child(+ Button::new(("remove-model", index), "Remove Model")+ .start_icon(+ Icon::new(IconName::Trash)+ .size(IconSize::XSmall)+ .color(Color::Muted),+ )+ .label_size(LabelSize::Small)+ .style(ButtonStyle::Outlined)+ .full_width()+ .on_click(cx.listener(move |this, _, _window, cx| {+ if let Some(form) = this.llm_provider_form.as_mut()+ && index < form.models.len()+ {+ form.models.remove(index);+ }+ cx.notify();+ })),+ )+ })+ .into_any_element()+}++fn render_model_capabilities(+ kind: CompatibleProviderKind,+ model: &ModelInput,+ index: usize,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) -> impl IntoElement {+ v_flex()+ .gap_1()+ .child(render_capability_checkbox(+ "supports-tools",+ index,+ "Supports tools",+ model.supports_tools,+ |model, state| model.supports_tools = state,+ cx,+ ))+ .child(render_capability_checkbox(+ "supports-images",+ index,+ "Supports images",+ model.supports_images,+ |model, state| model.supports_images = state,+ cx,+ ))+ .when(matches!(kind, CompatibleProviderKind::OpenAi), |this| {+ this.child(render_capability_checkbox(+ "supports-parallel-tool-calls",+ index,+ "Supports parallel_tool_calls",+ model.supports_parallel_tool_calls,+ |model, state| model.supports_parallel_tool_calls = state,+ cx,+ ))+ .child(render_capability_checkbox(+ "supports-prompt-cache-key",+ index,+ "Supports prompt_cache_key",+ model.supports_prompt_cache_key,+ |model, state| model.supports_prompt_cache_key = state,+ cx,+ ))+ .child(render_capability_checkbox(+ "supports-chat-completions",+ index,+ "Supports /chat/completions",+ model.supports_chat_completions,+ |model, state| model.supports_chat_completions = state,+ cx,+ ))+ .when(model.supports_chat_completions.selected(), |this| {+ this.child(render_capability_checkbox(+ "max-tokens-parameter",+ index,+ "Uses max_tokens for output limit",+ model.max_tokens_parameter,+ |model, state| model.max_tokens_parameter = state,+ cx,+ ))+ })+ .child(render_capability_checkbox(+ "supports-thinking",+ index,+ "Supports thinking",+ model.supports_thinking,+ |model, state| model.supports_thinking = state,+ cx,+ ))+ .when(model.supports_thinking.selected(), |this| {+ this.child(render_reasoning_effort_selector(+ model.reasoning_effort,+ index,+ window,+ cx,+ ))+ .when(model.supports_chat_completions.selected(), |this| {+ this.child(render_capability_checkbox(+ "interleaved-reasoning",+ index,+ "Preserves thinking in chat history",+ model.interleaved_reasoning,+ |model, state| model.interleaved_reasoning = state,+ cx,+ ))+ })+ })+ })+}++fn render_capability_checkbox(+ id: &'static str,+ index: usize,+ label: &'static str,+ state: ToggleState,+ update: fn(&mut ModelInput, ToggleState),+ cx: &mut Context<SettingsWindow>,+) -> impl IntoElement {+ Checkbox::new((id, index), state)+ .label(label)+ .on_click(cx.listener(move |this, checked, _window, cx| {+ if let Some(form) = this.llm_provider_form.as_mut()+ && let Some(model) = form.models.get_mut(index)+ {+ update(model, *checked);+ }+ cx.notify();+ }))+}++fn render_reasoning_effort_selector(+ selected: OpenAiReasoningEffort,+ index: usize,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) -> impl IntoElement {+ let settings_window = cx.weak_entity();+ let menu = ContextMenu::build(window, cx, move |mut menu, _window, _cx| {+ for effort in OpenAiReasoningEffort::OPENAI_COMPATIBLE_SELECTABLE {+ let is_selected = effort == selected;+ let settings_window = settings_window.clone();+ menu.push_item(+ ui::ContextMenuEntry::new(effort.label())+ .toggleable(IconPosition::End, is_selected)+ .handler(move |_window, cx| {+ settings_window+ .update(cx, |this, cx| {+ if let Some(form) = this.llm_provider_form.as_mut()+ && let Some(model) = form.models.get_mut(index)+ {+ model.reasoning_effort = effort;+ }+ cx.notify();+ })+ .ok();+ }),+ );+ }+ menu+ });++ v_flex()+ .gap_1()+ .child(Label::new("Default reasoning effort").size(LabelSize::Small))+ .child(+ DropdownMenu::new(+ ElementId::Name(format!("reasoning-effort-selector-{index}").into()),+ selected.label(),+ menu,+ )+ .style(DropdownStyle::Outlined)+ .trigger_size(ButtonSize::Compact)+ .full_width(true)+ .aria_label("Default reasoning effort"),+ )+}++fn render_form_error(error: SharedString) -> impl IntoElement {+ h_flex()+ .w_full()+ .gap_2()+ .child(+ Icon::new(IconName::XCircle)+ .size(IconSize::Small)+ .color(Color::Error),+ )+ .child(Label::new(error).size(LabelSize::Small).color(Color::Error))+}++fn render_form_actions(cx: &mut Context<SettingsWindow>) -> impl IntoElement {+ h_flex()+ .w_full()+ .gap_1()+ .justify_end()+ .child(+ Button::new("llm-provider-form-cancel", "Cancel").on_click(cx.listener(+ |this, _, window, cx| {+ this.llm_provider_form = None;+ this.pop_sub_page(window, cx);+ },+ )),+ )+ .child(+ Button::new("llm-provider-form-save", "Save Provider")+ .style(ButtonStyle::Filled)+ .on_click(cx.listener(|this, _, window, cx| {+ save_llm_provider_form(this, window, cx);+ })),+ )+}++struct LlmProviderFormValues {+ kind: CompatibleProviderKind,+ provider_name: String,+ api_url: String,+ api_key: String,+ models: Vec<ModelValues>,+}++struct ModelValues {+ name: String,+ max_completion_tokens: String,+ max_output_tokens: String,+ max_tokens: String,+ reasoning_effort: OpenAiReasoningEffort,+ supports_tools: bool,+ supports_images: bool,+ supports_parallel_tool_calls: bool,+ supports_prompt_cache_key: bool,+ supports_chat_completions: bool,+ supports_thinking: bool,+ interleaved_reasoning: bool,+ max_tokens_parameter: bool,+}++enum ParsedModels {+ OpenAi(Vec<OpenAiCompatibleAvailableModel>),+ Anthropic(Vec<AnthropicCompatibleAvailableModel>),+}++fn save_llm_provider_form(+ settings_window: &mut SettingsWindow,+ window: &mut Window,+ cx: &mut Context<SettingsWindow>,+) {+ let values = {+ let Some(form) = settings_window.llm_provider_form.as_ref() else {+ return;+ };+ LlmProviderFormValues {+ kind: form.kind,+ provider_name: form.provider_name.read(cx).text(cx),+ api_url: form.api_url.read(cx).text(cx),+ api_key: form.api_key.read(cx).text(cx),+ models: form+ .models+ .iter()+ .map(|model| ModelValues {+ name: model.name.read(cx).text(cx),+ max_completion_tokens: model.max_completion_tokens.read(cx).text(cx),+ max_output_tokens: model.max_output_tokens.read(cx).text(cx),+ max_tokens: model.max_tokens.read(cx).text(cx),+ reasoning_effort: model.reasoning_effort,+ supports_tools: model.supports_tools.selected(),+ supports_images: model.supports_images.selected(),+ supports_parallel_tool_calls: model.supports_parallel_tool_calls.selected(),+ supports_prompt_cache_key: model.supports_prompt_cache_key.selected(),+ supports_chat_completions: model.supports_chat_completions.selected(),+ supports_thinking: model.supports_thinking.selected(),+ interleaved_reasoning: model.interleaved_reasoning.selected(),+ max_tokens_parameter: model.max_tokens_parameter.selected(),+ })+ .collect(),+ }+ };++ let (provider_name, api_url, api_key, models) = match validate_llm_provider_form(&values, cx) {+ Ok(value) => value,+ Err(error) => {+ if let Some(form) = settings_window.llm_provider_form.as_mut() {+ form.error = Some(error);+ }+ cx.notify();+ return;+ }+ };++ let fs = <dyn fs::Fs>::global(cx);+ cx.spawn_in(window, async move |this, cx| {+ let result = async {+ let provider_id = LanguageModelProviderId(provider_name.clone().into());+ let settings_update = cx.update(|_window, cx| {+ settings::update_settings_file_with_completion(fs, cx, move |settings, _cx| {+ let language_models = settings.language_models.get_or_insert_default();+ match models {+ ParsedModels::OpenAi(available_models) => {+ language_models+ .openai_compatible+ .get_or_insert_default()+ .insert(+ Arc::from(provider_name.as_str()),+ OpenAiCompatibleSettingsContent {+ api_url: api_url.clone(),+ available_models,+ custom_headers: None,+ },+ );+ }+ ParsedModels::Anthropic(available_models) => {+ language_models+ .anthropic_compatible+ .get_or_insert_default()+ .insert(+ Arc::from(provider_name.as_str()),+ AnthropicCompatibleSettingsContent {+ api_url: api_url.clone(),+ available_models,+ custom_headers: None,+ },+ );+ }+ }+ })+ })?;++ settings_update+ .await+ .map_err(|_| anyhow::anyhow!("Settings update was canceled"))??;++ let set_api_key = cx.update(|_window, cx| {+ let provider = LanguageModelRegistry::read_global(cx)+ .provider(&provider_id)+ .ok_or_else(|| anyhow::anyhow!("Provider was not registered"))?;+ anyhow::Ok(provider.set_api_key(api_key, cx))+ })??;+ set_api_key.await?;++ cx.update(|window, cx| {+ this.update(cx, |this, cx| {+ this.provider_configuration_views.remove(&provider_id);+ this.llm_provider_form = None;+ this.pop_sub_page(window, cx);+ })+ })??;++ anyhow::Ok(())+ }+ .await;++ if let Err(error) = result {+ this.update(cx, |this, cx| {+ if let Some(form) = this.llm_provider_form.as_mut() {+ form.error = Some(error.to_string().into());+ }+ cx.notify();+ })?;+ }++ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+}++fn validate_llm_provider_form(+ values: &LlmProviderFormValues,+ cx: &App,+) -> Result<(String, String, String, ParsedModels), SharedString> {+ let provider_name = values.provider_name.clone();+ if provider_name.is_empty() {+ return Err("Provider Name cannot be empty".into());+ }++ if LanguageModelRegistry::read_global(cx)+ .providers()+ .iter()+ .any(|provider| {+ provider.id().0.as_ref() == provider_name.as_str()+ || provider.name().0.as_ref() == provider_name.as_str()+ })+ {+ return Err("Provider Name is already taken by another provider".into());+ }++ let api_url = values.api_url.clone();+ if api_url.is_empty() {+ return Err("API URL cannot be empty".into());+ }++ let api_key = values.api_key.clone();+ if api_key.is_empty() {+ return Err("API Key cannot be empty".into());+ }++ let models = match values.kind {+ CompatibleProviderKind::OpenAi => ParsedModels::OpenAi(+ values+ .models+ .iter()+ .map(parse_open_ai_model)+ .collect::<Result<Vec<_>, _>>()?,+ ),+ CompatibleProviderKind::Anthropic => ParsedModels::Anthropic(+ values+ .models+ .iter()+ .map(parse_anthropic_model)+ .collect::<Result<Vec<_>, _>>()?,+ ),+ };++ let mut model_names = HashSet::new();+ let model_names_are_unique = match &models {+ ParsedModels::OpenAi(models) => models+ .iter()+ .all(|model| model_names.insert(model.name.clone())),+ ParsedModels::Anthropic(models) => models+ .iter()+ .all(|model| model_names.insert(model.name.clone())),+ };+ if !model_names_are_unique {+ return Err("Model Names must be unique".into());+ }++ Ok((provider_name, api_url, api_key, models))+}++fn parse_model_name(model: &ModelValues) -> Result<String, SharedString> {+ if model.name.is_empty() {+ return Err("Model Name cannot be empty".into());+ }+ Ok(model.name.clone())+}++fn parse_open_ai_model(+ model: &ModelValues,+) -> Result<OpenAiCompatibleAvailableModel, SharedString> {+ Ok(OpenAiCompatibleAvailableModel {+ name: parse_model_name(model)?,+ display_name: None,+ max_completion_tokens: Some(parse_u64_field(+ &model.max_completion_tokens,+ "Max Completion Tokens",+ )?),+ max_output_tokens: Some(parse_u64_field(+ &model.max_output_tokens,+ "Max Output Tokens",+ )?),+ max_tokens: parse_u64_field(&model.max_tokens, "Max Tokens")?,+ reasoning_effort: model.supports_thinking.then_some(model.reasoning_effort),+ capabilities: OpenAiCompatibleModelCapabilities {+ tools: model.supports_tools,+ images: model.supports_images,+ parallel_tool_calls: model.supports_parallel_tool_calls,+ prompt_cache_key: model.supports_prompt_cache_key,+ chat_completions: model.supports_chat_completions,+ interleaved_reasoning: model.supports_thinking+ && model.supports_chat_completions+ && model.interleaved_reasoning,+ max_tokens_parameter: model.supports_chat_completions && model.max_tokens_parameter,+ },+ })+}++fn parse_anthropic_model(+ model: &ModelValues,+) -> Result<AnthropicCompatibleAvailableModel, SharedString> {+ Ok(AnthropicCompatibleAvailableModel {+ name: parse_model_name(model)?,+ display_name: None,+ max_tokens: parse_u64_field(&model.max_tokens, "Max Tokens")?,+ tool_override: None,+ max_output_tokens: Some(parse_u64_field(+ &model.max_output_tokens,+ "Max Output Tokens",+ )?),+ default_temperature: None,+ extra_beta_headers: Vec::new(),+ mode: None,+ capabilities: AnthropicCompatibleModelCapabilities {+ tools: model.supports_tools,+ images: model.supports_images,+ prompt_caching: false,+ },+ })+}++fn parse_u64_field(value: &str, name: &str) -> Result<u64, SharedString> {+ value+ .parse::<u64>()+ .map_err(|_| format!("{name} must be a number").into())+}diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rsindex b371fb68ccb..34a2ac271d4 100644--- a/crates/settings_ui/src/settings_ui.rs+++ b/crates/settings_ui/src/settings_ui.rs@@ -60,7 +60,7 @@ use crate::components::{text_field_a11y_state, theme_picker,};use crate::pages::{- CustomAgentForm, McpServerForm, render_input_audio_device_dropdown,+ CustomAgentForm, LlmProviderForm, McpServerForm, render_input_audio_device_dropdown,render_output_audio_device_dropdown,};@@ -957,6 +957,12 @@ pub struct SettingsWindow {/// Directory path of the skill whose share link was most recently copied,/// used to show a transient "copied" checkmark on its share button.pub(crate) last_copied_skill_directory_path: Option<PathBuf>,+ /// State for the active "add OpenAI/Anthropic-compatible provider" form sub-page, if open.+ pub(crate) llm_provider_form: Option<LlmProviderForm>,+ /// Stable focus handle for the LLM "Add Provider" button, so it can show a+ /// focus ring when the page auto-focuses it on open (which happens via mouse,+ /// where `focus_visible` styling would otherwise be suppressed).+ pub(crate) llm_provider_add_focus_handle: FocusHandle,/// State for the active "add/edit custom MCP server" form sub-page, if open.pub(crate) mcp_server_form: Option<McpServerForm>,/// Stable focus handle for the MCP "Add Server" button, so it can show a@@ -1983,6 +1989,8 @@ impl SettingsWindow {provider_configuration_views: HashMap::default(),configuring_provider: None,last_copied_skill_directory_path: None,+ llm_provider_form: None,+ llm_provider_add_focus_handle: cx.focus_handle(),mcp_server_form: None,mcp_add_server_focus_handle: cx.focus_handle(),custom_agent_form: None,@@ -3707,6 +3715,8 @@ impl SettingsWindow {if let Some(current_sub_page) = self.sub_page_stack.last() {let is_skills_page =current_sub_page.link.json_path == Some(AGENT_SKILLS_SETTINGS_PATH);+ let is_llm_providers_page = current_sub_page.link.json_path == Some("llm_providers")+ && current_sub_page.link.title.as_ref() == "LLM Providers";let is_external_agents_page = current_sub_page.link.json_path == Some("agent_servers");let is_mcp_servers_page = current_sub_page.link.json_path == Some("context_servers");@@ -3747,6 +3757,9 @@ impl SettingsWindow {})),)})+ .when(is_llm_providers_page, |this| {+ this.child(pages::render_add_llm_provider_popover(self, window, cx))+ }).when(is_skills_page, |this| {this.child(Button::new("open-skill-creator", "Create Skill")@@ -4027,7 +4040,11 @@ impl SettingsWindow {/// This function will create a new settings file if one doesn't exist/// if the current file is a project settings with a valid worktree id/// We do this because the settings ui allows initializing project settings- fn open_current_settings_file(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ pub(crate) fn open_current_settings_file(+ &mut self,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {match &self.current_file {SettingsUiFile::User => {let Some(original_window) = self.original_window else {@@ -5267,6 +5284,8 @@ pub mod test {provider_configuration_views: HashMap::default(),configuring_provider: None,last_copied_skill_directory_path: None,+ llm_provider_form: None,+ llm_provider_add_focus_handle: cx.focus_handle(),mcp_server_form: None,mcp_add_server_focus_handle: cx.focus_handle(),custom_agent_form: None,@@ -5404,6 +5423,8 @@ pub mod test {provider_configuration_views: HashMap::default(),configuring_provider: None,last_copied_skill_directory_path: None,+ llm_provider_form: None,+ llm_provider_add_focus_handle: cx.focus_handle(),mcp_server_form: None,mcp_add_server_focus_handle: cx.focus_handle(),custom_agent_form: None,