google.rs

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