settings.rs

  1use std::{sync::Arc, time::Duration};
  2
  3use anyhow::Result;
  4use gpui::AppContext;
  5use project::Fs;
  6use schemars::JsonSchema;
  7use serde::{Deserialize, Serialize};
  8use settings::{update_settings_file, Settings, SettingsSources};
  9
 10use crate::{
 11    provider::{
 12        self,
 13        anthropic::AnthropicSettings,
 14        cloud::{self, ZedDotDevSettings},
 15        copilot_chat::CopilotChatSettings,
 16        google::GoogleSettings,
 17        ollama::OllamaSettings,
 18        open_ai::OpenAiSettings,
 19    },
 20    LanguageModelCacheConfiguration,
 21};
 22
 23/// Initializes the language model settings.
 24pub fn init(fs: Arc<dyn Fs>, cx: &mut AppContext) {
 25    AllLanguageModelSettings::register(cx);
 26
 27    if AllLanguageModelSettings::get_global(cx)
 28        .openai
 29        .needs_setting_migration
 30    {
 31        update_settings_file::<AllLanguageModelSettings>(fs.clone(), cx, move |setting, _| {
 32            if let Some(settings) = setting.openai.clone() {
 33                let (newest_version, _) = settings.upgrade();
 34                setting.openai = Some(OpenAiSettingsContent::Versioned(
 35                    VersionedOpenAiSettingsContent::V1(newest_version),
 36                ));
 37            }
 38        });
 39    }
 40
 41    if AllLanguageModelSettings::get_global(cx)
 42        .anthropic
 43        .needs_setting_migration
 44    {
 45        update_settings_file::<AllLanguageModelSettings>(fs, cx, move |setting, _| {
 46            if let Some(settings) = setting.anthropic.clone() {
 47                let (newest_version, _) = settings.upgrade();
 48                setting.anthropic = Some(AnthropicSettingsContent::Versioned(
 49                    VersionedAnthropicSettingsContent::V1(newest_version),
 50                ));
 51            }
 52        });
 53    }
 54}
 55
 56#[derive(Default)]
 57pub struct AllLanguageModelSettings {
 58    pub anthropic: AnthropicSettings,
 59    pub ollama: OllamaSettings,
 60    pub openai: OpenAiSettings,
 61    pub zed_dot_dev: ZedDotDevSettings,
 62    pub google: GoogleSettings,
 63    pub copilot_chat: CopilotChatSettings,
 64}
 65
 66#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
 67pub struct AllLanguageModelSettingsContent {
 68    pub anthropic: Option<AnthropicSettingsContent>,
 69    pub ollama: Option<OllamaSettingsContent>,
 70    pub openai: Option<OpenAiSettingsContent>,
 71    #[serde(rename = "zed.dev")]
 72    pub zed_dot_dev: Option<ZedDotDevSettingsContent>,
 73    pub google: Option<GoogleSettingsContent>,
 74    pub copilot_chat: Option<CopilotChatSettingsContent>,
 75}
 76
 77#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
 78#[serde(untagged)]
 79pub enum AnthropicSettingsContent {
 80    Legacy(LegacyAnthropicSettingsContent),
 81    Versioned(VersionedAnthropicSettingsContent),
 82}
 83
 84impl AnthropicSettingsContent {
 85    pub fn upgrade(self) -> (AnthropicSettingsContentV1, bool) {
 86        match self {
 87            AnthropicSettingsContent::Legacy(content) => (
 88                AnthropicSettingsContentV1 {
 89                    api_url: content.api_url,
 90                    low_speed_timeout_in_seconds: content.low_speed_timeout_in_seconds,
 91                    available_models: content.available_models.map(|models| {
 92                        models
 93                            .into_iter()
 94                            .filter_map(|model| match model {
 95                                anthropic::Model::Custom {
 96                                    name,
 97                                    display_name,
 98                                    max_tokens,
 99                                    tool_override,
100                                    cache_configuration,
101                                    max_output_tokens,
102                                } => Some(provider::anthropic::AvailableModel {
103                                    name,
104                                    display_name,
105                                    max_tokens,
106                                    tool_override,
107                                    cache_configuration: cache_configuration.as_ref().map(
108                                        |config| LanguageModelCacheConfiguration {
109                                            max_cache_anchors: config.max_cache_anchors,
110                                            should_speculate: config.should_speculate,
111                                            min_total_token: config.min_total_token,
112                                        },
113                                    ),
114                                    max_output_tokens,
115                                }),
116                                _ => None,
117                            })
118                            .collect()
119                    }),
120                },
121                true,
122            ),
123            AnthropicSettingsContent::Versioned(content) => match content {
124                VersionedAnthropicSettingsContent::V1(content) => (content, false),
125            },
126        }
127    }
128}
129
130#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
131pub struct LegacyAnthropicSettingsContent {
132    pub api_url: Option<String>,
133    pub low_speed_timeout_in_seconds: Option<u64>,
134    pub available_models: Option<Vec<anthropic::Model>>,
135}
136
137#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
138#[serde(tag = "version")]
139pub enum VersionedAnthropicSettingsContent {
140    #[serde(rename = "1")]
141    V1(AnthropicSettingsContentV1),
142}
143
144#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
145pub struct AnthropicSettingsContentV1 {
146    pub api_url: Option<String>,
147    pub low_speed_timeout_in_seconds: Option<u64>,
148    pub available_models: Option<Vec<provider::anthropic::AvailableModel>>,
149}
150
151#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
152pub struct OllamaSettingsContent {
153    pub api_url: Option<String>,
154    pub low_speed_timeout_in_seconds: Option<u64>,
155    pub available_models: Option<Vec<provider::ollama::AvailableModel>>,
156}
157
158#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
159#[serde(untagged)]
160pub enum OpenAiSettingsContent {
161    Legacy(LegacyOpenAiSettingsContent),
162    Versioned(VersionedOpenAiSettingsContent),
163}
164
165impl OpenAiSettingsContent {
166    pub fn upgrade(self) -> (OpenAiSettingsContentV1, bool) {
167        match self {
168            OpenAiSettingsContent::Legacy(content) => (
169                OpenAiSettingsContentV1 {
170                    api_url: content.api_url,
171                    low_speed_timeout_in_seconds: content.low_speed_timeout_in_seconds,
172                    available_models: content.available_models.map(|models| {
173                        models
174                            .into_iter()
175                            .filter_map(|model| match model {
176                                open_ai::Model::Custom {
177                                    name,
178                                    display_name,
179                                    max_tokens,
180                                    max_output_tokens,
181                                } => Some(provider::open_ai::AvailableModel {
182                                    name,
183                                    max_tokens,
184                                    max_output_tokens,
185                                    display_name,
186                                }),
187                                _ => None,
188                            })
189                            .collect()
190                    }),
191                },
192                true,
193            ),
194            OpenAiSettingsContent::Versioned(content) => match content {
195                VersionedOpenAiSettingsContent::V1(content) => (content, false),
196            },
197        }
198    }
199}
200
201#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
202pub struct LegacyOpenAiSettingsContent {
203    pub api_url: Option<String>,
204    pub low_speed_timeout_in_seconds: Option<u64>,
205    pub available_models: Option<Vec<open_ai::Model>>,
206}
207
208#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
209#[serde(tag = "version")]
210pub enum VersionedOpenAiSettingsContent {
211    #[serde(rename = "1")]
212    V1(OpenAiSettingsContentV1),
213}
214
215#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
216pub struct OpenAiSettingsContentV1 {
217    pub api_url: Option<String>,
218    pub low_speed_timeout_in_seconds: Option<u64>,
219    pub available_models: Option<Vec<provider::open_ai::AvailableModel>>,
220}
221
222#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
223pub struct GoogleSettingsContent {
224    pub api_url: Option<String>,
225    pub low_speed_timeout_in_seconds: Option<u64>,
226    pub available_models: Option<Vec<provider::google::AvailableModel>>,
227}
228
229#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
230pub struct ZedDotDevSettingsContent {
231    available_models: Option<Vec<cloud::AvailableModel>>,
232}
233
234#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
235pub struct CopilotChatSettingsContent {
236    low_speed_timeout_in_seconds: Option<u64>,
237}
238
239impl settings::Settings for AllLanguageModelSettings {
240    const KEY: Option<&'static str> = Some("language_models");
241
242    const PRESERVED_KEYS: Option<&'static [&'static str]> = Some(&["version"]);
243
244    type FileContent = AllLanguageModelSettingsContent;
245
246    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
247        fn merge<T>(target: &mut T, value: Option<T>) {
248            if let Some(value) = value {
249                *target = value;
250            }
251        }
252
253        let mut settings = AllLanguageModelSettings::default();
254
255        for value in sources.defaults_and_customizations() {
256            // Anthropic
257            let (anthropic, upgraded) = match value.anthropic.clone().map(|s| s.upgrade()) {
258                Some((content, upgraded)) => (Some(content), upgraded),
259                None => (None, false),
260            };
261
262            if upgraded {
263                settings.anthropic.needs_setting_migration = true;
264            }
265
266            merge(
267                &mut settings.anthropic.api_url,
268                anthropic.as_ref().and_then(|s| s.api_url.clone()),
269            );
270            if let Some(low_speed_timeout_in_seconds) = anthropic
271                .as_ref()
272                .and_then(|s| s.low_speed_timeout_in_seconds)
273            {
274                settings.anthropic.low_speed_timeout =
275                    Some(Duration::from_secs(low_speed_timeout_in_seconds));
276            }
277            merge(
278                &mut settings.anthropic.available_models,
279                anthropic.as_ref().and_then(|s| s.available_models.clone()),
280            );
281
282            // Ollama
283            let ollama = value.ollama.clone();
284
285            merge(
286                &mut settings.ollama.api_url,
287                value.ollama.as_ref().and_then(|s| s.api_url.clone()),
288            );
289            if let Some(low_speed_timeout_in_seconds) = value
290                .ollama
291                .as_ref()
292                .and_then(|s| s.low_speed_timeout_in_seconds)
293            {
294                settings.ollama.low_speed_timeout =
295                    Some(Duration::from_secs(low_speed_timeout_in_seconds));
296            }
297            merge(
298                &mut settings.ollama.available_models,
299                ollama.as_ref().and_then(|s| s.available_models.clone()),
300            );
301
302            // OpenAI
303            let (openai, upgraded) = match value.openai.clone().map(|s| s.upgrade()) {
304                Some((content, upgraded)) => (Some(content), upgraded),
305                None => (None, false),
306            };
307
308            if upgraded {
309                settings.openai.needs_setting_migration = true;
310            }
311
312            merge(
313                &mut settings.openai.api_url,
314                openai.as_ref().and_then(|s| s.api_url.clone()),
315            );
316            if let Some(low_speed_timeout_in_seconds) =
317                openai.as_ref().and_then(|s| s.low_speed_timeout_in_seconds)
318            {
319                settings.openai.low_speed_timeout =
320                    Some(Duration::from_secs(low_speed_timeout_in_seconds));
321            }
322            merge(
323                &mut settings.openai.available_models,
324                openai.as_ref().and_then(|s| s.available_models.clone()),
325            );
326
327            merge(
328                &mut settings.zed_dot_dev.available_models,
329                value
330                    .zed_dot_dev
331                    .as_ref()
332                    .and_then(|s| s.available_models.clone()),
333            );
334
335            merge(
336                &mut settings.google.api_url,
337                value.google.as_ref().and_then(|s| s.api_url.clone()),
338            );
339            if let Some(low_speed_timeout_in_seconds) = value
340                .google
341                .as_ref()
342                .and_then(|s| s.low_speed_timeout_in_seconds)
343            {
344                settings.google.low_speed_timeout =
345                    Some(Duration::from_secs(low_speed_timeout_in_seconds));
346            }
347            merge(
348                &mut settings.google.available_models,
349                value
350                    .google
351                    .as_ref()
352                    .and_then(|s| s.available_models.clone()),
353            );
354
355            if let Some(low_speed_timeout) = value
356                .copilot_chat
357                .as_ref()
358                .and_then(|s| s.low_speed_timeout_in_seconds)
359            {
360                settings.copilot_chat.low_speed_timeout =
361                    Some(Duration::from_secs(low_speed_timeout));
362            }
363        }
364
365        Ok(settings)
366    }
367}