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