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