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