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