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(vec![google_ai::Tool {
476 function_declarations: request
477 .tools
478 .into_iter()
479 .map(|tool| FunctionDeclaration {
480 name: tool.name,
481 description: tool.description,
482 parameters: tool.input_schema,
483 })
484 .collect(),
485 }]),
486 tool_config: None,
487 }
488}
489
490pub fn map_to_language_model_completion_events(
491 events: Pin<Box<dyn Send + Stream<Item = Result<GenerateContentResponse>>>>,
492) -> impl Stream<Item = Result<LanguageModelCompletionEvent>> {
493 use std::sync::atomic::{AtomicU64, Ordering};
494
495 static TOOL_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
496
497 struct State {
498 events: Pin<Box<dyn Send + Stream<Item = Result<GenerateContentResponse>>>>,
499 usage: UsageMetadata,
500 stop_reason: StopReason,
501 }
502
503 futures::stream::unfold(
504 State {
505 events,
506 usage: UsageMetadata::default(),
507 stop_reason: StopReason::EndTurn,
508 },
509 |mut state| async move {
510 if let Some(event) = state.events.next().await {
511 match event {
512 Ok(event) => {
513 let mut events: Vec<Result<LanguageModelCompletionEvent>> = Vec::new();
514 let mut wants_to_use_tool = false;
515 if let Some(usage_metadata) = event.usage_metadata {
516 update_usage(&mut state.usage, &usage_metadata);
517 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(
518 convert_usage(&state.usage),
519 )))
520 }
521 if let Some(candidates) = event.candidates {
522 for candidate in candidates {
523 if let Some(finish_reason) = candidate.finish_reason.as_deref() {
524 state.stop_reason = match finish_reason {
525 "STOP" => StopReason::EndTurn,
526 "MAX_TOKENS" => StopReason::MaxTokens,
527 _ => {
528 log::error!(
529 "Unexpected google finish_reason: {finish_reason}"
530 );
531 StopReason::EndTurn
532 }
533 };
534 }
535 candidate
536 .content
537 .parts
538 .into_iter()
539 .for_each(|part| match part {
540 Part::TextPart(text_part) => events.push(Ok(
541 LanguageModelCompletionEvent::Text(text_part.text),
542 )),
543 Part::InlineDataPart(_) => {}
544 Part::FunctionCallPart(function_call_part) => {
545 wants_to_use_tool = true;
546 let name: Arc<str> =
547 function_call_part.function_call.name.into();
548 let next_tool_id =
549 TOOL_CALL_COUNTER.fetch_add(1, Ordering::SeqCst);
550 let id: LanguageModelToolUseId =
551 format!("{}-{}", name, next_tool_id).into();
552
553 events.push(Ok(LanguageModelCompletionEvent::ToolUse(
554 LanguageModelToolUse {
555 id,
556 name,
557 input: function_call_part.function_call.args,
558 },
559 )));
560 }
561 Part::FunctionResponsePart(_) => {}
562 });
563 }
564 }
565
566 // Even when Gemini wants to use a Tool, the API
567 // responds with `finish_reason: STOP`
568 if wants_to_use_tool {
569 state.stop_reason = StopReason::ToolUse;
570 }
571 events.push(Ok(LanguageModelCompletionEvent::Stop(state.stop_reason)));
572 return Some((events, state));
573 }
574 Err(err) => {
575 return Some((vec![Err(anyhow!(err))], state));
576 }
577 }
578 }
579
580 None
581 },
582 )
583 .flat_map(futures::stream::iter)
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_variant)
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 .size_full()
791 .justify_between()
792 .child(
793 h_flex()
794 .gap_1()
795 .child(Icon::new(IconName::Check).color(Color::Success))
796 .child(Label::new(if env_var_set {
797 format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
798 } else {
799 "API key configured.".to_string()
800 })),
801 )
802 .child(
803 Button::new("reset-key", "Reset key")
804 .icon(Some(IconName::Trash))
805 .icon_size(IconSize::Small)
806 .icon_position(IconPosition::Start)
807 .disabled(env_var_set)
808 .when(env_var_set, |this| {
809 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable.")))
810 })
811 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
812 )
813 .into_any()
814 }
815 }
816}