1use anyhow::{anyhow, Context as _, Result};
2use collections::BTreeMap;
3use credentials_provider::CredentialsProvider;
4use editor::{Editor, EditorElement, EditorStyle};
5use futures::{future::BoxFuture, FutureExt, StreamExt};
6use google_ai::stream_generate_content;
7use gpui::{
8 AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,
9};
10use http_client::HttpClient;
11use language_model::{AuthenticateError, LanguageModelCompletionEvent};
12use language_model::{
13 LanguageModel, LanguageModelId, LanguageModelName, LanguageModelProvider,
14 LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
15 LanguageModelRequest, RateLimiter, Role,
16};
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19use settings::{Settings, SettingsStore};
20use std::{future, sync::Arc};
21use strum::IntoEnumIterator;
22use theme::ThemeSettings;
23use ui::{prelude::*, Icon, IconName, Tooltip};
24use util::ResultExt;
25
26use crate::AllLanguageModelSettings;
27
28const PROVIDER_ID: &str = "google";
29const PROVIDER_NAME: &str = "Google AI";
30
31#[derive(Default, Clone, Debug, PartialEq)]
32pub struct GoogleSettings {
33 pub api_url: String,
34 pub available_models: Vec<AvailableModel>,
35}
36
37#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
38pub struct AvailableModel {
39 name: String,
40 display_name: Option<String>,
41 max_tokens: usize,
42}
43
44pub struct GoogleLanguageModelProvider {
45 http_client: Arc<dyn HttpClient>,
46 state: gpui::Entity<State>,
47}
48
49pub struct State {
50 api_key: Option<String>,
51 api_key_from_env: bool,
52 _subscription: Subscription,
53}
54
55const GOOGLE_AI_API_KEY_VAR: &str = "GOOGLE_AI_API_KEY";
56
57impl State {
58 fn is_authenticated(&self) -> bool {
59 self.api_key.is_some()
60 }
61
62 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
63 let credentials_provider = <dyn CredentialsProvider>::global(cx);
64 let api_url = AllLanguageModelSettings::get_global(cx)
65 .google
66 .api_url
67 .clone();
68 cx.spawn(|this, mut cx| async move {
69 credentials_provider
70 .delete_credentials(&api_url, &cx)
71 .await
72 .log_err();
73 this.update(&mut cx, |this, cx| {
74 this.api_key = None;
75 this.api_key_from_env = false;
76 cx.notify();
77 })
78 })
79 }
80
81 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
82 let credentials_provider = <dyn CredentialsProvider>::global(cx);
83 let api_url = AllLanguageModelSettings::get_global(cx)
84 .google
85 .api_url
86 .clone();
87 cx.spawn(|this, mut cx| async move {
88 credentials_provider
89 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
90 .await?;
91 this.update(&mut cx, |this, cx| {
92 this.api_key = Some(api_key);
93 cx.notify();
94 })
95 })
96 }
97
98 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
99 if self.is_authenticated() {
100 return Task::ready(Ok(()));
101 }
102
103 let credentials_provider = <dyn CredentialsProvider>::global(cx);
104 let api_url = AllLanguageModelSettings::get_global(cx)
105 .google
106 .api_url
107 .clone();
108
109 cx.spawn(|this, mut cx| async move {
110 let (api_key, from_env) = if let Ok(api_key) = std::env::var(GOOGLE_AI_API_KEY_VAR) {
111 (api_key, true)
112 } else {
113 let (_, api_key) = credentials_provider
114 .read_credentials(&api_url, &cx)
115 .await?
116 .ok_or(AuthenticateError::CredentialsNotFound)?;
117 (
118 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
119 false,
120 )
121 };
122
123 this.update(&mut cx, |this, cx| {
124 this.api_key = Some(api_key);
125 this.api_key_from_env = from_env;
126 cx.notify();
127 })?;
128
129 Ok(())
130 })
131 }
132}
133
134impl GoogleLanguageModelProvider {
135 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
136 let state = cx.new(|cx| State {
137 api_key: None,
138 api_key_from_env: false,
139 _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
140 cx.notify();
141 }),
142 });
143
144 Self { http_client, state }
145 }
146}
147
148impl LanguageModelProviderState for GoogleLanguageModelProvider {
149 type ObservableEntity = State;
150
151 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
152 Some(self.state.clone())
153 }
154}
155
156impl LanguageModelProvider for GoogleLanguageModelProvider {
157 fn id(&self) -> LanguageModelProviderId {
158 LanguageModelProviderId(PROVIDER_ID.into())
159 }
160
161 fn name(&self) -> LanguageModelProviderName {
162 LanguageModelProviderName(PROVIDER_NAME.into())
163 }
164
165 fn icon(&self) -> IconName {
166 IconName::AiGoogle
167 }
168
169 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
170 let model = google_ai::Model::default();
171 Some(Arc::new(GoogleLanguageModel {
172 id: LanguageModelId::from(model.id().to_string()),
173 model,
174 state: self.state.clone(),
175 http_client: self.http_client.clone(),
176 rate_limiter: RateLimiter::new(4),
177 }))
178 }
179
180 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
181 let mut models = BTreeMap::default();
182
183 // Add base models from google_ai::Model::iter()
184 for model in google_ai::Model::iter() {
185 if !matches!(model, google_ai::Model::Custom { .. }) {
186 models.insert(model.id().to_string(), model);
187 }
188 }
189
190 // Override with available models from settings
191 for model in &AllLanguageModelSettings::get_global(cx)
192 .google
193 .available_models
194 {
195 models.insert(
196 model.name.clone(),
197 google_ai::Model::Custom {
198 name: model.name.clone(),
199 display_name: model.display_name.clone(),
200 max_tokens: model.max_tokens,
201 },
202 );
203 }
204
205 models
206 .into_values()
207 .map(|model| {
208 Arc::new(GoogleLanguageModel {
209 id: LanguageModelId::from(model.id().to_string()),
210 model,
211 state: self.state.clone(),
212 http_client: self.http_client.clone(),
213 rate_limiter: RateLimiter::new(4),
214 }) as Arc<dyn LanguageModel>
215 })
216 .collect()
217 }
218
219 fn is_authenticated(&self, cx: &App) -> bool {
220 self.state.read(cx).is_authenticated()
221 }
222
223 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
224 self.state.update(cx, |state, cx| state.authenticate(cx))
225 }
226
227 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
228 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
229 .into()
230 }
231
232 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
233 self.state.update(cx, |state, cx| state.reset_api_key(cx))
234 }
235}
236
237pub struct GoogleLanguageModel {
238 id: LanguageModelId,
239 model: google_ai::Model,
240 state: gpui::Entity<State>,
241 http_client: Arc<dyn HttpClient>,
242 rate_limiter: RateLimiter,
243}
244
245impl LanguageModel for GoogleLanguageModel {
246 fn id(&self) -> LanguageModelId {
247 self.id.clone()
248 }
249
250 fn name(&self) -> LanguageModelName {
251 LanguageModelName::from(self.model.display_name().to_string())
252 }
253
254 fn provider_id(&self) -> LanguageModelProviderId {
255 LanguageModelProviderId(PROVIDER_ID.into())
256 }
257
258 fn provider_name(&self) -> LanguageModelProviderName {
259 LanguageModelProviderName(PROVIDER_NAME.into())
260 }
261
262 fn telemetry_id(&self) -> String {
263 format!("google/{}", self.model.id())
264 }
265
266 fn max_token_count(&self) -> usize {
267 self.model.max_token_count()
268 }
269
270 fn count_tokens(
271 &self,
272 request: LanguageModelRequest,
273 cx: &App,
274 ) -> BoxFuture<'static, Result<usize>> {
275 let request = into_google(request, self.model.id().to_string());
276 let http_client = self.http_client.clone();
277 let api_key = self.state.read(cx).api_key.clone();
278
279 let settings = &AllLanguageModelSettings::get_global(cx).google;
280 let api_url = settings.api_url.clone();
281
282 async move {
283 let api_key = api_key.ok_or_else(|| anyhow!("Missing Google API key"))?;
284 let response = google_ai::count_tokens(
285 http_client.as_ref(),
286 &api_url,
287 &api_key,
288 google_ai::CountTokensRequest {
289 contents: request.contents,
290 },
291 )
292 .await?;
293 Ok(response.total_tokens)
294 }
295 .boxed()
296 }
297
298 fn stream_completion(
299 &self,
300 request: LanguageModelRequest,
301 cx: &AsyncApp,
302 ) -> BoxFuture<
303 'static,
304 Result<futures::stream::BoxStream<'static, Result<LanguageModelCompletionEvent>>>,
305 > {
306 let request = into_google(request, self.model.id().to_string());
307
308 let http_client = self.http_client.clone();
309 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
310 let settings = &AllLanguageModelSettings::get_global(cx).google;
311 (state.api_key.clone(), settings.api_url.clone())
312 }) else {
313 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
314 };
315
316 let future = self.rate_limiter.stream(async move {
317 let api_key = api_key.ok_or_else(|| anyhow!("Missing Google API Key"))?;
318 let response =
319 stream_generate_content(http_client.as_ref(), &api_url, &api_key, request);
320 let events = response.await?;
321 Ok(google_ai::extract_text_from_events(events).boxed())
322 });
323 async move {
324 Ok(future
325 .await?
326 .map(|result| result.map(LanguageModelCompletionEvent::Text))
327 .boxed())
328 }
329 .boxed()
330 }
331
332 fn use_any_tool(
333 &self,
334 _request: LanguageModelRequest,
335 _name: String,
336 _description: String,
337 _schema: serde_json::Value,
338 _cx: &AsyncApp,
339 ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
340 future::ready(Err(anyhow!("not implemented"))).boxed()
341 }
342}
343
344pub fn into_google(
345 request: LanguageModelRequest,
346 model: String,
347) -> google_ai::GenerateContentRequest {
348 google_ai::GenerateContentRequest {
349 model,
350 contents: request
351 .messages
352 .into_iter()
353 .map(|msg| google_ai::Content {
354 parts: vec![google_ai::Part::TextPart(google_ai::TextPart {
355 text: msg.string_contents(),
356 })],
357 role: match msg.role {
358 Role::User => google_ai::Role::User,
359 Role::Assistant => google_ai::Role::Model,
360 Role::System => google_ai::Role::User, // Google AI doesn't have a system role
361 },
362 })
363 .collect(),
364 generation_config: Some(google_ai::GenerationConfig {
365 candidate_count: Some(1),
366 stop_sequences: Some(request.stop),
367 max_output_tokens: None,
368 temperature: request.temperature.map(|t| t as f64).or(Some(1.0)),
369 top_p: None,
370 top_k: None,
371 }),
372 safety_settings: None,
373 }
374}
375
376pub fn count_google_tokens(
377 request: LanguageModelRequest,
378 cx: &App,
379) -> BoxFuture<'static, Result<usize>> {
380 // We couldn't use the GoogleLanguageModelProvider to count tokens because the github copilot doesn't have the access to google_ai directly.
381 // So we have to use tokenizer from tiktoken_rs to count tokens.
382 cx.background_spawn(async move {
383 let messages = request
384 .messages
385 .into_iter()
386 .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
387 role: match message.role {
388 Role::User => "user".into(),
389 Role::Assistant => "assistant".into(),
390 Role::System => "system".into(),
391 },
392 content: Some(message.string_contents()),
393 name: None,
394 function_call: None,
395 })
396 .collect::<Vec<_>>();
397
398 // Tiktoken doesn't yet support these models, so we manually use the
399 // same tokenizer as GPT-4.
400 tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
401 })
402 .boxed()
403}
404
405struct ConfigurationView {
406 api_key_editor: Entity<Editor>,
407 state: gpui::Entity<State>,
408 load_credentials_task: Option<Task<()>>,
409}
410
411impl ConfigurationView {
412 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
413 cx.observe(&state, |_, _, cx| {
414 cx.notify();
415 })
416 .detach();
417
418 let load_credentials_task = Some(cx.spawn_in(window, {
419 let state = state.clone();
420 |this, mut cx| async move {
421 if let Some(task) = state
422 .update(&mut cx, |state, cx| state.authenticate(cx))
423 .log_err()
424 {
425 // We don't log an error, because "not signed in" is also an error.
426 let _ = task.await;
427 }
428 this.update(&mut cx, |this, cx| {
429 this.load_credentials_task = None;
430 cx.notify();
431 })
432 .log_err();
433 }
434 }));
435
436 Self {
437 api_key_editor: cx.new(|cx| {
438 let mut editor = Editor::single_line(window, cx);
439 editor.set_placeholder_text("AIzaSy...", cx);
440 editor
441 }),
442 state,
443 load_credentials_task,
444 }
445 }
446
447 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
448 let api_key = self.api_key_editor.read(cx).text(cx);
449 if api_key.is_empty() {
450 return;
451 }
452
453 let state = self.state.clone();
454 cx.spawn_in(window, |_, mut cx| async move {
455 state
456 .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
457 .await
458 })
459 .detach_and_log_err(cx);
460
461 cx.notify();
462 }
463
464 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
465 self.api_key_editor
466 .update(cx, |editor, cx| editor.set_text("", window, cx));
467
468 let state = self.state.clone();
469 cx.spawn_in(window, |_, mut cx| async move {
470 state
471 .update(&mut cx, |state, cx| state.reset_api_key(cx))?
472 .await
473 })
474 .detach_and_log_err(cx);
475
476 cx.notify();
477 }
478
479 fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
480 let settings = ThemeSettings::get_global(cx);
481 let text_style = TextStyle {
482 color: cx.theme().colors().text,
483 font_family: settings.ui_font.family.clone(),
484 font_features: settings.ui_font.features.clone(),
485 font_fallbacks: settings.ui_font.fallbacks.clone(),
486 font_size: rems(0.875).into(),
487 font_weight: settings.ui_font.weight,
488 font_style: FontStyle::Normal,
489 line_height: relative(1.3),
490 white_space: WhiteSpace::Normal,
491 ..Default::default()
492 };
493 EditorElement::new(
494 &self.api_key_editor,
495 EditorStyle {
496 background: cx.theme().colors().editor_background,
497 local_player: cx.theme().players().local(),
498 text: text_style,
499 ..Default::default()
500 },
501 )
502 }
503
504 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
505 !self.state.read(cx).is_authenticated()
506 }
507}
508
509impl Render for ConfigurationView {
510 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
511 const GOOGLE_CONSOLE_URL: &str = "https://aistudio.google.com/app/apikey";
512 const INSTRUCTIONS: [&str; 3] = [
513 "To use Zed's assistant with Google AI, you need to add an API key. Follow these steps:",
514 "- Create one by visiting:",
515 "- Paste your API key below and hit enter to use the assistant",
516 ];
517
518 let env_var_set = self.state.read(cx).api_key_from_env;
519
520 if self.load_credentials_task.is_some() {
521 div().child(Label::new("Loading credentials...")).into_any()
522 } else if self.should_render_editor(cx) {
523 v_flex()
524 .size_full()
525 .on_action(cx.listener(Self::save_api_key))
526 .child(Label::new(INSTRUCTIONS[0]))
527 .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
528 Button::new("google_console", GOOGLE_CONSOLE_URL)
529 .style(ButtonStyle::Subtle)
530 .icon(IconName::ArrowUpRight)
531 .icon_size(IconSize::XSmall)
532 .icon_color(Color::Muted)
533 .on_click(move |_, _, cx| cx.open_url(GOOGLE_CONSOLE_URL))
534 )
535 )
536 .child(Label::new(INSTRUCTIONS[2]))
537 .child(
538 h_flex()
539 .w_full()
540 .my_2()
541 .px_2()
542 .py_1()
543 .bg(cx.theme().colors().editor_background)
544 .border_1()
545 .border_color(cx.theme().colors().border_variant)
546 .rounded_md()
547 .child(self.render_api_key_editor(cx)),
548 )
549 .child(
550 Label::new(
551 format!("You can also assign the {GOOGLE_AI_API_KEY_VAR} environment variable and restart Zed."),
552 )
553 .size(LabelSize::Small),
554 )
555 .into_any()
556 } else {
557 h_flex()
558 .size_full()
559 .justify_between()
560 .child(
561 h_flex()
562 .gap_1()
563 .child(Icon::new(IconName::Check).color(Color::Success))
564 .child(Label::new(if env_var_set {
565 format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
566 } else {
567 "API key configured.".to_string()
568 })),
569 )
570 .child(
571 Button::new("reset-key", "Reset key")
572 .icon(Some(IconName::Trash))
573 .icon_size(IconSize::Small)
574 .icon_position(IconPosition::Start)
575 .disabled(env_var_set)
576 .when(env_var_set, |this| {
577 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable.")))
578 })
579 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
580 )
581 .into_any()
582 }
583 }
584}