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, AppContext, AsyncAppContext, FontStyle, ModelContext, Subscription, Task, TextStyle,
  8    View, WhiteSpace,
  9};
 10use http_client::HttpClient;
 11use schemars::JsonSchema;
 12use serde::{Deserialize, Serialize};
 13use settings::{Settings, SettingsStore};
 14use std::{future, sync::Arc, time::Duration};
 15use strum::IntoEnumIterator;
 16use theme::ThemeSettings;
 17use ui::{prelude::*, Icon, IconName, Tooltip};
 18use util::ResultExt;
 19
 20use crate::LanguageModelCompletionEvent;
 21use crate::{
 22    settings::AllLanguageModelSettings, LanguageModel, LanguageModelId, LanguageModelName,
 23    LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
 24    LanguageModelProviderState, LanguageModelRequest, RateLimiter,
 25};
 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 low_speed_timeout: Option<Duration>,
 34    pub available_models: Vec<AvailableModel>,
 35}
 36
 37#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 38pub struct AvailableModel {
 39    name: String,
 40    max_tokens: usize,
 41}
 42
 43pub struct GoogleLanguageModelProvider {
 44    http_client: Arc<dyn HttpClient>,
 45    state: gpui::Model<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 ModelContext<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 ModelContext<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 ModelContext<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 AppContext) -> Self {
121        let state = cx.new_model(|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::Model<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: &AppContext) -> 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                    max_tokens: model.max_tokens,
174                },
175            );
176        }
177
178        models
179            .into_values()
180            .map(|model| {
181                Arc::new(GoogleLanguageModel {
182                    id: LanguageModelId::from(model.id().to_string()),
183                    model,
184                    state: self.state.clone(),
185                    http_client: self.http_client.clone(),
186                    rate_limiter: RateLimiter::new(4),
187                }) as Arc<dyn LanguageModel>
188            })
189            .collect()
190    }
191
192    fn is_authenticated(&self, cx: &AppContext) -> bool {
193        self.state.read(cx).is_authenticated()
194    }
195
196    fn authenticate(&self, cx: &mut AppContext) -> Task<Result<()>> {
197        self.state.update(cx, |state, cx| state.authenticate(cx))
198    }
199
200    fn configuration_view(&self, cx: &mut WindowContext) -> AnyView {
201        cx.new_view(|cx| ConfigurationView::new(self.state.clone(), cx))
202            .into()
203    }
204
205    fn reset_credentials(&self, cx: &mut AppContext) -> Task<Result<()>> {
206        let state = self.state.clone();
207        let delete_credentials =
208            cx.delete_credentials(&AllLanguageModelSettings::get_global(cx).google.api_url);
209        cx.spawn(|mut cx| async move {
210            delete_credentials.await.log_err();
211            state.update(&mut cx, |this, cx| {
212                this.api_key = None;
213                cx.notify();
214            })
215        })
216    }
217}
218
219pub struct GoogleLanguageModel {
220    id: LanguageModelId,
221    model: google_ai::Model,
222    state: gpui::Model<State>,
223    http_client: Arc<dyn HttpClient>,
224    rate_limiter: RateLimiter,
225}
226
227impl LanguageModel for GoogleLanguageModel {
228    fn id(&self) -> LanguageModelId {
229        self.id.clone()
230    }
231
232    fn name(&self) -> LanguageModelName {
233        LanguageModelName::from(self.model.display_name().to_string())
234    }
235
236    fn provider_id(&self) -> LanguageModelProviderId {
237        LanguageModelProviderId(PROVIDER_ID.into())
238    }
239
240    fn provider_name(&self) -> LanguageModelProviderName {
241        LanguageModelProviderName(PROVIDER_NAME.into())
242    }
243
244    fn telemetry_id(&self) -> String {
245        format!("google/{}", self.model.id())
246    }
247
248    fn max_token_count(&self) -> usize {
249        self.model.max_token_count()
250    }
251
252    fn count_tokens(
253        &self,
254        request: LanguageModelRequest,
255        cx: &AppContext,
256    ) -> BoxFuture<'static, Result<usize>> {
257        let request = request.into_google(self.model.id().to_string());
258        let http_client = self.http_client.clone();
259        let api_key = self.state.read(cx).api_key.clone();
260
261        let settings = &AllLanguageModelSettings::get_global(cx).google;
262        let api_url = settings.api_url.clone();
263        let low_speed_timeout = settings.low_speed_timeout;
264
265        async move {
266            let api_key = api_key.ok_or_else(|| anyhow!("missing 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                low_speed_timeout,
275            )
276            .await?;
277            Ok(response.total_tokens)
278        }
279        .boxed()
280    }
281
282    fn stream_completion(
283        &self,
284        request: LanguageModelRequest,
285        cx: &AsyncAppContext,
286    ) -> BoxFuture<
287        'static,
288        Result<futures::stream::BoxStream<'static, Result<LanguageModelCompletionEvent>>>,
289    > {
290        let request = request.into_google(self.model.id().to_string());
291
292        let http_client = self.http_client.clone();
293        let Ok((api_key, api_url, low_speed_timeout)) = cx.read_model(&self.state, |state, cx| {
294            let settings = &AllLanguageModelSettings::get_global(cx).google;
295            (
296                state.api_key.clone(),
297                settings.api_url.clone(),
298                settings.low_speed_timeout,
299            )
300        }) else {
301            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
302        };
303
304        let future = self.rate_limiter.stream(async move {
305            let api_key = api_key.ok_or_else(|| anyhow!("missing api key"))?;
306            let response = stream_generate_content(
307                http_client.as_ref(),
308                &api_url,
309                &api_key,
310                request,
311                low_speed_timeout,
312            );
313            let events = response.await?;
314            Ok(google_ai::extract_text_from_events(events).boxed())
315        });
316        async move {
317            Ok(future
318                .await?
319                .map(|result| result.map(LanguageModelCompletionEvent::Text))
320                .boxed())
321        }
322        .boxed()
323    }
324
325    fn use_any_tool(
326        &self,
327        _request: LanguageModelRequest,
328        _name: String,
329        _description: String,
330        _schema: serde_json::Value,
331        _cx: &AsyncAppContext,
332    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
333        future::ready(Err(anyhow!("not implemented"))).boxed()
334    }
335}
336
337struct ConfigurationView {
338    api_key_editor: View<Editor>,
339    state: gpui::Model<State>,
340    load_credentials_task: Option<Task<()>>,
341}
342
343impl ConfigurationView {
344    fn new(state: gpui::Model<State>, cx: &mut ViewContext<Self>) -> Self {
345        cx.observe(&state, |_, _, cx| {
346            cx.notify();
347        })
348        .detach();
349
350        let load_credentials_task = Some(cx.spawn({
351            let state = state.clone();
352            |this, mut cx| async move {
353                if let Some(task) = state
354                    .update(&mut cx, |state, cx| state.authenticate(cx))
355                    .log_err()
356                {
357                    // We don't log an error, because "not signed in" is also an error.
358                    let _ = task.await;
359                }
360                this.update(&mut cx, |this, cx| {
361                    this.load_credentials_task = None;
362                    cx.notify();
363                })
364                .log_err();
365            }
366        }));
367
368        Self {
369            api_key_editor: cx.new_view(|cx| {
370                let mut editor = Editor::single_line(cx);
371                editor.set_placeholder_text("AIzaSy...", cx);
372                editor
373            }),
374            state,
375            load_credentials_task,
376        }
377    }
378
379    fn save_api_key(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
380        let api_key = self.api_key_editor.read(cx).text(cx);
381        if api_key.is_empty() {
382            return;
383        }
384
385        let state = self.state.clone();
386        cx.spawn(|_, mut cx| async move {
387            state
388                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
389                .await
390        })
391        .detach_and_log_err(cx);
392
393        cx.notify();
394    }
395
396    fn reset_api_key(&mut self, cx: &mut ViewContext<Self>) {
397        self.api_key_editor
398            .update(cx, |editor, cx| editor.set_text("", cx));
399
400        let state = self.state.clone();
401        cx.spawn(|_, mut cx| async move {
402            state
403                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
404                .await
405        })
406        .detach_and_log_err(cx);
407
408        cx.notify();
409    }
410
411    fn render_api_key_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
412        let settings = ThemeSettings::get_global(cx);
413        let text_style = TextStyle {
414            color: cx.theme().colors().text,
415            font_family: settings.ui_font.family.clone(),
416            font_features: settings.ui_font.features.clone(),
417            font_fallbacks: settings.ui_font.fallbacks.clone(),
418            font_size: rems(0.875).into(),
419            font_weight: settings.ui_font.weight,
420            font_style: FontStyle::Normal,
421            line_height: relative(1.3),
422            background_color: None,
423            underline: None,
424            strikethrough: None,
425            white_space: WhiteSpace::Normal,
426            truncate: None,
427        };
428        EditorElement::new(
429            &self.api_key_editor,
430            EditorStyle {
431                background: cx.theme().colors().editor_background,
432                local_player: cx.theme().players().local(),
433                text: text_style,
434                ..Default::default()
435            },
436        )
437    }
438
439    fn should_render_editor(&self, cx: &mut ViewContext<Self>) -> bool {
440        !self.state.read(cx).is_authenticated()
441    }
442}
443
444impl Render for ConfigurationView {
445    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
446        const GOOGLE_CONSOLE_URL: &str = "https://aistudio.google.com/app/apikey";
447        const INSTRUCTIONS: [&str; 4] = [
448            "To use the Google AI assistant, you need to add your Google AI API key.",
449            "You can create an API key at:",
450            "",
451            "Paste your Google AI API key below and hit enter to use the assistant:",
452        ];
453
454        let env_var_set = self.state.read(cx).api_key_from_env;
455
456        if self.load_credentials_task.is_some() {
457            div().child(Label::new("Loading credentials...")).into_any()
458        } else if self.should_render_editor(cx) {
459            v_flex()
460                .size_full()
461                .on_action(cx.listener(Self::save_api_key))
462                .child(Label::new(INSTRUCTIONS[0]))
463                .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
464                    Button::new("google_console", GOOGLE_CONSOLE_URL)
465                        .style(ButtonStyle::Subtle)
466                        .icon(IconName::ExternalLink)
467                        .icon_size(IconSize::XSmall)
468                        .icon_color(Color::Muted)
469                        .on_click(move |_, cx| cx.open_url(GOOGLE_CONSOLE_URL))
470                    )
471                )
472                .child(Label::new(INSTRUCTIONS[2]))
473                .child(Label::new(INSTRUCTIONS[3]))
474                .child(
475                    h_flex()
476                        .w_full()
477                        .my_2()
478                        .px_2()
479                        .py_1()
480                        .bg(cx.theme().colors().editor_background)
481                        .rounded_md()
482                        .child(self.render_api_key_editor(cx)),
483                )
484                .child(
485                    Label::new(
486                        format!("You can also assign the {GOOGLE_AI_API_KEY_VAR} environment variable and restart Zed."),
487                    )
488                    .size(LabelSize::Small),
489                )
490                .into_any()
491        } else {
492            h_flex()
493                .size_full()
494                .justify_between()
495                .child(
496                    h_flex()
497                        .gap_1()
498                        .child(Icon::new(IconName::Check).color(Color::Success))
499                        .child(Label::new(if env_var_set {
500                            format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
501                        } else {
502                            "API key configured.".to_string()
503                        })),
504                )
505                .child(
506                    Button::new("reset-key", "Reset key")
507                        .icon(Some(IconName::Trash))
508                        .icon_size(IconSize::Small)
509                        .icon_position(IconPosition::Start)
510                        .disabled(env_var_set)
511                        .when(env_var_set, |this| {
512                            this.tooltip(|cx| Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable."), cx))
513                        })
514                        .on_click(cx.listener(|this, _, cx| this.reset_api_key(cx))),
515                )
516                .into_any()
517        }
518    }
519}