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