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                                                    raw_input: function_call_part
541                                                        .function_call
542                                                        .args
543                                                        .to_string(),
544                                                    input: function_call_part.function_call.args,
545                                                },
546                                            )));
547                                        }
548                                        Part::FunctionResponsePart(_) => {}
549                                    });
550                            }
551                        }
552
553                        // Even when Gemini wants to use a Tool, the API
554                        // responds with `finish_reason: STOP`
555                        if wants_to_use_tool {
556                            state.stop_reason = StopReason::ToolUse;
557                        }
558                        events.push(Ok(LanguageModelCompletionEvent::Stop(state.stop_reason)));
559                        return Some((events, state));
560                    }
561                    Err(err) => {
562                        return Some((vec![Err(anyhow!(err))], state));
563                    }
564                }
565            }
566
567            None
568        },
569    )
570    .flat_map(futures::stream::iter)
571}
572
573pub fn count_google_tokens(
574    request: LanguageModelRequest,
575    cx: &App,
576) -> BoxFuture<'static, Result<usize>> {
577    // We couldn't use the GoogleLanguageModelProvider to count tokens because the github copilot doesn't have the access to google_ai directly.
578    // So we have to use tokenizer from tiktoken_rs to count tokens.
579    cx.background_spawn(async move {
580        let messages = request
581            .messages
582            .into_iter()
583            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
584                role: match message.role {
585                    Role::User => "user".into(),
586                    Role::Assistant => "assistant".into(),
587                    Role::System => "system".into(),
588                },
589                content: Some(message.string_contents()),
590                name: None,
591                function_call: None,
592            })
593            .collect::<Vec<_>>();
594
595        // Tiktoken doesn't yet support these models, so we manually use the
596        // same tokenizer as GPT-4.
597        tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
598    })
599    .boxed()
600}
601
602fn update_usage(usage: &mut UsageMetadata, new: &UsageMetadata) {
603    if let Some(prompt_token_count) = new.prompt_token_count {
604        usage.prompt_token_count = Some(prompt_token_count);
605    }
606    if let Some(cached_content_token_count) = new.cached_content_token_count {
607        usage.cached_content_token_count = Some(cached_content_token_count);
608    }
609    if let Some(candidates_token_count) = new.candidates_token_count {
610        usage.candidates_token_count = Some(candidates_token_count);
611    }
612    if let Some(tool_use_prompt_token_count) = new.tool_use_prompt_token_count {
613        usage.tool_use_prompt_token_count = Some(tool_use_prompt_token_count);
614    }
615    if let Some(thoughts_token_count) = new.thoughts_token_count {
616        usage.thoughts_token_count = Some(thoughts_token_count);
617    }
618    if let Some(total_token_count) = new.total_token_count {
619        usage.total_token_count = Some(total_token_count);
620    }
621}
622
623fn convert_usage(usage: &UsageMetadata) -> language_model::TokenUsage {
624    language_model::TokenUsage {
625        input_tokens: usage.prompt_token_count.unwrap_or(0) as u32,
626        output_tokens: usage.candidates_token_count.unwrap_or(0) as u32,
627        cache_read_input_tokens: usage.cached_content_token_count.unwrap_or(0) as u32,
628        cache_creation_input_tokens: 0,
629    }
630}
631
632struct ConfigurationView {
633    api_key_editor: Entity<Editor>,
634    state: gpui::Entity<State>,
635    load_credentials_task: Option<Task<()>>,
636}
637
638impl ConfigurationView {
639    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
640        cx.observe(&state, |_, _, cx| {
641            cx.notify();
642        })
643        .detach();
644
645        let load_credentials_task = Some(cx.spawn_in(window, {
646            let state = state.clone();
647            async move |this, cx| {
648                if let Some(task) = state
649                    .update(cx, |state, cx| state.authenticate(cx))
650                    .log_err()
651                {
652                    // We don't log an error, because "not signed in" is also an error.
653                    let _ = task.await;
654                }
655                this.update(cx, |this, cx| {
656                    this.load_credentials_task = None;
657                    cx.notify();
658                })
659                .log_err();
660            }
661        }));
662
663        Self {
664            api_key_editor: cx.new(|cx| {
665                let mut editor = Editor::single_line(window, cx);
666                editor.set_placeholder_text("AIzaSy...", cx);
667                editor
668            }),
669            state,
670            load_credentials_task,
671        }
672    }
673
674    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
675        let api_key = self.api_key_editor.read(cx).text(cx);
676        if api_key.is_empty() {
677            return;
678        }
679
680        let state = self.state.clone();
681        cx.spawn_in(window, async move |_, cx| {
682            state
683                .update(cx, |state, cx| state.set_api_key(api_key, cx))?
684                .await
685        })
686        .detach_and_log_err(cx);
687
688        cx.notify();
689    }
690
691    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
692        self.api_key_editor
693            .update(cx, |editor, cx| editor.set_text("", window, cx));
694
695        let state = self.state.clone();
696        cx.spawn_in(window, async move |_, cx| {
697            state.update(cx, |state, cx| state.reset_api_key(cx))?.await
698        })
699        .detach_and_log_err(cx);
700
701        cx.notify();
702    }
703
704    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
705        let settings = ThemeSettings::get_global(cx);
706        let text_style = TextStyle {
707            color: cx.theme().colors().text,
708            font_family: settings.ui_font.family.clone(),
709            font_features: settings.ui_font.features.clone(),
710            font_fallbacks: settings.ui_font.fallbacks.clone(),
711            font_size: rems(0.875).into(),
712            font_weight: settings.ui_font.weight,
713            font_style: FontStyle::Normal,
714            line_height: relative(1.3),
715            white_space: WhiteSpace::Normal,
716            ..Default::default()
717        };
718        EditorElement::new(
719            &self.api_key_editor,
720            EditorStyle {
721                background: cx.theme().colors().editor_background,
722                local_player: cx.theme().players().local(),
723                text: text_style,
724                ..Default::default()
725            },
726        )
727    }
728
729    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
730        !self.state.read(cx).is_authenticated()
731    }
732}
733
734impl Render for ConfigurationView {
735    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
736        let env_var_set = self.state.read(cx).api_key_from_env;
737
738        if self.load_credentials_task.is_some() {
739            div().child(Label::new("Loading credentials...")).into_any()
740        } else if self.should_render_editor(cx) {
741            v_flex()
742                .size_full()
743                .on_action(cx.listener(Self::save_api_key))
744                .child(Label::new("To use Zed's assistant with Google AI, you need to add an API key. Follow these steps:"))
745                .child(
746                    List::new()
747                        .child(InstructionListItem::new(
748                            "Create one by visiting",
749                            Some("Google AI's console"),
750                            Some("https://aistudio.google.com/app/apikey"),
751                        ))
752                        .child(InstructionListItem::text_only(
753                            "Paste your API key below and hit enter to start using the assistant",
754                        )),
755                )
756                .child(
757                    h_flex()
758                        .w_full()
759                        .my_2()
760                        .px_2()
761                        .py_1()
762                        .bg(cx.theme().colors().editor_background)
763                        .border_1()
764                        .border_color(cx.theme().colors().border)
765                        .rounded_sm()
766                        .child(self.render_api_key_editor(cx)),
767                )
768                .child(
769                    Label::new(
770                        format!("You can also assign the {GOOGLE_AI_API_KEY_VAR} environment variable and restart Zed."),
771                    )
772                    .size(LabelSize::Small).color(Color::Muted),
773                )
774                .into_any()
775        } else {
776            h_flex()
777                .mt_1()
778                .p_1()
779                .justify_between()
780                .rounded_md()
781                .border_1()
782                .border_color(cx.theme().colors().border)
783                .bg(cx.theme().colors().background)
784                .child(
785                    h_flex()
786                        .gap_1()
787                        .child(Icon::new(IconName::Check).color(Color::Success))
788                        .child(Label::new(if env_var_set {
789                            format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
790                        } else {
791                            "API key configured.".to_string()
792                        })),
793                )
794                .child(
795                    Button::new("reset-key", "Reset Key")
796                        .label_size(LabelSize::Small)
797                        .icon(Some(IconName::Trash))
798                        .icon_size(IconSize::Small)
799                        .icon_position(IconPosition::Start)
800                        .disabled(env_var_set)
801                        .when(env_var_set, |this| {
802                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable.")))
803                        })
804                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
805                )
806                .into_any()
807        }
808    }
809}