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