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