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