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 }
603 events
604 }
605}
606
607pub fn count_google_tokens(
608 request: LanguageModelRequest,
609 cx: &App,
610) -> BoxFuture<'static, Result<usize>> {
611 // We couldn't use the GoogleLanguageModelProvider to count tokens because the github copilot doesn't have the access to google_ai directly.
612 // So we have to use tokenizer from tiktoken_rs to count tokens.
613 cx.background_spawn(async move {
614 let messages = request
615 .messages
616 .into_iter()
617 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
618 role: match message.role {
619 Role::User => "user".into(),
620 Role::Assistant => "assistant".into(),
621 Role::System => "system".into(),
622 },
623 content: Some(message.string_contents()),
624 name: None,
625 function_call: None,
626 })
627 .collect::<Vec<_>>();
628
629 // Tiktoken doesn't yet support these models, so we manually use the
630 // same tokenizer as GPT-4.
631 tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
632 })
633 .boxed()
634}
635
636fn update_usage(usage: &mut UsageMetadata, new: &UsageMetadata) {
637 if let Some(prompt_token_count) = new.prompt_token_count {
638 usage.prompt_token_count = Some(prompt_token_count);
639 }
640 if let Some(cached_content_token_count) = new.cached_content_token_count {
641 usage.cached_content_token_count = Some(cached_content_token_count);
642 }
643 if let Some(candidates_token_count) = new.candidates_token_count {
644 usage.candidates_token_count = Some(candidates_token_count);
645 }
646 if let Some(tool_use_prompt_token_count) = new.tool_use_prompt_token_count {
647 usage.tool_use_prompt_token_count = Some(tool_use_prompt_token_count);
648 }
649 if let Some(thoughts_token_count) = new.thoughts_token_count {
650 usage.thoughts_token_count = Some(thoughts_token_count);
651 }
652 if let Some(total_token_count) = new.total_token_count {
653 usage.total_token_count = Some(total_token_count);
654 }
655}
656
657fn convert_usage(usage: &UsageMetadata) -> language_model::TokenUsage {
658 language_model::TokenUsage {
659 input_tokens: usage.prompt_token_count.unwrap_or(0) as u32,
660 output_tokens: usage.candidates_token_count.unwrap_or(0) as u32,
661 cache_read_input_tokens: usage.cached_content_token_count.unwrap_or(0) as u32,
662 cache_creation_input_tokens: 0,
663 }
664}
665
666struct ConfigurationView {
667 api_key_editor: Entity<Editor>,
668 state: gpui::Entity<State>,
669 load_credentials_task: Option<Task<()>>,
670}
671
672impl ConfigurationView {
673 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
674 cx.observe(&state, |_, _, cx| {
675 cx.notify();
676 })
677 .detach();
678
679 let load_credentials_task = Some(cx.spawn_in(window, {
680 let state = state.clone();
681 async move |this, cx| {
682 if let Some(task) = state
683 .update(cx, |state, cx| state.authenticate(cx))
684 .log_err()
685 {
686 // We don't log an error, because "not signed in" is also an error.
687 let _ = task.await;
688 }
689 this.update(cx, |this, cx| {
690 this.load_credentials_task = None;
691 cx.notify();
692 })
693 .log_err();
694 }
695 }));
696
697 Self {
698 api_key_editor: cx.new(|cx| {
699 let mut editor = Editor::single_line(window, cx);
700 editor.set_placeholder_text("AIzaSy...", cx);
701 editor
702 }),
703 state,
704 load_credentials_task,
705 }
706 }
707
708 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
709 let api_key = self.api_key_editor.read(cx).text(cx);
710 if api_key.is_empty() {
711 return;
712 }
713
714 let state = self.state.clone();
715 cx.spawn_in(window, async move |_, cx| {
716 state
717 .update(cx, |state, cx| state.set_api_key(api_key, cx))?
718 .await
719 })
720 .detach_and_log_err(cx);
721
722 cx.notify();
723 }
724
725 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
726 self.api_key_editor
727 .update(cx, |editor, cx| editor.set_text("", window, cx));
728
729 let state = self.state.clone();
730 cx.spawn_in(window, async move |_, cx| {
731 state.update(cx, |state, cx| state.reset_api_key(cx))?.await
732 })
733 .detach_and_log_err(cx);
734
735 cx.notify();
736 }
737
738 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
739 let settings = ThemeSettings::get_global(cx);
740 let text_style = TextStyle {
741 color: cx.theme().colors().text,
742 font_family: settings.ui_font.family.clone(),
743 font_features: settings.ui_font.features.clone(),
744 font_fallbacks: settings.ui_font.fallbacks.clone(),
745 font_size: rems(0.875).into(),
746 font_weight: settings.ui_font.weight,
747 font_style: FontStyle::Normal,
748 line_height: relative(1.3),
749 white_space: WhiteSpace::Normal,
750 ..Default::default()
751 };
752 EditorElement::new(
753 &self.api_key_editor,
754 EditorStyle {
755 background: cx.theme().colors().editor_background,
756 local_player: cx.theme().players().local(),
757 text: text_style,
758 ..Default::default()
759 },
760 )
761 }
762
763 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
764 !self.state.read(cx).is_authenticated()
765 }
766}
767
768impl Render for ConfigurationView {
769 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
770 let env_var_set = self.state.read(cx).api_key_from_env;
771
772 if self.load_credentials_task.is_some() {
773 div().child(Label::new("Loading credentials...")).into_any()
774 } else if self.should_render_editor(cx) {
775 v_flex()
776 .size_full()
777 .on_action(cx.listener(Self::save_api_key))
778 .child(Label::new("To use Zed's assistant with Google AI, you need to add an API key. Follow these steps:"))
779 .child(
780 List::new()
781 .child(InstructionListItem::new(
782 "Create one by visiting",
783 Some("Google AI's console"),
784 Some("https://aistudio.google.com/app/apikey"),
785 ))
786 .child(InstructionListItem::text_only(
787 "Paste your API key below and hit enter to start using the assistant",
788 )),
789 )
790 .child(
791 h_flex()
792 .w_full()
793 .my_2()
794 .px_2()
795 .py_1()
796 .bg(cx.theme().colors().editor_background)
797 .border_1()
798 .border_color(cx.theme().colors().border)
799 .rounded_sm()
800 .child(self.render_api_key_editor(cx)),
801 )
802 .child(
803 Label::new(
804 format!("You can also assign the {GOOGLE_AI_API_KEY_VAR} environment variable and restart Zed."),
805 )
806 .size(LabelSize::Small).color(Color::Muted),
807 )
808 .into_any()
809 } else {
810 h_flex()
811 .mt_1()
812 .p_1()
813 .justify_between()
814 .rounded_md()
815 .border_1()
816 .border_color(cx.theme().colors().border)
817 .bg(cx.theme().colors().background)
818 .child(
819 h_flex()
820 .gap_1()
821 .child(Icon::new(IconName::Check).color(Color::Success))
822 .child(Label::new(if env_var_set {
823 format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
824 } else {
825 "API key configured.".to_string()
826 })),
827 )
828 .child(
829 Button::new("reset-key", "Reset Key")
830 .label_size(LabelSize::Small)
831 .icon(Some(IconName::Trash))
832 .icon_size(IconSize::Small)
833 .icon_position(IconPosition::Start)
834 .disabled(env_var_set)
835 .when(env_var_set, |this| {
836 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable.")))
837 })
838 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
839 )
840 .into_any()
841 }
842 }
843}