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: &'static 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        let api_url = AllLanguageModelSettings::get_global(cx)
261            .google
262            .api_url
263            .clone();
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            )
275            .await?;
276            Ok(response.total_tokens)
277        }
278        .boxed()
279    }
280
281    fn stream_completion(
282        &self,
283        request: LanguageModelRequest,
284        cx: &AsyncAppContext,
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_model(&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 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: &AsyncAppContext,
322    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
323        future::ready(Err(anyhow!("not implemented"))).boxed()
324    }
325}
326
327struct ConfigurationView {
328    api_key_editor: View<Editor>,
329    state: gpui::Model<State>,
330    load_credentials_task: Option<Task<()>>,
331}
332
333impl ConfigurationView {
334    fn new(state: gpui::Model<State>, cx: &mut ViewContext<Self>) -> Self {
335        cx.observe(&state, |_, _, cx| {
336            cx.notify();
337        })
338        .detach();
339
340        let load_credentials_task = Some(cx.spawn({
341            let state = state.clone();
342            |this, mut cx| async move {
343                if let Some(task) = state
344                    .update(&mut cx, |state, cx| state.authenticate(cx))
345                    .log_err()
346                {
347                    // We don't log an error, because "not signed in" is also an error.
348                    let _ = task.await;
349                }
350                this.update(&mut cx, |this, cx| {
351                    this.load_credentials_task = None;
352                    cx.notify();
353                })
354                .log_err();
355            }
356        }));
357
358        Self {
359            api_key_editor: cx.new_view(|cx| {
360                let mut editor = Editor::single_line(cx);
361                editor.set_placeholder_text("AIzaSy...", cx);
362                editor
363            }),
364            state,
365            load_credentials_task,
366        }
367    }
368
369    fn save_api_key(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
370        let api_key = self.api_key_editor.read(cx).text(cx);
371        if api_key.is_empty() {
372            return;
373        }
374
375        let state = self.state.clone();
376        cx.spawn(|_, mut cx| async move {
377            state
378                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
379                .await
380        })
381        .detach_and_log_err(cx);
382
383        cx.notify();
384    }
385
386    fn reset_api_key(&mut self, cx: &mut ViewContext<Self>) {
387        self.api_key_editor
388            .update(cx, |editor, cx| editor.set_text("", cx));
389
390        let state = self.state.clone();
391        cx.spawn(|_, mut cx| async move {
392            state
393                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
394                .await
395        })
396        .detach_and_log_err(cx);
397
398        cx.notify();
399    }
400
401    fn render_api_key_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
402        let settings = ThemeSettings::get_global(cx);
403        let text_style = TextStyle {
404            color: cx.theme().colors().text,
405            font_family: settings.ui_font.family.clone(),
406            font_features: settings.ui_font.features.clone(),
407            font_fallbacks: settings.ui_font.fallbacks.clone(),
408            font_size: rems(0.875).into(),
409            font_weight: settings.ui_font.weight,
410            font_style: FontStyle::Normal,
411            line_height: relative(1.3),
412            background_color: None,
413            underline: None,
414            strikethrough: None,
415            white_space: WhiteSpace::Normal,
416            truncate: None,
417        };
418        EditorElement::new(
419            &self.api_key_editor,
420            EditorStyle {
421                background: cx.theme().colors().editor_background,
422                local_player: cx.theme().players().local(),
423                text: text_style,
424                ..Default::default()
425            },
426        )
427    }
428
429    fn should_render_editor(&self, cx: &mut ViewContext<Self>) -> bool {
430        !self.state.read(cx).is_authenticated()
431    }
432}
433
434impl Render for ConfigurationView {
435    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
436        const GOOGLE_CONSOLE_URL: &str = "https://aistudio.google.com/app/apikey";
437        const INSTRUCTIONS: [&str; 4] = [
438            "To use the Google AI assistant, you need to add your Google AI API key.",
439            "You can create an API key at:",
440            "",
441            "Paste your Google AI API key below and hit enter to use the assistant:",
442        ];
443
444        let env_var_set = self.state.read(cx).api_key_from_env;
445
446        if self.load_credentials_task.is_some() {
447            div().child(Label::new("Loading credentials...")).into_any()
448        } else if self.should_render_editor(cx) {
449            v_flex()
450                .size_full()
451                .on_action(cx.listener(Self::save_api_key))
452                .child(Label::new(INSTRUCTIONS[0]))
453                .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
454                    Button::new("google_console", GOOGLE_CONSOLE_URL)
455                        .style(ButtonStyle::Subtle)
456                        .icon(IconName::ExternalLink)
457                        .icon_size(IconSize::XSmall)
458                        .icon_color(Color::Muted)
459                        .on_click(move |_, cx| cx.open_url(GOOGLE_CONSOLE_URL))
460                    )
461                )
462                .child(Label::new(INSTRUCTIONS[2]))
463                .child(Label::new(INSTRUCTIONS[3]))
464                .child(
465                    h_flex()
466                        .w_full()
467                        .my_2()
468                        .px_2()
469                        .py_1()
470                        .bg(cx.theme().colors().editor_background)
471                        .rounded_md()
472                        .child(self.render_api_key_editor(cx)),
473                )
474                .child(
475                    Label::new(
476                        format!("You can also assign the {GOOGLE_AI_API_KEY_VAR} environment variable and restart Zed."),
477                    )
478                    .size(LabelSize::Small),
479                )
480                .into_any()
481        } else {
482            h_flex()
483                .size_full()
484                .justify_between()
485                .child(
486                    h_flex()
487                        .gap_1()
488                        .child(Icon::new(IconName::Check).color(Color::Success))
489                        .child(Label::new(if env_var_set {
490                            format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
491                        } else {
492                            "API key configured.".to_string()
493                        })),
494                )
495                .child(
496                    Button::new("reset-key", "Reset key")
497                        .icon(Some(IconName::Trash))
498                        .icon_size(IconSize::Small)
499                        .icon_position(IconPosition::Start)
500                        .disabled(env_var_set)
501                        .when(env_var_set, |this| {
502                            this.tooltip(|cx| Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable."), cx))
503                        })
504                        .on_click(cx.listener(|this, _, cx| this.reset_api_key(cx))),
505                )
506                .into_any()
507        }
508    }
509}