1use anyhow::{Context as _, Result, anyhow};
2use credentials_provider::CredentialsProvider;
3
4use convert_case::{Case, Casing};
5use futures::{FutureExt, StreamExt, future::BoxFuture};
6use gpui::{AnyView, App, AsyncApp, Context, Entity, Subscription, Task, Window};
7use http_client::HttpClient;
8use language_model::{
9 AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
10 LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
11 LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
12 LanguageModelToolChoice, RateLimiter,
13};
14use menu;
15use open_ai::{ResponseStreamEvent, stream_completion};
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18use settings::{Settings, SettingsStore};
19use std::sync::Arc;
20
21use ui::{ElevationIndex, Tooltip, prelude::*};
22use ui_input::SingleLineInput;
23use util::ResultExt;
24
25use crate::AllLanguageModelSettings;
26use crate::provider::open_ai::{OpenAiEventMapper, into_open_ai};
27
28#[derive(Default, Clone, Debug, PartialEq)]
29pub struct OpenAiCompatibleSettings {
30 pub api_url: String,
31 pub available_models: Vec<AvailableModel>,
32}
33
34#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
35pub struct AvailableModel {
36 pub name: String,
37 pub display_name: Option<String>,
38 pub max_tokens: u64,
39 pub max_output_tokens: Option<u64>,
40 pub max_completion_tokens: Option<u64>,
41}
42
43pub struct OpenAiCompatibleLanguageModelProvider {
44 id: LanguageModelProviderId,
45 name: LanguageModelProviderName,
46 http_client: Arc<dyn HttpClient>,
47 state: gpui::Entity<State>,
48}
49
50pub struct State {
51 id: Arc<str>,
52 env_var_name: Arc<str>,
53 api_key: Option<String>,
54 api_key_from_env: bool,
55 settings: OpenAiCompatibleSettings,
56 _subscription: Subscription,
57}
58
59impl State {
60 fn is_authenticated(&self) -> bool {
61 self.api_key.is_some()
62 }
63
64 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
65 let credentials_provider = <dyn CredentialsProvider>::global(cx);
66 let api_url = self.settings.api_url.clone();
67 cx.spawn(async move |this, cx| {
68 credentials_provider
69 .delete_credentials(&api_url, &cx)
70 .await
71 .log_err();
72 this.update(cx, |this, cx| {
73 this.api_key = None;
74 this.api_key_from_env = false;
75 cx.notify();
76 })
77 })
78 }
79
80 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
81 let credentials_provider = <dyn CredentialsProvider>::global(cx);
82 let api_url = self.settings.api_url.clone();
83 cx.spawn(async move |this, cx| {
84 credentials_provider
85 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
86 .await
87 .log_err();
88 this.update(cx, |this, cx| {
89 this.api_key = Some(api_key);
90 cx.notify();
91 })
92 })
93 }
94
95 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
96 if self.is_authenticated() {
97 return Task::ready(Ok(()));
98 }
99
100 let credentials_provider = <dyn CredentialsProvider>::global(cx);
101 let env_var_name = self.env_var_name.clone();
102 let api_url = self.settings.api_url.clone();
103 cx.spawn(async move |this, cx| {
104 let (api_key, from_env) = if let Ok(api_key) = std::env::var(env_var_name.as_ref()) {
105 (api_key, true)
106 } else {
107 let (_, api_key) = credentials_provider
108 .read_credentials(&api_url, &cx)
109 .await?
110 .ok_or(AuthenticateError::CredentialsNotFound)?;
111 (
112 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
113 false,
114 )
115 };
116 this.update(cx, |this, cx| {
117 this.api_key = Some(api_key);
118 this.api_key_from_env = from_env;
119 cx.notify();
120 })?;
121
122 Ok(())
123 })
124 }
125}
126
127impl OpenAiCompatibleLanguageModelProvider {
128 pub fn new(id: Arc<str>, http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
129 fn resolve_settings<'a>(id: &'a str, cx: &'a App) -> Option<&'a OpenAiCompatibleSettings> {
130 AllLanguageModelSettings::get_global(cx)
131 .openai_compatible
132 .get(id)
133 }
134
135 let state = cx.new(|cx| State {
136 id: id.clone(),
137 env_var_name: format!("{}_API_KEY", id).to_case(Case::Constant).into(),
138 settings: resolve_settings(&id, cx).cloned().unwrap_or_default(),
139 api_key: None,
140 api_key_from_env: false,
141 _subscription: cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
142 let Some(settings) = resolve_settings(&this.id, cx) else {
143 return;
144 };
145 if &this.settings != settings {
146 this.settings = settings.clone();
147 cx.notify();
148 }
149 }),
150 });
151
152 Self {
153 id: id.clone().into(),
154 name: id.into(),
155 http_client,
156 state,
157 }
158 }
159
160 fn create_language_model(&self, model: AvailableModel) -> Arc<dyn LanguageModel> {
161 Arc::new(OpenAiCompatibleLanguageModel {
162 id: LanguageModelId::from(model.name.clone()),
163 provider_id: self.id.clone(),
164 provider_name: self.name.clone(),
165 model,
166 state: self.state.clone(),
167 http_client: self.http_client.clone(),
168 request_limiter: RateLimiter::new(4),
169 })
170 }
171}
172
173impl LanguageModelProviderState for OpenAiCompatibleLanguageModelProvider {
174 type ObservableEntity = State;
175
176 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
177 Some(self.state.clone())
178 }
179}
180
181impl LanguageModelProvider for OpenAiCompatibleLanguageModelProvider {
182 fn id(&self) -> LanguageModelProviderId {
183 self.id.clone()
184 }
185
186 fn name(&self) -> LanguageModelProviderName {
187 self.name.clone()
188 }
189
190 fn icon(&self) -> IconName {
191 IconName::AiOpenAiCompat
192 }
193
194 fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
195 self.state
196 .read(cx)
197 .settings
198 .available_models
199 .first()
200 .map(|model| self.create_language_model(model.clone()))
201 }
202
203 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
204 None
205 }
206
207 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
208 self.state
209 .read(cx)
210 .settings
211 .available_models
212 .iter()
213 .map(|model| self.create_language_model(model.clone()))
214 .collect()
215 }
216
217 fn is_authenticated(&self, cx: &App) -> bool {
218 self.state.read(cx).is_authenticated()
219 }
220
221 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
222 self.state.update(cx, |state, cx| state.authenticate(cx))
223 }
224
225 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
226 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
227 .into()
228 }
229
230 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
231 self.state.update(cx, |state, cx| state.reset_api_key(cx))
232 }
233}
234
235pub struct OpenAiCompatibleLanguageModel {
236 id: LanguageModelId,
237 provider_id: LanguageModelProviderId,
238 provider_name: LanguageModelProviderName,
239 model: AvailableModel,
240 state: gpui::Entity<State>,
241 http_client: Arc<dyn HttpClient>,
242 request_limiter: RateLimiter,
243}
244
245impl OpenAiCompatibleLanguageModel {
246 fn stream_completion(
247 &self,
248 request: open_ai::Request,
249 cx: &AsyncApp,
250 ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
251 {
252 let http_client = self.http_client.clone();
253 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, _| {
254 (state.api_key.clone(), state.settings.api_url.clone())
255 }) else {
256 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
257 };
258
259 let provider = self.provider_name.clone();
260 let future = self.request_limiter.stream(async move {
261 let Some(api_key) = api_key else {
262 return Err(LanguageModelCompletionError::NoApiKey { provider });
263 };
264 let request = stream_completion(http_client.as_ref(), &api_url, &api_key, request);
265 let response = request.await?;
266 Ok(response)
267 });
268
269 async move { Ok(future.await?.boxed()) }.boxed()
270 }
271}
272
273impl LanguageModel for OpenAiCompatibleLanguageModel {
274 fn id(&self) -> LanguageModelId {
275 self.id.clone()
276 }
277
278 fn name(&self) -> LanguageModelName {
279 LanguageModelName::from(
280 self.model
281 .display_name
282 .clone()
283 .unwrap_or_else(|| self.model.name.clone()),
284 )
285 }
286
287 fn provider_id(&self) -> LanguageModelProviderId {
288 self.provider_id.clone()
289 }
290
291 fn provider_name(&self) -> LanguageModelProviderName {
292 self.provider_name.clone()
293 }
294
295 fn supports_tools(&self) -> bool {
296 true
297 }
298
299 fn supports_images(&self) -> bool {
300 false
301 }
302
303 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
304 match choice {
305 LanguageModelToolChoice::Auto => true,
306 LanguageModelToolChoice::Any => true,
307 LanguageModelToolChoice::None => true,
308 }
309 }
310
311 fn telemetry_id(&self) -> String {
312 format!("openai/{}", self.model.name)
313 }
314
315 fn max_token_count(&self) -> u64 {
316 self.model.max_tokens
317 }
318
319 fn max_output_tokens(&self) -> Option<u64> {
320 self.model.max_output_tokens
321 }
322
323 fn count_tokens(
324 &self,
325 request: LanguageModelRequest,
326 cx: &App,
327 ) -> BoxFuture<'static, Result<u64>> {
328 let max_token_count = self.max_token_count();
329 cx.background_spawn(async move {
330 let messages = super::open_ai::collect_tiktoken_messages(request);
331 let model = if max_token_count >= 100_000 {
332 // If the max tokens is 100k or more, it is likely the o200k_base tokenizer from gpt4o
333 "gpt-4o"
334 } else {
335 // Otherwise fallback to gpt-4, since only cl100k_base and o200k_base are
336 // supported with this tiktoken method
337 "gpt-4"
338 };
339 tiktoken_rs::num_tokens_from_messages(model, &messages).map(|tokens| tokens as u64)
340 })
341 .boxed()
342 }
343
344 fn stream_completion(
345 &self,
346 request: LanguageModelRequest,
347 cx: &AsyncApp,
348 ) -> BoxFuture<
349 'static,
350 Result<
351 futures::stream::BoxStream<
352 'static,
353 Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
354 >,
355 LanguageModelCompletionError,
356 >,
357 > {
358 let request = into_open_ai(
359 request,
360 &self.model.name,
361 true,
362 self.max_output_tokens(),
363 None,
364 );
365 let completions = self.stream_completion(request, cx);
366 async move {
367 let mapper = OpenAiEventMapper::new();
368 Ok(mapper.map_stream(completions.await?).boxed())
369 }
370 .boxed()
371 }
372}
373
374struct ConfigurationView {
375 api_key_editor: Entity<SingleLineInput>,
376 state: gpui::Entity<State>,
377 load_credentials_task: Option<Task<()>>,
378}
379
380impl ConfigurationView {
381 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
382 let api_key_editor = cx.new(|cx| {
383 SingleLineInput::new(
384 window,
385 cx,
386 "000000000000000000000000000000000000000000000000000",
387 )
388 });
389
390 cx.observe(&state, |_, _, cx| {
391 cx.notify();
392 })
393 .detach();
394
395 let load_credentials_task = Some(cx.spawn_in(window, {
396 let state = state.clone();
397 async move |this, cx| {
398 if let Some(task) = state
399 .update(cx, |state, cx| state.authenticate(cx))
400 .log_err()
401 {
402 // We don't log an error, because "not signed in" is also an error.
403 let _ = task.await;
404 }
405 this.update(cx, |this, cx| {
406 this.load_credentials_task = None;
407 cx.notify();
408 })
409 .log_err();
410 }
411 }));
412
413 Self {
414 api_key_editor,
415 state,
416 load_credentials_task,
417 }
418 }
419
420 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
421 let api_key = self
422 .api_key_editor
423 .read(cx)
424 .editor()
425 .read(cx)
426 .text(cx)
427 .trim()
428 .to_string();
429
430 // Don't proceed if no API key is provided and we're not authenticated
431 if api_key.is_empty() && !self.state.read(cx).is_authenticated() {
432 return;
433 }
434
435 let state = self.state.clone();
436 cx.spawn_in(window, async move |_, cx| {
437 state
438 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
439 .await
440 })
441 .detach_and_log_err(cx);
442
443 cx.notify();
444 }
445
446 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
447 self.api_key_editor.update(cx, |input, cx| {
448 input.editor.update(cx, |editor, cx| {
449 editor.set_text("", window, cx);
450 });
451 });
452
453 let state = self.state.clone();
454 cx.spawn_in(window, async move |_, cx| {
455 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
456 })
457 .detach_and_log_err(cx);
458
459 cx.notify();
460 }
461
462 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
463 !self.state.read(cx).is_authenticated()
464 }
465}
466
467impl Render for ConfigurationView {
468 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
469 let env_var_set = self.state.read(cx).api_key_from_env;
470 let env_var_name = self.state.read(cx).env_var_name.clone();
471
472 let api_key_section = if self.should_render_editor(cx) {
473 v_flex()
474 .on_action(cx.listener(Self::save_api_key))
475 .child(Label::new("To use Zed's agent with an OpenAI-compatible provider, you need to add an API key."))
476 .child(
477 div()
478 .pt(DynamicSpacing::Base04.rems(cx))
479 .child(self.api_key_editor.clone())
480 )
481 .child(
482 Label::new(
483 format!("You can also assign the {env_var_name} environment variable and restart Zed."),
484 )
485 .size(LabelSize::Small).color(Color::Muted),
486 )
487 .into_any()
488 } else {
489 h_flex()
490 .mt_1()
491 .p_1()
492 .justify_between()
493 .rounded_md()
494 .border_1()
495 .border_color(cx.theme().colors().border)
496 .bg(cx.theme().colors().background)
497 .child(
498 h_flex()
499 .gap_1()
500 .child(Icon::new(IconName::Check).color(Color::Success))
501 .child(Label::new(if env_var_set {
502 format!("API key set in {env_var_name} environment variable.")
503 } else {
504 "API key configured.".to_string()
505 })),
506 )
507 .child(
508 Button::new("reset-api-key", "Reset API Key")
509 .label_size(LabelSize::Small)
510 .icon(IconName::Undo)
511 .icon_size(IconSize::Small)
512 .icon_position(IconPosition::Start)
513 .layer(ElevationIndex::ModalSurface)
514 .when(env_var_set, |this| {
515 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {env_var_name} environment variable.")))
516 })
517 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
518 )
519 .into_any()
520 };
521
522 if self.load_credentials_task.is_some() {
523 div().child(Label::new("Loading credentials…")).into_any()
524 } else {
525 v_flex().size_full().child(api_key_section).into_any()
526 }
527 }
528}