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