google.rs

  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_executor()
334        .spawn(async move {
335            let messages = request
336                .messages
337                .into_iter()
338                .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
339                    role: match message.role {
340                        Role::User => "user".into(),
341                        Role::Assistant => "assistant".into(),
342                        Role::System => "system".into(),
343                    },
344                    content: Some(message.string_contents()),
345                    name: None,
346                    function_call: None,
347                })
348                .collect::<Vec<_>>();
349
350            // Tiktoken doesn't yet support these models, so we manually use the
351            // same tokenizer as GPT-4.
352            tiktoken_rs::num_tokens_from_messages("gpt-4", &messages)
353        })
354        .boxed()
355}
356
357struct ConfigurationView {
358    api_key_editor: Entity<Editor>,
359    state: gpui::Entity<State>,
360    load_credentials_task: Option<Task<()>>,
361}
362
363impl ConfigurationView {
364    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
365        cx.observe(&state, |_, _, cx| {
366            cx.notify();
367        })
368        .detach();
369
370        let load_credentials_task = Some(cx.spawn_in(window, {
371            let state = state.clone();
372            |this, mut cx| async move {
373                if let Some(task) = state
374                    .update(&mut cx, |state, cx| state.authenticate(cx))
375                    .log_err()
376                {
377                    // We don't log an error, because "not signed in" is also an error.
378                    let _ = task.await;
379                }
380                this.update(&mut cx, |this, cx| {
381                    this.load_credentials_task = None;
382                    cx.notify();
383                })
384                .log_err();
385            }
386        }));
387
388        Self {
389            api_key_editor: cx.new(|cx| {
390                let mut editor = Editor::single_line(window, cx);
391                editor.set_placeholder_text("AIzaSy...", cx);
392                editor
393            }),
394            state,
395            load_credentials_task,
396        }
397    }
398
399    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
400        let api_key = self.api_key_editor.read(cx).text(cx);
401        if api_key.is_empty() {
402            return;
403        }
404
405        let state = self.state.clone();
406        cx.spawn_in(window, |_, mut cx| async move {
407            state
408                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
409                .await
410        })
411        .detach_and_log_err(cx);
412
413        cx.notify();
414    }
415
416    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
417        self.api_key_editor
418            .update(cx, |editor, cx| editor.set_text("", window, cx));
419
420        let state = self.state.clone();
421        cx.spawn_in(window, |_, mut cx| async move {
422            state
423                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
424                .await
425        })
426        .detach_and_log_err(cx);
427
428        cx.notify();
429    }
430
431    fn render_api_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
432        let settings = ThemeSettings::get_global(cx);
433        let text_style = TextStyle {
434            color: cx.theme().colors().text,
435            font_family: settings.ui_font.family.clone(),
436            font_features: settings.ui_font.features.clone(),
437            font_fallbacks: settings.ui_font.fallbacks.clone(),
438            font_size: rems(0.875).into(),
439            font_weight: settings.ui_font.weight,
440            font_style: FontStyle::Normal,
441            line_height: relative(1.3),
442            white_space: WhiteSpace::Normal,
443            ..Default::default()
444        };
445        EditorElement::new(
446            &self.api_key_editor,
447            EditorStyle {
448                background: cx.theme().colors().editor_background,
449                local_player: cx.theme().players().local(),
450                text: text_style,
451                ..Default::default()
452            },
453        )
454    }
455
456    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
457        !self.state.read(cx).is_authenticated()
458    }
459}
460
461impl Render for ConfigurationView {
462    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
463        const GOOGLE_CONSOLE_URL: &str = "https://aistudio.google.com/app/apikey";
464        const INSTRUCTIONS: [&str; 3] = [
465            "To use Zed's assistant with Google AI, you need to add an API key. Follow these steps:",
466            "- Create one by visiting:",
467            "- Paste your API key below and hit enter to use the assistant",
468        ];
469
470        let env_var_set = self.state.read(cx).api_key_from_env;
471
472        if self.load_credentials_task.is_some() {
473            div().child(Label::new("Loading credentials...")).into_any()
474        } else if self.should_render_editor(cx) {
475            v_flex()
476                .size_full()
477                .on_action(cx.listener(Self::save_api_key))
478                .child(Label::new(INSTRUCTIONS[0]))
479                .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
480                    Button::new("google_console", GOOGLE_CONSOLE_URL)
481                        .style(ButtonStyle::Subtle)
482                        .icon(IconName::ArrowUpRight)
483                        .icon_size(IconSize::XSmall)
484                        .icon_color(Color::Muted)
485                        .on_click(move |_, _, cx| cx.open_url(GOOGLE_CONSOLE_URL))
486                    )
487                )
488                .child(Label::new(INSTRUCTIONS[2]))
489                .child(
490                    h_flex()
491                        .w_full()
492                        .my_2()
493                        .px_2()
494                        .py_1()
495                        .bg(cx.theme().colors().editor_background)
496                        .border_1()
497                        .border_color(cx.theme().colors().border_variant)
498                        .rounded_md()
499                        .child(self.render_api_key_editor(cx)),
500                )
501                .child(
502                    Label::new(
503                        format!("You can also assign the {GOOGLE_AI_API_KEY_VAR} environment variable and restart Zed."),
504                    )
505                    .size(LabelSize::Small),
506                )
507                .into_any()
508        } else {
509            h_flex()
510                .size_full()
511                .justify_between()
512                .child(
513                    h_flex()
514                        .gap_1()
515                        .child(Icon::new(IconName::Check).color(Color::Success))
516                        .child(Label::new(if env_var_set {
517                            format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
518                        } else {
519                            "API key configured.".to_string()
520                        })),
521                )
522                .child(
523                    Button::new("reset-key", "Reset key")
524                        .icon(Some(IconName::Trash))
525                        .icon_size(IconSize::Small)
526                        .icon_position(IconPosition::Start)
527                        .disabled(env_var_set)
528                        .when(env_var_set, |this| {
529                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable.")))
530                        })
531                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
532                )
533                .into_any()
534        }
535    }
536}