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