open_ai.rs

  1use anyhow::{Context as _, Result, anyhow};
  2use collections::{BTreeMap, HashMap};
  3use credentials_provider::CredentialsProvider;
  4use editor::{Editor, EditorElement, EditorStyle};
  5use futures::Stream;
  6use futures::{FutureExt, StreamExt, future::BoxFuture};
  7use gpui::{
  8    AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
  9};
 10use http_client::HttpClient;
 11use language_model::{
 12    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
 13    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
 14    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
 15    LanguageModelToolUse, MessageContent, RateLimiter, Role, StopReason,
 16};
 17use open_ai::{Model, ResponseStreamEvent, stream_completion};
 18use schemars::JsonSchema;
 19use serde::{Deserialize, Serialize};
 20use settings::{Settings, SettingsStore};
 21use std::pin::Pin;
 22use std::str::FromStr as _;
 23use std::sync::Arc;
 24use strum::IntoEnumIterator;
 25use theme::ThemeSettings;
 26use ui::{Icon, IconName, List, Tooltip, prelude::*};
 27use util::ResultExt;
 28
 29use crate::{AllLanguageModelSettings, ui::InstructionListItem};
 30
 31const PROVIDER_ID: &str = "openai";
 32const PROVIDER_NAME: &str = "OpenAI";
 33
 34#[derive(Default, Clone, Debug, PartialEq)]
 35pub struct OpenAiSettings {
 36    pub api_url: String,
 37    pub available_models: Vec<AvailableModel>,
 38    pub needs_setting_migration: bool,
 39}
 40
 41#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 42pub struct AvailableModel {
 43    pub name: String,
 44    pub display_name: Option<String>,
 45    pub max_tokens: usize,
 46    pub max_output_tokens: Option<u32>,
 47    pub max_completion_tokens: Option<u32>,
 48}
 49
 50pub struct OpenAiLanguageModelProvider {
 51    http_client: Arc<dyn HttpClient>,
 52    state: gpui::Entity<State>,
 53}
 54
 55pub struct State {
 56    api_key: Option<String>,
 57    api_key_from_env: bool,
 58    _subscription: Subscription,
 59}
 60
 61const OPENAI_API_KEY_VAR: &str = "OPENAI_API_KEY";
 62
 63impl State {
 64    fn is_authenticated(&self) -> bool {
 65        self.api_key.is_some()
 66    }
 67
 68    fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 69        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 70        let api_url = AllLanguageModelSettings::get_global(cx)
 71            .openai
 72            .api_url
 73            .clone();
 74        cx.spawn(async move |this, cx| {
 75            credentials_provider
 76                .delete_credentials(&api_url, &cx)
 77                .await
 78                .log_err();
 79            this.update(cx, |this, cx| {
 80                this.api_key = None;
 81                this.api_key_from_env = false;
 82                cx.notify();
 83            })
 84        })
 85    }
 86
 87    fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
 88        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 89        let api_url = AllLanguageModelSettings::get_global(cx)
 90            .openai
 91            .api_url
 92            .clone();
 93        cx.spawn(async move |this, cx| {
 94            credentials_provider
 95                .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
 96                .await
 97                .log_err();
 98            this.update(cx, |this, cx| {
 99                this.api_key = Some(api_key);
100                cx.notify();
101            })
102        })
103    }
104
105    fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
106        if self.is_authenticated() {
107            return Task::ready(Ok(()));
108        }
109
110        let credentials_provider = <dyn CredentialsProvider>::global(cx);
111        let api_url = AllLanguageModelSettings::get_global(cx)
112            .openai
113            .api_url
114            .clone();
115        cx.spawn(async move |this, cx| {
116            let (api_key, from_env) = if let Ok(api_key) = std::env::var(OPENAI_API_KEY_VAR) {
117                (api_key, true)
118            } else {
119                let (_, api_key) = credentials_provider
120                    .read_credentials(&api_url, &cx)
121                    .await?
122                    .ok_or(AuthenticateError::CredentialsNotFound)?;
123                (
124                    String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
125                    false,
126                )
127            };
128            this.update(cx, |this, cx| {
129                this.api_key = Some(api_key);
130                this.api_key_from_env = from_env;
131                cx.notify();
132            })?;
133
134            Ok(())
135        })
136    }
137}
138
139impl OpenAiLanguageModelProvider {
140    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
141        let state = cx.new(|cx| State {
142            api_key: None,
143            api_key_from_env: false,
144            _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
145                cx.notify();
146            }),
147        });
148
149        Self { http_client, state }
150    }
151
152    fn create_language_model(&self, model: open_ai::Model) -> Arc<dyn LanguageModel> {
153        Arc::new(OpenAiLanguageModel {
154            id: LanguageModelId::from(model.id().to_string()),
155            model,
156            state: self.state.clone(),
157            http_client: self.http_client.clone(),
158            request_limiter: RateLimiter::new(4),
159        })
160    }
161}
162
163impl LanguageModelProviderState for OpenAiLanguageModelProvider {
164    type ObservableEntity = State;
165
166    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
167        Some(self.state.clone())
168    }
169}
170
171impl LanguageModelProvider for OpenAiLanguageModelProvider {
172    fn id(&self) -> LanguageModelProviderId {
173        LanguageModelProviderId(PROVIDER_ID.into())
174    }
175
176    fn name(&self) -> LanguageModelProviderName {
177        LanguageModelProviderName(PROVIDER_NAME.into())
178    }
179
180    fn icon(&self) -> IconName {
181        IconName::AiOpenAi
182    }
183
184    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
185        Some(self.create_language_model(open_ai::Model::default()))
186    }
187
188    fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
189        Some(self.create_language_model(open_ai::Model::default_fast()))
190    }
191
192    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
193        let mut models = BTreeMap::default();
194
195        // Add base models from open_ai::Model::iter()
196        for model in open_ai::Model::iter() {
197            if !matches!(model, open_ai::Model::Custom { .. }) {
198                models.insert(model.id().to_string(), model);
199            }
200        }
201
202        // Override with available models from settings
203        for model in &AllLanguageModelSettings::get_global(cx)
204            .openai
205            .available_models
206        {
207            models.insert(
208                model.name.clone(),
209                open_ai::Model::Custom {
210                    name: model.name.clone(),
211                    display_name: model.display_name.clone(),
212                    max_tokens: model.max_tokens,
213                    max_output_tokens: model.max_output_tokens,
214                    max_completion_tokens: model.max_completion_tokens,
215                },
216            );
217        }
218
219        models
220            .into_values()
221            .map(|model| self.create_language_model(model))
222            .collect()
223    }
224
225    fn is_authenticated(&self, cx: &App) -> bool {
226        self.state.read(cx).is_authenticated()
227    }
228
229    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
230        self.state.update(cx, |state, cx| state.authenticate(cx))
231    }
232
233    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
234        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
235            .into()
236    }
237
238    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
239        self.state.update(cx, |state, cx| state.reset_api_key(cx))
240    }
241}
242
243pub struct OpenAiLanguageModel {
244    id: LanguageModelId,
245    model: open_ai::Model,
246    state: gpui::Entity<State>,
247    http_client: Arc<dyn HttpClient>,
248    request_limiter: RateLimiter,
249}
250
251impl OpenAiLanguageModel {
252    fn stream_completion(
253        &self,
254        request: open_ai::Request,
255        cx: &AsyncApp,
256    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
257    {
258        let http_client = self.http_client.clone();
259        let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
260            let settings = &AllLanguageModelSettings::get_global(cx).openai;
261            (state.api_key.clone(), settings.api_url.clone())
262        }) else {
263            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
264        };
265
266        let future = self.request_limiter.stream(async move {
267            let api_key = api_key.ok_or_else(|| anyhow!("Missing OpenAI API Key"))?;
268            let request = stream_completion(http_client.as_ref(), &api_url, &api_key, request);
269            let response = request.await?;
270            Ok(response)
271        });
272
273        async move { Ok(future.await?.boxed()) }.boxed()
274    }
275}
276
277impl LanguageModel for OpenAiLanguageModel {
278    fn id(&self) -> LanguageModelId {
279        self.id.clone()
280    }
281
282    fn name(&self) -> LanguageModelName {
283        LanguageModelName::from(self.model.display_name().to_string())
284    }
285
286    fn provider_id(&self) -> LanguageModelProviderId {
287        LanguageModelProviderId(PROVIDER_ID.into())
288    }
289
290    fn provider_name(&self) -> LanguageModelProviderName {
291        LanguageModelProviderName(PROVIDER_NAME.into())
292    }
293
294    fn supports_tools(&self) -> bool {
295        true
296    }
297
298    fn telemetry_id(&self) -> String {
299        format!("openai/{}", self.model.id())
300    }
301
302    fn max_token_count(&self) -> usize {
303        self.model.max_token_count()
304    }
305
306    fn max_output_tokens(&self) -> Option<u32> {
307        self.model.max_output_tokens()
308    }
309
310    fn count_tokens(
311        &self,
312        request: LanguageModelRequest,
313        cx: &App,
314    ) -> BoxFuture<'static, Result<usize>> {
315        count_open_ai_tokens(request, self.model.clone(), cx)
316    }
317
318    fn stream_completion(
319        &self,
320        request: LanguageModelRequest,
321        cx: &AsyncApp,
322    ) -> BoxFuture<
323        'static,
324        Result<
325            futures::stream::BoxStream<
326                'static,
327                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
328            >,
329        >,
330    > {
331        let request = into_open_ai(request, &self.model, self.max_output_tokens());
332        let completions = self.stream_completion(request, cx);
333        async move { Ok(map_to_language_model_completion_events(completions.await?).boxed()) }
334            .boxed()
335    }
336}
337
338pub fn into_open_ai(
339    request: LanguageModelRequest,
340    model: &Model,
341    max_output_tokens: Option<u32>,
342) -> open_ai::Request {
343    let stream = !model.id().starts_with("o1-");
344
345    let mut messages = Vec::new();
346    for message in request.messages {
347        for content in message.content {
348            match content {
349                MessageContent::Text(text) | MessageContent::Thinking { text, .. } => messages
350                    .push(match message.role {
351                        Role::User => open_ai::RequestMessage::User { content: text },
352                        Role::Assistant => open_ai::RequestMessage::Assistant {
353                            content: Some(text),
354                            tool_calls: Vec::new(),
355                        },
356                        Role::System => open_ai::RequestMessage::System { content: text },
357                    }),
358                MessageContent::RedactedThinking(_) => {}
359                MessageContent::Image(_) => {}
360                MessageContent::ToolUse(tool_use) => {
361                    let tool_call = open_ai::ToolCall {
362                        id: tool_use.id.to_string(),
363                        content: open_ai::ToolCallContent::Function {
364                            function: open_ai::FunctionContent {
365                                name: tool_use.name.to_string(),
366                                arguments: serde_json::to_string(&tool_use.input)
367                                    .unwrap_or_default(),
368                            },
369                        },
370                    };
371
372                    if let Some(last_assistant_message) = messages.iter_mut().rfind(|message| {
373                        matches!(message, open_ai::RequestMessage::Assistant { .. })
374                    }) {
375                        if let open_ai::RequestMessage::Assistant { tool_calls, .. } =
376                            last_assistant_message
377                        {
378                            tool_calls.push(tool_call);
379                        }
380                    } else {
381                        messages.push(open_ai::RequestMessage::Assistant {
382                            content: None,
383                            tool_calls: vec![tool_call],
384                        });
385                    }
386                }
387                MessageContent::ToolResult(tool_result) => {
388                    messages.push(open_ai::RequestMessage::Tool {
389                        content: tool_result.content.to_string(),
390                        tool_call_id: tool_result.tool_use_id.to_string(),
391                    });
392                }
393            }
394        }
395    }
396
397    open_ai::Request {
398        model: model.id().into(),
399        messages,
400        stream,
401        stop: request.stop,
402        temperature: request.temperature.unwrap_or(1.0),
403        max_tokens: max_output_tokens,
404        parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
405            // Disable parallel tool calls, as the Agent currently expects a maximum of one per turn.
406            Some(false)
407        } else {
408            None
409        },
410        tools: request
411            .tools
412            .into_iter()
413            .map(|tool| open_ai::ToolDefinition::Function {
414                function: open_ai::FunctionDefinition {
415                    name: tool.name,
416                    description: Some(tool.description),
417                    parameters: Some(tool.input_schema),
418                },
419            })
420            .collect(),
421        tool_choice: None,
422    }
423}
424
425pub fn map_to_language_model_completion_events(
426    events: Pin<Box<dyn Send + Stream<Item = Result<ResponseStreamEvent>>>>,
427) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
428    #[derive(Default)]
429    struct RawToolCall {
430        id: String,
431        name: String,
432        arguments: String,
433    }
434
435    struct State {
436        events: Pin<Box<dyn Send + Stream<Item = Result<ResponseStreamEvent>>>>,
437        tool_calls_by_index: HashMap<usize, RawToolCall>,
438    }
439
440    futures::stream::unfold(
441        State {
442            events,
443            tool_calls_by_index: HashMap::default(),
444        },
445        |mut state| async move {
446            if let Some(event) = state.events.next().await {
447                match event {
448                    Ok(event) => {
449                        let Some(choice) = event.choices.first() else {
450                            return Some((
451                                vec![Err(LanguageModelCompletionError::Other(anyhow!(
452                                    "Response contained no choices"
453                                )))],
454                                state,
455                            ));
456                        };
457
458                        let mut events = Vec::new();
459                        if let Some(content) = choice.delta.content.clone() {
460                            events.push(Ok(LanguageModelCompletionEvent::Text(content)));
461                        }
462
463                        if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
464                            for tool_call in tool_calls {
465                                let entry = state
466                                    .tool_calls_by_index
467                                    .entry(tool_call.index)
468                                    .or_default();
469
470                                if let Some(tool_id) = tool_call.id.clone() {
471                                    entry.id = tool_id;
472                                }
473
474                                if let Some(function) = tool_call.function.as_ref() {
475                                    if let Some(name) = function.name.clone() {
476                                        entry.name = name;
477                                    }
478
479                                    if let Some(arguments) = function.arguments.clone() {
480                                        entry.arguments.push_str(&arguments);
481                                    }
482                                }
483                            }
484                        }
485
486                        match choice.finish_reason.as_deref() {
487                            Some("stop") => {
488                                events.push(Ok(LanguageModelCompletionEvent::Stop(
489                                    StopReason::EndTurn,
490                                )));
491                            }
492                            Some("tool_calls") => {
493                                events.extend(state.tool_calls_by_index.drain().map(
494                                    |(_, tool_call)| match serde_json::Value::from_str(
495                                        &tool_call.arguments,
496                                    ) {
497                                        Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
498                                            LanguageModelToolUse {
499                                                id: tool_call.id.clone().into(),
500                                                name: tool_call.name.as_str().into(),
501                                                is_input_complete: true,
502                                                input,
503                                                raw_input: tool_call.arguments.clone(),
504                                            },
505                                        )),
506                                        Err(error) => {
507                                            Err(LanguageModelCompletionError::BadInputJson {
508                                                id: tool_call.id.into(),
509                                                tool_name: tool_call.name.as_str().into(),
510                                                raw_input: tool_call.arguments.into(),
511                                                json_parse_error: error.to_string(),
512                                            })
513                                        }
514                                    },
515                                ));
516
517                                events.push(Ok(LanguageModelCompletionEvent::Stop(
518                                    StopReason::ToolUse,
519                                )));
520                            }
521                            Some(stop_reason) => {
522                                log::error!("Unexpected OpenAI stop_reason: {stop_reason:?}",);
523                                events.push(Ok(LanguageModelCompletionEvent::Stop(
524                                    StopReason::EndTurn,
525                                )));
526                            }
527                            None => {}
528                        }
529
530                        return Some((events, state));
531                    }
532                    Err(err) => {
533                        return Some((vec![Err(LanguageModelCompletionError::Other(err))], state));
534                    }
535                }
536            }
537
538            None
539        },
540    )
541    .flat_map(futures::stream::iter)
542}
543
544pub fn count_open_ai_tokens(
545    request: LanguageModelRequest,
546    model: open_ai::Model,
547    cx: &App,
548) -> BoxFuture<'static, Result<usize>> {
549    cx.background_spawn(async move {
550        let messages = request
551            .messages
552            .into_iter()
553            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
554                role: match message.role {
555                    Role::User => "user".into(),
556                    Role::Assistant => "assistant".into(),
557                    Role::System => "system".into(),
558                },
559                content: Some(message.string_contents()),
560                name: None,
561                function_call: None,
562            })
563            .collect::<Vec<_>>();
564
565        match model {
566            open_ai::Model::Custom { .. }
567            | open_ai::Model::O1Mini
568            | open_ai::Model::O1
569            | open_ai::Model::O3Mini => tiktoken_rs::num_tokens_from_messages("gpt-4", &messages),
570            _ => tiktoken_rs::num_tokens_from_messages(model.id(), &messages),
571        }
572    })
573    .boxed()
574}
575
576struct ConfigurationView {
577    api_key_editor: Entity<Editor>,
578    state: gpui::Entity<State>,
579    load_credentials_task: Option<Task<()>>,
580}
581
582impl ConfigurationView {
583    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
584        let api_key_editor = cx.new(|cx| {
585            let mut editor = Editor::single_line(window, cx);
586            editor.set_placeholder_text("sk-000000000000000000000000000000000000000000000000", cx);
587            editor
588        });
589
590        cx.observe(&state, |_, _, cx| {
591            cx.notify();
592        })
593        .detach();
594
595        let load_credentials_task = Some(cx.spawn_in(window, {
596            let state = state.clone();
597            async move |this, cx| {
598                if let Some(task) = state
599                    .update(cx, |state, cx| state.authenticate(cx))
600                    .log_err()
601                {
602                    // We don't log an error, because "not signed in" is also an error.
603                    let _ = task.await;
604                }
605
606                this.update(cx, |this, cx| {
607                    this.load_credentials_task = None;
608                    cx.notify();
609                })
610                .log_err();
611            }
612        }));
613
614        Self {
615            api_key_editor,
616            state,
617            load_credentials_task,
618        }
619    }
620
621    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
622        let api_key = self.api_key_editor.read(cx).text(cx);
623        if api_key.is_empty() {
624            return;
625        }
626
627        let state = self.state.clone();
628        cx.spawn_in(window, async move |_, cx| {
629            state
630                .update(cx, |state, cx| state.set_api_key(api_key, cx))?
631                .await
632        })
633        .detach_and_log_err(cx);
634
635        cx.notify();
636    }
637
638    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
639        self.api_key_editor
640            .update(cx, |editor, cx| editor.set_text("", window, cx));
641
642        let state = self.state.clone();
643        cx.spawn_in(window, async move |_, cx| {
644            state.update(cx, |state, cx| state.reset_api_key(cx))?.await
645        })
646        .detach_and_log_err(cx);
647
648        cx.notify();
649    }
650
651    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
652        let settings = ThemeSettings::get_global(cx);
653        let text_style = TextStyle {
654            color: cx.theme().colors().text,
655            font_family: settings.ui_font.family.clone(),
656            font_features: settings.ui_font.features.clone(),
657            font_fallbacks: settings.ui_font.fallbacks.clone(),
658            font_size: rems(0.875).into(),
659            font_weight: settings.ui_font.weight,
660            font_style: FontStyle::Normal,
661            line_height: relative(1.3),
662            white_space: WhiteSpace::Normal,
663            ..Default::default()
664        };
665        EditorElement::new(
666            &self.api_key_editor,
667            EditorStyle {
668                background: cx.theme().colors().editor_background,
669                local_player: cx.theme().players().local(),
670                text: text_style,
671                ..Default::default()
672            },
673        )
674    }
675
676    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
677        !self.state.read(cx).is_authenticated()
678    }
679}
680
681impl Render for ConfigurationView {
682    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
683        let env_var_set = self.state.read(cx).api_key_from_env;
684
685        if self.load_credentials_task.is_some() {
686            div().child(Label::new("Loading credentials...")).into_any()
687        } else if self.should_render_editor(cx) {
688            v_flex()
689                .size_full()
690                .on_action(cx.listener(Self::save_api_key))
691                .child(Label::new("To use Zed's assistant with OpenAI, you need to add an API key. Follow these steps:"))
692                .child(
693                    List::new()
694                        .child(InstructionListItem::new(
695                            "Create one by visiting",
696                            Some("OpenAI's console"),
697                            Some("https://platform.openai.com/api-keys"),
698                        ))
699                        .child(InstructionListItem::text_only(
700                            "Ensure your OpenAI account has credits",
701                        ))
702                        .child(InstructionListItem::text_only(
703                            "Paste your API key below and hit enter to start using the assistant",
704                        )),
705                )
706                .child(
707                    h_flex()
708                        .w_full()
709                        .my_2()
710                        .px_2()
711                        .py_1()
712                        .bg(cx.theme().colors().editor_background)
713                        .border_1()
714                        .border_color(cx.theme().colors().border)
715                        .rounded_sm()
716                        .child(self.render_api_key_editor(cx)),
717                )
718                .child(
719                    Label::new(
720                        format!("You can also assign the {OPENAI_API_KEY_VAR} environment variable and restart Zed."),
721                    )
722                    .size(LabelSize::Small).color(Color::Muted),
723                )
724                .child(
725                    Label::new(
726                        "Note that having a subscription for another service like GitHub Copilot won't work.".to_string(),
727                    )
728                    .size(LabelSize::Small).color(Color::Muted),
729                )
730                .into_any()
731        } else {
732            h_flex()
733                .mt_1()
734                .p_1()
735                .justify_between()
736                .rounded_md()
737                .border_1()
738                .border_color(cx.theme().colors().border)
739                .bg(cx.theme().colors().background)
740                .child(
741                    h_flex()
742                        .gap_1()
743                        .child(Icon::new(IconName::Check).color(Color::Success))
744                        .child(Label::new(if env_var_set {
745                            format!("API key set in {OPENAI_API_KEY_VAR} environment variable.")
746                        } else {
747                            "API key configured.".to_string()
748                        })),
749                )
750                .child(
751                    Button::new("reset-key", "Reset Key")
752                        .label_size(LabelSize::Small)
753                        .icon(Some(IconName::Trash))
754                        .icon_size(IconSize::Small)
755                        .icon_position(IconPosition::Start)
756                        .disabled(env_var_set)
757                        .when(env_var_set, |this| {
758                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {OPENAI_API_KEY_VAR} environment variable.")))
759                        })
760                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
761                )
762                .into_any()
763        }
764    }
765}