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