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