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: (request.tools.len() > 0).then(|| {
421            vec![google_ai::Tool {
422                function_declarations: request
423                    .tools
424                    .into_iter()
425                    .map(|tool| FunctionDeclaration {
426                        name: tool.name,
427                        description: tool.description,
428                        parameters: tool.input_schema,
429                    })
430                    .collect(),
431            }]
432        }),
433        tool_config: None,
434    }
435}
436
437pub fn map_to_language_model_completion_events(
438    events: Pin<Box<dyn Send + Stream<Item = Result<GenerateContentResponse>>>>,
439) -> impl Stream<Item = Result<LanguageModelCompletionEvent>> {
440    use std::sync::atomic::{AtomicU64, Ordering};
441
442    static TOOL_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
443
444    struct State {
445        events: Pin<Box<dyn Send + Stream<Item = Result<GenerateContentResponse>>>>,
446        usage: UsageMetadata,
447        stop_reason: StopReason,
448    }
449
450    futures::stream::unfold(
451        State {
452            events,
453            usage: UsageMetadata::default(),
454            stop_reason: StopReason::EndTurn,
455        },
456        |mut state| async move {
457            if let Some(event) = state.events.next().await {
458                match event {
459                    Ok(event) => {
460                        let mut events: Vec<Result<LanguageModelCompletionEvent>> = Vec::new();
461                        let mut wants_to_use_tool = false;
462                        if let Some(usage_metadata) = event.usage_metadata {
463                            update_usage(&mut state.usage, &usage_metadata);
464                            events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(
465                                convert_usage(&state.usage),
466                            )))
467                        }
468                        if let Some(candidates) = event.candidates {
469                            for candidate in candidates {
470                                if let Some(finish_reason) = candidate.finish_reason.as_deref() {
471                                    state.stop_reason = match finish_reason {
472                                        "STOP" => StopReason::EndTurn,
473                                        "MAX_TOKENS" => StopReason::MaxTokens,
474                                        _ => {
475                                            log::error!(
476                                                "Unexpected google finish_reason: {finish_reason}"
477                                            );
478                                            StopReason::EndTurn
479                                        }
480                                    };
481                                }
482                                candidate
483                                    .content
484                                    .parts
485                                    .into_iter()
486                                    .for_each(|part| match part {
487                                        Part::TextPart(text_part) => events.push(Ok(
488                                            LanguageModelCompletionEvent::Text(text_part.text),
489                                        )),
490                                        Part::InlineDataPart(_) => {}
491                                        Part::FunctionCallPart(function_call_part) => {
492                                            wants_to_use_tool = true;
493                                            let name: Arc<str> =
494                                                function_call_part.function_call.name.into();
495                                            let next_tool_id =
496                                                TOOL_CALL_COUNTER.fetch_add(1, Ordering::SeqCst);
497                                            let id: LanguageModelToolUseId =
498                                                format!("{}-{}", name, next_tool_id).into();
499
500                                            events.push(Ok(LanguageModelCompletionEvent::ToolUse(
501                                                LanguageModelToolUse {
502                                                    id,
503                                                    name,
504                                                    input: function_call_part.function_call.args,
505                                                },
506                                            )));
507                                        }
508                                        Part::FunctionResponsePart(_) => {}
509                                    });
510                            }
511                        }
512
513                        // Even when Gemini wants to use a Tool, the API
514                        // responds with `finish_reason: STOP`
515                        if wants_to_use_tool {
516                            state.stop_reason = StopReason::ToolUse;
517                        }
518                        events.push(Ok(LanguageModelCompletionEvent::Stop(state.stop_reason)));
519                        return Some((events, state));
520                    }
521                    Err(err) => {
522                        return Some((vec![Err(anyhow!(err))], state));
523                    }
524                }
525            }
526
527            None
528        },
529    )
530    .flat_map(futures::stream::iter)
531}
532
533pub fn count_google_tokens(
534    request: LanguageModelRequest,
535    cx: &App,
536) -> BoxFuture<'static, Result<usize>> {
537    // We couldn't use the GoogleLanguageModelProvider to count tokens because the github copilot doesn't have the access to google_ai directly.
538    // So we have to use tokenizer from tiktoken_rs to count tokens.
539    cx.background_spawn(async move {
540        let messages = request
541            .messages
542            .into_iter()
543            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
544                role: match message.role {
545                    Role::User => "user".into(),
546                    Role::Assistant => "assistant".into(),
547                    Role::System => "system".into(),
548                },
549                content: Some(message.string_contents()),
550                name: None,
551                function_call: None,
552            })
553            .collect::<Vec<_>>();
554
555        // Tiktoken doesn't yet support these models, so we manually use the
556        // same tokenizer as GPT-4.
557        tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
558    })
559    .boxed()
560}
561
562fn update_usage(usage: &mut UsageMetadata, new: &UsageMetadata) {
563    if let Some(prompt_token_count) = new.prompt_token_count {
564        usage.prompt_token_count = Some(prompt_token_count);
565    }
566    if let Some(cached_content_token_count) = new.cached_content_token_count {
567        usage.cached_content_token_count = Some(cached_content_token_count);
568    }
569    if let Some(candidates_token_count) = new.candidates_token_count {
570        usage.candidates_token_count = Some(candidates_token_count);
571    }
572    if let Some(tool_use_prompt_token_count) = new.tool_use_prompt_token_count {
573        usage.tool_use_prompt_token_count = Some(tool_use_prompt_token_count);
574    }
575    if let Some(thoughts_token_count) = new.thoughts_token_count {
576        usage.thoughts_token_count = Some(thoughts_token_count);
577    }
578    if let Some(total_token_count) = new.total_token_count {
579        usage.total_token_count = Some(total_token_count);
580    }
581}
582
583fn convert_usage(usage: &UsageMetadata) -> language_model::TokenUsage {
584    language_model::TokenUsage {
585        input_tokens: usage.prompt_token_count.unwrap_or(0) as u32,
586        output_tokens: usage.candidates_token_count.unwrap_or(0) as u32,
587        cache_read_input_tokens: usage.cached_content_token_count.unwrap_or(0) as u32,
588        cache_creation_input_tokens: 0,
589    }
590}
591
592struct ConfigurationView {
593    api_key_editor: Entity<Editor>,
594    state: gpui::Entity<State>,
595    load_credentials_task: Option<Task<()>>,
596}
597
598impl ConfigurationView {
599    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
600        cx.observe(&state, |_, _, cx| {
601            cx.notify();
602        })
603        .detach();
604
605        let load_credentials_task = Some(cx.spawn_in(window, {
606            let state = state.clone();
607            async move |this, cx| {
608                if let Some(task) = state
609                    .update(cx, |state, cx| state.authenticate(cx))
610                    .log_err()
611                {
612                    // We don't log an error, because "not signed in" is also an error.
613                    let _ = task.await;
614                }
615                this.update(cx, |this, cx| {
616                    this.load_credentials_task = None;
617                    cx.notify();
618                })
619                .log_err();
620            }
621        }));
622
623        Self {
624            api_key_editor: cx.new(|cx| {
625                let mut editor = Editor::single_line(window, cx);
626                editor.set_placeholder_text("AIzaSy...", cx);
627                editor
628            }),
629            state,
630            load_credentials_task,
631        }
632    }
633
634    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
635        let api_key = self.api_key_editor.read(cx).text(cx);
636        if api_key.is_empty() {
637            return;
638        }
639
640        let state = self.state.clone();
641        cx.spawn_in(window, async move |_, cx| {
642            state
643                .update(cx, |state, cx| state.set_api_key(api_key, cx))?
644                .await
645        })
646        .detach_and_log_err(cx);
647
648        cx.notify();
649    }
650
651    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
652        self.api_key_editor
653            .update(cx, |editor, cx| editor.set_text("", window, cx));
654
655        let state = self.state.clone();
656        cx.spawn_in(window, async move |_, cx| {
657            state.update(cx, |state, cx| state.reset_api_key(cx))?.await
658        })
659        .detach_and_log_err(cx);
660
661        cx.notify();
662    }
663
664    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
665        let settings = ThemeSettings::get_global(cx);
666        let text_style = TextStyle {
667            color: cx.theme().colors().text,
668            font_family: settings.ui_font.family.clone(),
669            font_features: settings.ui_font.features.clone(),
670            font_fallbacks: settings.ui_font.fallbacks.clone(),
671            font_size: rems(0.875).into(),
672            font_weight: settings.ui_font.weight,
673            font_style: FontStyle::Normal,
674            line_height: relative(1.3),
675            white_space: WhiteSpace::Normal,
676            ..Default::default()
677        };
678        EditorElement::new(
679            &self.api_key_editor,
680            EditorStyle {
681                background: cx.theme().colors().editor_background,
682                local_player: cx.theme().players().local(),
683                text: text_style,
684                ..Default::default()
685            },
686        )
687    }
688
689    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
690        !self.state.read(cx).is_authenticated()
691    }
692}
693
694impl Render for ConfigurationView {
695    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
696        let env_var_set = self.state.read(cx).api_key_from_env;
697
698        if self.load_credentials_task.is_some() {
699            div().child(Label::new("Loading credentials...")).into_any()
700        } else if self.should_render_editor(cx) {
701            v_flex()
702                .size_full()
703                .on_action(cx.listener(Self::save_api_key))
704                .child(Label::new("To use Zed's assistant with Google AI, you need to add an API key. Follow these steps:"))
705                .child(
706                    List::new()
707                        .child(InstructionListItem::new(
708                            "Create one by visiting",
709                            Some("Google AI's console"),
710                            Some("https://aistudio.google.com/app/apikey"),
711                        ))
712                        .child(InstructionListItem::text_only(
713                            "Paste your API key below and hit enter to start using the assistant",
714                        )),
715                )
716                .child(
717                    h_flex()
718                        .w_full()
719                        .my_2()
720                        .px_2()
721                        .py_1()
722                        .bg(cx.theme().colors().editor_background)
723                        .border_1()
724                        .border_color(cx.theme().colors().border_variant)
725                        .rounded_sm()
726                        .child(self.render_api_key_editor(cx)),
727                )
728                .child(
729                    Label::new(
730                        format!("You can also assign the {GOOGLE_AI_API_KEY_VAR} environment variable and restart Zed."),
731                    )
732                    .size(LabelSize::Small).color(Color::Muted),
733                )
734                .into_any()
735        } else {
736            h_flex()
737                .size_full()
738                .justify_between()
739                .child(
740                    h_flex()
741                        .gap_1()
742                        .child(Icon::new(IconName::Check).color(Color::Success))
743                        .child(Label::new(if env_var_set {
744                            format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
745                        } else {
746                            "API key configured.".to_string()
747                        })),
748                )
749                .child(
750                    Button::new("reset-key", "Reset key")
751                        .icon(Some(IconName::Trash))
752                        .icon_size(IconSize::Small)
753                        .icon_position(IconPosition::Start)
754                        .disabled(env_var_set)
755                        .when(env_var_set, |this| {
756                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable.")))
757                        })
758                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
759                )
760                .into_any()
761        }
762    }
763}