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