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