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