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