1use anyhow::{Context as _, Result, anyhow};
2use collections::BTreeMap;
3use credentials_provider::CredentialsProvider;
4use editor::{Editor, EditorElement, EditorStyle};
5use futures::{FutureExt, Stream, StreamExt, future::BoxFuture};
6use google_ai::{
7 FunctionDeclaration, GenerateContentResponse, Part, SystemInstruction, UsageMetadata,
8};
9use gpui::{
10 AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
11};
12use http_client::HttpClient;
13use language_model::{
14 AuthenticateError, LanguageModelCompletionError, LanguageModelCompletionEvent,
15 LanguageModelToolSchemaFormat, LanguageModelToolUse, LanguageModelToolUseId, MessageContent,
16 StopReason,
17};
18use language_model::{
19 LanguageModel, LanguageModelId, LanguageModelName, LanguageModelProvider,
20 LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
21 LanguageModelRequest, RateLimiter, Role,
22};
23use schemars::JsonSchema;
24use serde::{Deserialize, Serialize};
25use settings::{Settings, SettingsStore};
26use std::pin::Pin;
27use std::sync::Arc;
28use strum::IntoEnumIterator;
29use theme::ThemeSettings;
30use ui::{Icon, IconName, List, Tooltip, prelude::*};
31use util::ResultExt;
32
33use crate::AllLanguageModelSettings;
34use crate::ui::InstructionListItem;
35
36const PROVIDER_ID: &str = "google";
37const PROVIDER_NAME: &str = "Google AI";
38
39#[derive(Default, Clone, Debug, PartialEq)]
40pub struct GoogleSettings {
41 pub api_url: String,
42 pub available_models: Vec<AvailableModel>,
43}
44
45#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
46pub struct AvailableModel {
47 name: String,
48 display_name: Option<String>,
49 max_tokens: usize,
50}
51
52pub struct GoogleLanguageModelProvider {
53 http_client: Arc<dyn HttpClient>,
54 state: gpui::Entity<State>,
55}
56
57pub struct State {
58 api_key: Option<String>,
59 api_key_from_env: bool,
60 _subscription: Subscription,
61}
62
63const GOOGLE_AI_API_KEY_VAR: &str = "GOOGLE_AI_API_KEY";
64
65impl State {
66 fn is_authenticated(&self) -> bool {
67 self.api_key.is_some()
68 }
69
70 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
71 let credentials_provider = <dyn CredentialsProvider>::global(cx);
72 let api_url = AllLanguageModelSettings::get_global(cx)
73 .google
74 .api_url
75 .clone();
76 cx.spawn(async move |this, cx| {
77 credentials_provider
78 .delete_credentials(&api_url, &cx)
79 .await
80 .log_err();
81 this.update(cx, |this, cx| {
82 this.api_key = None;
83 this.api_key_from_env = false;
84 cx.notify();
85 })
86 })
87 }
88
89 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
90 let credentials_provider = <dyn CredentialsProvider>::global(cx);
91 let api_url = AllLanguageModelSettings::get_global(cx)
92 .google
93 .api_url
94 .clone();
95 cx.spawn(async move |this, cx| {
96 credentials_provider
97 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
98 .await?;
99 this.update(cx, |this, cx| {
100 this.api_key = Some(api_key);
101 cx.notify();
102 })
103 })
104 }
105
106 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
107 if self.is_authenticated() {
108 return Task::ready(Ok(()));
109 }
110
111 let credentials_provider = <dyn CredentialsProvider>::global(cx);
112 let api_url = AllLanguageModelSettings::get_global(cx)
113 .google
114 .api_url
115 .clone();
116
117 cx.spawn(async move |this, cx| {
118 let (api_key, from_env) = if let Ok(api_key) = std::env::var(GOOGLE_AI_API_KEY_VAR) {
119 (api_key, true)
120 } else {
121 let (_, api_key) = credentials_provider
122 .read_credentials(&api_url, &cx)
123 .await?
124 .ok_or(AuthenticateError::CredentialsNotFound)?;
125 (
126 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
127 false,
128 )
129 };
130
131 this.update(cx, |this, cx| {
132 this.api_key = Some(api_key);
133 this.api_key_from_env = from_env;
134 cx.notify();
135 })?;
136
137 Ok(())
138 })
139 }
140}
141
142impl GoogleLanguageModelProvider {
143 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
144 let state = cx.new(|cx| State {
145 api_key: None,
146 api_key_from_env: false,
147 _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
148 cx.notify();
149 }),
150 });
151
152 Self { http_client, state }
153 }
154
155 fn create_language_model(&self, model: google_ai::Model) -> Arc<dyn LanguageModel> {
156 Arc::new(GoogleLanguageModel {
157 id: LanguageModelId::from(model.id().to_string()),
158 model,
159 state: self.state.clone(),
160 http_client: self.http_client.clone(),
161 request_limiter: RateLimiter::new(4),
162 })
163 }
164}
165
166impl LanguageModelProviderState for GoogleLanguageModelProvider {
167 type ObservableEntity = State;
168
169 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
170 Some(self.state.clone())
171 }
172}
173
174impl LanguageModelProvider for GoogleLanguageModelProvider {
175 fn id(&self) -> LanguageModelProviderId {
176 LanguageModelProviderId(PROVIDER_ID.into())
177 }
178
179 fn name(&self) -> LanguageModelProviderName {
180 LanguageModelProviderName(PROVIDER_NAME.into())
181 }
182
183 fn icon(&self) -> IconName {
184 IconName::AiGoogle
185 }
186
187 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
188 Some(self.create_language_model(google_ai::Model::default()))
189 }
190
191 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
192 Some(self.create_language_model(google_ai::Model::default_fast()))
193 }
194
195 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
196 let mut models = BTreeMap::default();
197
198 // Add base models from google_ai::Model::iter()
199 for model in google_ai::Model::iter() {
200 if !matches!(model, google_ai::Model::Custom { .. }) {
201 models.insert(model.id().to_string(), model);
202 }
203 }
204
205 // Override with available models from settings
206 for model in &AllLanguageModelSettings::get_global(cx)
207 .google
208 .available_models
209 {
210 models.insert(
211 model.name.clone(),
212 google_ai::Model::Custom {
213 name: model.name.clone(),
214 display_name: model.display_name.clone(),
215 max_tokens: model.max_tokens,
216 },
217 );
218 }
219
220 models
221 .into_values()
222 .map(|model| {
223 Arc::new(GoogleLanguageModel {
224 id: LanguageModelId::from(model.id().to_string()),
225 model,
226 state: self.state.clone(),
227 http_client: self.http_client.clone(),
228 request_limiter: RateLimiter::new(4),
229 }) as Arc<dyn LanguageModel>
230 })
231 .collect()
232 }
233
234 fn is_authenticated(&self, cx: &App) -> bool {
235 self.state.read(cx).is_authenticated()
236 }
237
238 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
239 self.state.update(cx, |state, cx| state.authenticate(cx))
240 }
241
242 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
243 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
244 .into()
245 }
246
247 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
248 self.state.update(cx, |state, cx| state.reset_api_key(cx))
249 }
250}
251
252pub struct GoogleLanguageModel {
253 id: LanguageModelId,
254 model: google_ai::Model,
255 state: gpui::Entity<State>,
256 http_client: Arc<dyn HttpClient>,
257 request_limiter: RateLimiter,
258}
259
260impl GoogleLanguageModel {
261 fn stream_completion(
262 &self,
263 request: google_ai::GenerateContentRequest,
264 cx: &AsyncApp,
265 ) -> BoxFuture<
266 'static,
267 Result<futures::stream::BoxStream<'static, Result<GenerateContentResponse>>>,
268 > {
269 let http_client = self.http_client.clone();
270
271 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
272 let settings = &AllLanguageModelSettings::get_global(cx).google;
273 (state.api_key.clone(), settings.api_url.clone())
274 }) else {
275 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
276 };
277
278 async move {
279 let api_key = api_key.ok_or_else(|| anyhow!("Missing Google API key"))?;
280 let request = google_ai::stream_generate_content(
281 http_client.as_ref(),
282 &api_url,
283 &api_key,
284 request,
285 );
286 request.await.context("failed to stream completion")
287 }
288 .boxed()
289 }
290}
291
292impl LanguageModel for GoogleLanguageModel {
293 fn id(&self) -> LanguageModelId {
294 self.id.clone()
295 }
296
297 fn name(&self) -> LanguageModelName {
298 LanguageModelName::from(self.model.display_name().to_string())
299 }
300
301 fn provider_id(&self) -> LanguageModelProviderId {
302 LanguageModelProviderId(PROVIDER_ID.into())
303 }
304
305 fn provider_name(&self) -> LanguageModelProviderName {
306 LanguageModelProviderName(PROVIDER_NAME.into())
307 }
308
309 fn supports_tools(&self) -> bool {
310 true
311 }
312
313 fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
314 LanguageModelToolSchemaFormat::JsonSchemaSubset
315 }
316
317 fn telemetry_id(&self) -> String {
318 format!("google/{}", self.model.id())
319 }
320
321 fn max_token_count(&self) -> usize {
322 self.model.max_token_count()
323 }
324
325 fn count_tokens(
326 &self,
327 request: LanguageModelRequest,
328 cx: &App,
329 ) -> BoxFuture<'static, Result<usize>> {
330 let request = into_google(request, self.model.id().to_string());
331 let http_client = self.http_client.clone();
332 let api_key = self.state.read(cx).api_key.clone();
333
334 let settings = &AllLanguageModelSettings::get_global(cx).google;
335 let api_url = settings.api_url.clone();
336
337 async move {
338 let api_key = api_key.ok_or_else(|| anyhow!("Missing Google API key"))?;
339 let response = google_ai::count_tokens(
340 http_client.as_ref(),
341 &api_url,
342 &api_key,
343 google_ai::CountTokensRequest {
344 contents: request.contents,
345 },
346 )
347 .await?;
348 Ok(response.total_tokens)
349 }
350 .boxed()
351 }
352
353 fn stream_completion(
354 &self,
355 request: LanguageModelRequest,
356 cx: &AsyncApp,
357 ) -> BoxFuture<
358 'static,
359 Result<
360 futures::stream::BoxStream<
361 'static,
362 Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
363 >,
364 >,
365 > {
366 let request = into_google(request, self.model.id().to_string());
367 let request = self.stream_completion(request, cx);
368 let future = self.request_limiter.stream(async move {
369 let response = request
370 .await
371 .map_err(|err| LanguageModelCompletionError::Other(anyhow!(err)))?;
372 Ok(map_to_language_model_completion_events(response))
373 });
374 async move { Ok(future.await?.boxed()) }.boxed()
375 }
376}
377
378pub fn into_google(
379 mut request: LanguageModelRequest,
380 model: String,
381) -> google_ai::GenerateContentRequest {
382 fn map_content(content: Vec<MessageContent>) -> Vec<Part> {
383 content
384 .into_iter()
385 .filter_map(|content| match content {
386 language_model::MessageContent::Text(text)
387 | language_model::MessageContent::Thinking { text, .. } => {
388 if !text.is_empty() {
389 Some(Part::TextPart(google_ai::TextPart { text }))
390 } else {
391 None
392 }
393 }
394 language_model::MessageContent::RedactedThinking(_) => None,
395 language_model::MessageContent::Image(image) => {
396 Some(Part::InlineDataPart(google_ai::InlineDataPart {
397 inline_data: google_ai::GenerativeContentBlob {
398 mime_type: "image/png".to_string(),
399 data: image.source.to_string(),
400 },
401 }))
402 }
403 language_model::MessageContent::ToolUse(tool_use) => {
404 Some(Part::FunctionCallPart(google_ai::FunctionCallPart {
405 function_call: google_ai::FunctionCall {
406 name: tool_use.name.to_string(),
407 args: tool_use.input,
408 },
409 }))
410 }
411 language_model::MessageContent::ToolResult(tool_result) => Some(
412 Part::FunctionResponsePart(google_ai::FunctionResponsePart {
413 function_response: google_ai::FunctionResponse {
414 name: tool_result.tool_name.to_string(),
415 // The API expects a valid JSON object
416 response: serde_json::json!({
417 "output": tool_result.content
418 }),
419 },
420 }),
421 ),
422 })
423 .collect()
424 }
425
426 let system_instructions = if request
427 .messages
428 .first()
429 .map_or(false, |msg| matches!(msg.role, Role::System))
430 {
431 let message = request.messages.remove(0);
432 Some(SystemInstruction {
433 parts: map_content(message.content),
434 })
435 } else {
436 None
437 };
438
439 google_ai::GenerateContentRequest {
440 model,
441 system_instruction: system_instructions,
442 contents: request
443 .messages
444 .into_iter()
445 .map(|message| google_ai::Content {
446 parts: map_content(message.content),
447 role: match message.role {
448 Role::User => google_ai::Role::User,
449 Role::Assistant => google_ai::Role::Model,
450 Role::System => google_ai::Role::User, // Google AI doesn't have a system role
451 },
452 })
453 .collect(),
454 generation_config: Some(google_ai::GenerationConfig {
455 candidate_count: Some(1),
456 stop_sequences: Some(request.stop),
457 max_output_tokens: None,
458 temperature: request.temperature.map(|t| t as f64).or(Some(1.0)),
459 top_p: None,
460 top_k: None,
461 }),
462 safety_settings: None,
463 tools: (request.tools.len() > 0).then(|| {
464 vec![google_ai::Tool {
465 function_declarations: request
466 .tools
467 .into_iter()
468 .map(|tool| FunctionDeclaration {
469 name: tool.name,
470 description: tool.description,
471 parameters: tool.input_schema,
472 })
473 .collect(),
474 }]
475 }),
476 tool_config: None,
477 }
478}
479
480pub fn map_to_language_model_completion_events(
481 events: Pin<Box<dyn Send + Stream<Item = Result<GenerateContentResponse>>>>,
482) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
483 use std::sync::atomic::{AtomicU64, Ordering};
484
485 static TOOL_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
486
487 struct State {
488 events: Pin<Box<dyn Send + Stream<Item = Result<GenerateContentResponse>>>>,
489 usage: UsageMetadata,
490 stop_reason: StopReason,
491 }
492
493 futures::stream::unfold(
494 State {
495 events,
496 usage: UsageMetadata::default(),
497 stop_reason: StopReason::EndTurn,
498 },
499 |mut state| async move {
500 if let Some(event) = state.events.next().await {
501 match event {
502 Ok(event) => {
503 let mut events: Vec<_> = Vec::new();
504 let mut wants_to_use_tool = false;
505 if let Some(usage_metadata) = event.usage_metadata {
506 update_usage(&mut state.usage, &usage_metadata);
507 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(
508 convert_usage(&state.usage),
509 )))
510 }
511 if let Some(candidates) = event.candidates {
512 for candidate in candidates {
513 if let Some(finish_reason) = candidate.finish_reason.as_deref() {
514 state.stop_reason = match finish_reason {
515 "STOP" => StopReason::EndTurn,
516 "MAX_TOKENS" => StopReason::MaxTokens,
517 _ => {
518 log::error!(
519 "Unexpected google finish_reason: {finish_reason}"
520 );
521 StopReason::EndTurn
522 }
523 };
524 }
525 candidate
526 .content
527 .parts
528 .into_iter()
529 .for_each(|part| match part {
530 Part::TextPart(text_part) => events.push(Ok(
531 LanguageModelCompletionEvent::Text(text_part.text),
532 )),
533 Part::InlineDataPart(_) => {}
534 Part::FunctionCallPart(function_call_part) => {
535 wants_to_use_tool = true;
536 let name: Arc<str> =
537 function_call_part.function_call.name.into();
538 let next_tool_id =
539 TOOL_CALL_COUNTER.fetch_add(1, Ordering::SeqCst);
540 let id: LanguageModelToolUseId =
541 format!("{}-{}", name, next_tool_id).into();
542
543 events.push(Ok(LanguageModelCompletionEvent::ToolUse(
544 LanguageModelToolUse {
545 id,
546 name,
547 is_input_complete: true,
548 raw_input: function_call_part
549 .function_call
550 .args
551 .to_string(),
552 input: function_call_part.function_call.args,
553 },
554 )));
555 }
556 Part::FunctionResponsePart(_) => {}
557 });
558 }
559 }
560
561 // Even when Gemini wants to use a Tool, the API
562 // responds with `finish_reason: STOP`
563 if wants_to_use_tool {
564 state.stop_reason = StopReason::ToolUse;
565 }
566 events.push(Ok(LanguageModelCompletionEvent::Stop(state.stop_reason)));
567 return Some((events, state));
568 }
569 Err(err) => {
570 return Some((
571 vec![Err(LanguageModelCompletionError::Other(anyhow!(err)))],
572 state,
573 ));
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)
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 .mt_1()
789 .p_1()
790 .justify_between()
791 .rounded_md()
792 .border_1()
793 .border_color(cx.theme().colors().border)
794 .bg(cx.theme().colors().background)
795 .child(
796 h_flex()
797 .gap_1()
798 .child(Icon::new(IconName::Check).color(Color::Success))
799 .child(Label::new(if env_var_set {
800 format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
801 } else {
802 "API key configured.".to_string()
803 })),
804 )
805 .child(
806 Button::new("reset-key", "Reset Key")
807 .label_size(LabelSize::Small)
808 .icon(Some(IconName::Trash))
809 .icon_size(IconSize::Small)
810 .icon_position(IconPosition::Start)
811 .disabled(env_var_set)
812 .when(env_var_set, |this| {
813 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable.")))
814 })
815 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
816 )
817 .into_any()
818 }
819 }
820}