google.rs

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