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