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}
156
157#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
158#[serde(untagged)]
159pub enum OpenAiSettingsContent {
160 Legacy(LegacyOpenAiSettingsContent),
161 Versioned(VersionedOpenAiSettingsContent),
162}
163
164impl OpenAiSettingsContent {
165 pub fn upgrade(self) -> (OpenAiSettingsContentV1, bool) {
166 match self {
167 OpenAiSettingsContent::Legacy(content) => (
168 OpenAiSettingsContentV1 {
169 api_url: content.api_url,
170 low_speed_timeout_in_seconds: content.low_speed_timeout_in_seconds,
171 available_models: content.available_models.map(|models| {
172 models
173 .into_iter()
174 .filter_map(|model| match model {
175 open_ai::Model::Custom { name, max_tokens } => {
176 Some(provider::open_ai::AvailableModel { name, max_tokens })
177 }
178 _ => None,
179 })
180 .collect()
181 }),
182 },
183 true,
184 ),
185 OpenAiSettingsContent::Versioned(content) => match content {
186 VersionedOpenAiSettingsContent::V1(content) => (content, false),
187 },
188 }
189 }
190}
191
192#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
193pub struct LegacyOpenAiSettingsContent {
194 pub api_url: Option<String>,
195 pub low_speed_timeout_in_seconds: Option<u64>,
196 pub available_models: Option<Vec<open_ai::Model>>,
197}
198
199#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
200#[serde(tag = "version")]
201pub enum VersionedOpenAiSettingsContent {
202 #[serde(rename = "1")]
203 V1(OpenAiSettingsContentV1),
204}
205
206#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
207pub struct OpenAiSettingsContentV1 {
208 pub api_url: Option<String>,
209 pub low_speed_timeout_in_seconds: Option<u64>,
210 pub available_models: Option<Vec<provider::open_ai::AvailableModel>>,
211}
212
213#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
214pub struct GoogleSettingsContent {
215 pub api_url: Option<String>,
216 pub low_speed_timeout_in_seconds: Option<u64>,
217 pub available_models: Option<Vec<provider::google::AvailableModel>>,
218}
219
220#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
221pub struct ZedDotDevSettingsContent {
222 available_models: Option<Vec<cloud::AvailableModel>>,
223}
224
225#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
226pub struct CopilotChatSettingsContent {
227 low_speed_timeout_in_seconds: Option<u64>,
228}
229
230impl settings::Settings for AllLanguageModelSettings {
231 const KEY: Option<&'static str> = Some("language_models");
232
233 const PRESERVED_KEYS: Option<&'static [&'static str]> = Some(&["version"]);
234
235 type FileContent = AllLanguageModelSettingsContent;
236
237 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
238 fn merge<T>(target: &mut T, value: Option<T>) {
239 if let Some(value) = value {
240 *target = value;
241 }
242 }
243
244 let mut settings = AllLanguageModelSettings::default();
245
246 for value in sources.defaults_and_customizations() {
247 // Anthropic
248 let (anthropic, upgraded) = match value.anthropic.clone().map(|s| s.upgrade()) {
249 Some((content, upgraded)) => (Some(content), upgraded),
250 None => (None, false),
251 };
252
253 if upgraded {
254 settings.anthropic.needs_setting_migration = true;
255 }
256
257 merge(
258 &mut settings.anthropic.api_url,
259 anthropic.as_ref().and_then(|s| s.api_url.clone()),
260 );
261 if let Some(low_speed_timeout_in_seconds) = anthropic
262 .as_ref()
263 .and_then(|s| s.low_speed_timeout_in_seconds)
264 {
265 settings.anthropic.low_speed_timeout =
266 Some(Duration::from_secs(low_speed_timeout_in_seconds));
267 }
268 merge(
269 &mut settings.anthropic.available_models,
270 anthropic.as_ref().and_then(|s| s.available_models.clone()),
271 );
272
273 merge(
274 &mut settings.ollama.api_url,
275 value.ollama.as_ref().and_then(|s| s.api_url.clone()),
276 );
277 if let Some(low_speed_timeout_in_seconds) = value
278 .ollama
279 .as_ref()
280 .and_then(|s| s.low_speed_timeout_in_seconds)
281 {
282 settings.ollama.low_speed_timeout =
283 Some(Duration::from_secs(low_speed_timeout_in_seconds));
284 }
285
286 // OpenAI
287 let (openai, upgraded) = match value.openai.clone().map(|s| s.upgrade()) {
288 Some((content, upgraded)) => (Some(content), upgraded),
289 None => (None, false),
290 };
291
292 if upgraded {
293 settings.openai.needs_setting_migration = true;
294 }
295
296 merge(
297 &mut settings.openai.api_url,
298 openai.as_ref().and_then(|s| s.api_url.clone()),
299 );
300 if let Some(low_speed_timeout_in_seconds) =
301 openai.as_ref().and_then(|s| s.low_speed_timeout_in_seconds)
302 {
303 settings.openai.low_speed_timeout =
304 Some(Duration::from_secs(low_speed_timeout_in_seconds));
305 }
306 merge(
307 &mut settings.openai.available_models,
308 openai.as_ref().and_then(|s| s.available_models.clone()),
309 );
310
311 merge(
312 &mut settings.zed_dot_dev.available_models,
313 value
314 .zed_dot_dev
315 .as_ref()
316 .and_then(|s| s.available_models.clone()),
317 );
318
319 merge(
320 &mut settings.google.api_url,
321 value.google.as_ref().and_then(|s| s.api_url.clone()),
322 );
323 if let Some(low_speed_timeout_in_seconds) = value
324 .google
325 .as_ref()
326 .and_then(|s| s.low_speed_timeout_in_seconds)
327 {
328 settings.google.low_speed_timeout =
329 Some(Duration::from_secs(low_speed_timeout_in_seconds));
330 }
331 merge(
332 &mut settings.google.available_models,
333 value
334 .google
335 .as_ref()
336 .and_then(|s| s.available_models.clone()),
337 );
338
339 if let Some(low_speed_timeout) = value
340 .copilot_chat
341 .as_ref()
342 .and_then(|s| s.low_speed_timeout_in_seconds)
343 {
344 settings.copilot_chat.low_speed_timeout =
345 Some(Duration::from_secs(low_speed_timeout));
346 }
347 }
348
349 Ok(settings)
350 }
351}