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::*, Indicator};
 18use util::ResultExt;
 19
 20use crate::{
 21    settings::AllLanguageModelSettings, LanguageModel, LanguageModelId, LanguageModelName,
 22    LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
 23    LanguageModelProviderState, LanguageModelRequest, RateLimiter,
 24};
 25
 26const PROVIDER_ID: &str = "google";
 27const PROVIDER_NAME: &str = "Google AI";
 28
 29#[derive(Default, Clone, Debug, PartialEq)]
 30pub struct GoogleSettings {
 31    pub api_url: String,
 32    pub low_speed_timeout: Option<Duration>,
 33    pub available_models: Vec<AvailableModel>,
 34}
 35
 36#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 37pub struct AvailableModel {
 38    name: String,
 39    max_tokens: usize,
 40}
 41
 42pub struct GoogleLanguageModelProvider {
 43    http_client: Arc<dyn HttpClient>,
 44    state: gpui::Model<State>,
 45}
 46
 47pub struct State {
 48    api_key: Option<String>,
 49    _subscription: Subscription,
 50}
 51
 52impl State {
 53    fn is_authenticated(&self) -> bool {
 54        self.api_key.is_some()
 55    }
 56
 57    fn reset_api_key(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 58        let delete_credentials =
 59            cx.delete_credentials(&AllLanguageModelSettings::get_global(cx).google.api_url);
 60        cx.spawn(|this, mut cx| async move {
 61            delete_credentials.await.ok();
 62            this.update(&mut cx, |this, cx| {
 63                this.api_key = None;
 64                cx.notify();
 65            })
 66        })
 67    }
 68
 69    fn set_api_key(&mut self, api_key: String, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 70        let settings = &AllLanguageModelSettings::get_global(cx).google;
 71        let write_credentials =
 72            cx.write_credentials(&settings.api_url, "Bearer", api_key.as_bytes());
 73
 74        cx.spawn(|this, mut cx| async move {
 75            write_credentials.await?;
 76            this.update(&mut cx, |this, cx| {
 77                this.api_key = Some(api_key);
 78                cx.notify();
 79            })
 80        })
 81    }
 82
 83    fn authenticate(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 84        if self.is_authenticated() {
 85            Task::ready(Ok(()))
 86        } else {
 87            let api_url = AllLanguageModelSettings::get_global(cx)
 88                .google
 89                .api_url
 90                .clone();
 91
 92            cx.spawn(|this, mut cx| async move {
 93                let api_key = if let Ok(api_key) = std::env::var("GOOGLE_AI_API_KEY") {
 94                    api_key
 95                } else {
 96                    let (_, api_key) = cx
 97                        .update(|cx| cx.read_credentials(&api_url))?
 98                        .await?
 99                        .ok_or_else(|| anyhow!("credentials not found"))?;
100                    String::from_utf8(api_key)?
101                };
102
103                this.update(&mut cx, |this, cx| {
104                    this.api_key = Some(api_key);
105                    cx.notify();
106                })
107            })
108        }
109    }
110}
111
112impl GoogleLanguageModelProvider {
113    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut AppContext) -> Self {
114        let state = cx.new_model(|cx| State {
115            api_key: None,
116            _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
117                cx.notify();
118            }),
119        });
120
121        Self { http_client, state }
122    }
123}
124
125impl LanguageModelProviderState for GoogleLanguageModelProvider {
126    type ObservableEntity = State;
127
128    fn observable_entity(&self) -> Option<gpui::Model<Self::ObservableEntity>> {
129        Some(self.state.clone())
130    }
131}
132
133impl LanguageModelProvider for GoogleLanguageModelProvider {
134    fn id(&self) -> LanguageModelProviderId {
135        LanguageModelProviderId(PROVIDER_ID.into())
136    }
137
138    fn name(&self) -> LanguageModelProviderName {
139        LanguageModelProviderName(PROVIDER_NAME.into())
140    }
141
142    fn icon(&self) -> IconName {
143        IconName::AiGoogle
144    }
145
146    fn provided_models(&self, cx: &AppContext) -> Vec<Arc<dyn LanguageModel>> {
147        let mut models = BTreeMap::default();
148
149        // Add base models from google_ai::Model::iter()
150        for model in google_ai::Model::iter() {
151            if !matches!(model, google_ai::Model::Custom { .. }) {
152                models.insert(model.id().to_string(), model);
153            }
154        }
155
156        // Override with available models from settings
157        for model in &AllLanguageModelSettings::get_global(cx)
158            .google
159            .available_models
160        {
161            models.insert(
162                model.name.clone(),
163                google_ai::Model::Custom {
164                    name: model.name.clone(),
165                    max_tokens: model.max_tokens,
166                },
167            );
168        }
169
170        models
171            .into_values()
172            .map(|model| {
173                Arc::new(GoogleLanguageModel {
174                    id: LanguageModelId::from(model.id().to_string()),
175                    model,
176                    state: self.state.clone(),
177                    http_client: self.http_client.clone(),
178                    rate_limiter: RateLimiter::new(4),
179                }) as Arc<dyn LanguageModel>
180            })
181            .collect()
182    }
183
184    fn is_authenticated(&self, cx: &AppContext) -> bool {
185        self.state.read(cx).is_authenticated()
186    }
187
188    fn authenticate(&self, cx: &mut AppContext) -> Task<Result<()>> {
189        self.state.update(cx, |state, cx| state.authenticate(cx))
190    }
191
192    fn configuration_view(&self, cx: &mut WindowContext) -> AnyView {
193        cx.new_view(|cx| ConfigurationView::new(self.state.clone(), cx))
194            .into()
195    }
196
197    fn reset_credentials(&self, cx: &mut AppContext) -> Task<Result<()>> {
198        let state = self.state.clone();
199        let delete_credentials =
200            cx.delete_credentials(&AllLanguageModelSettings::get_global(cx).google.api_url);
201        cx.spawn(|mut cx| async move {
202            delete_credentials.await.log_err();
203            state.update(&mut cx, |this, cx| {
204                this.api_key = None;
205                cx.notify();
206            })
207        })
208    }
209}
210
211pub struct GoogleLanguageModel {
212    id: LanguageModelId,
213    model: google_ai::Model,
214    state: gpui::Model<State>,
215    http_client: Arc<dyn HttpClient>,
216    rate_limiter: RateLimiter,
217}
218
219impl LanguageModel for GoogleLanguageModel {
220    fn id(&self) -> LanguageModelId {
221        self.id.clone()
222    }
223
224    fn name(&self) -> LanguageModelName {
225        LanguageModelName::from(self.model.display_name().to_string())
226    }
227
228    fn provider_id(&self) -> LanguageModelProviderId {
229        LanguageModelProviderId(PROVIDER_ID.into())
230    }
231
232    fn provider_name(&self) -> LanguageModelProviderName {
233        LanguageModelProviderName(PROVIDER_NAME.into())
234    }
235
236    fn telemetry_id(&self) -> String {
237        format!("google/{}", self.model.id())
238    }
239
240    fn max_token_count(&self) -> usize {
241        self.model.max_token_count()
242    }
243
244    fn count_tokens(
245        &self,
246        request: LanguageModelRequest,
247        cx: &AppContext,
248    ) -> BoxFuture<'static, Result<usize>> {
249        let request = request.into_google(self.model.id().to_string());
250        let http_client = self.http_client.clone();
251        let api_key = self.state.read(cx).api_key.clone();
252        let api_url = AllLanguageModelSettings::get_global(cx)
253            .google
254            .api_url
255            .clone();
256
257        async move {
258            let api_key = api_key.ok_or_else(|| anyhow!("missing api key"))?;
259            let response = google_ai::count_tokens(
260                http_client.as_ref(),
261                &api_url,
262                &api_key,
263                google_ai::CountTokensRequest {
264                    contents: request.contents,
265                },
266            )
267            .await?;
268            Ok(response.total_tokens)
269        }
270        .boxed()
271    }
272
273    fn stream_completion(
274        &self,
275        request: LanguageModelRequest,
276        cx: &AsyncAppContext,
277    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<String>>>> {
278        let request = request.into_google(self.model.id().to_string());
279
280        let http_client = self.http_client.clone();
281        let Ok((api_key, api_url)) = cx.read_model(&self.state, |state, cx| {
282            let settings = &AllLanguageModelSettings::get_global(cx).google;
283            (state.api_key.clone(), settings.api_url.clone())
284        }) else {
285            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
286        };
287
288        let future = self.rate_limiter.stream(async move {
289            let api_key = api_key.ok_or_else(|| anyhow!("missing api key"))?;
290            let response =
291                stream_generate_content(http_client.as_ref(), &api_url, &api_key, request);
292            let events = response.await?;
293            Ok(google_ai::extract_text_from_events(events).boxed())
294        });
295        async move { Ok(future.await?.boxed()) }.boxed()
296    }
297
298    fn use_any_tool(
299        &self,
300        _request: LanguageModelRequest,
301        _name: String,
302        _description: String,
303        _schema: serde_json::Value,
304        _cx: &AsyncAppContext,
305    ) -> BoxFuture<'static, Result<serde_json::Value>> {
306        future::ready(Err(anyhow!("not implemented"))).boxed()
307    }
308}
309
310struct ConfigurationView {
311    api_key_editor: View<Editor>,
312    state: gpui::Model<State>,
313    load_credentials_task: Option<Task<()>>,
314}
315
316impl ConfigurationView {
317    fn new(state: gpui::Model<State>, cx: &mut ViewContext<Self>) -> Self {
318        cx.observe(&state, |_, _, cx| {
319            cx.notify();
320        })
321        .detach();
322
323        let load_credentials_task = Some(cx.spawn({
324            let state = state.clone();
325            |this, mut cx| async move {
326                if let Some(task) = state
327                    .update(&mut cx, |state, cx| state.authenticate(cx))
328                    .log_err()
329                {
330                    // We don't log an error, because "not signed in" is also an error.
331                    let _ = task.await;
332                }
333                this.update(&mut cx, |this, cx| {
334                    this.load_credentials_task = None;
335                    cx.notify();
336                })
337                .log_err();
338            }
339        }));
340
341        Self {
342            api_key_editor: cx.new_view(|cx| {
343                let mut editor = Editor::single_line(cx);
344                editor.set_placeholder_text("AIzaSy...", cx);
345                editor
346            }),
347            state,
348            load_credentials_task,
349        }
350    }
351
352    fn save_api_key(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
353        let api_key = self.api_key_editor.read(cx).text(cx);
354        if api_key.is_empty() {
355            return;
356        }
357
358        let state = self.state.clone();
359        cx.spawn(|_, mut cx| async move {
360            state
361                .update(&mut cx, |state, cx| state.set_api_key(api_key, cx))?
362                .await
363        })
364        .detach_and_log_err(cx);
365
366        cx.notify();
367    }
368
369    fn reset_api_key(&mut self, cx: &mut ViewContext<Self>) {
370        self.api_key_editor
371            .update(cx, |editor, cx| editor.set_text("", cx));
372
373        let state = self.state.clone();
374        cx.spawn(|_, mut cx| async move {
375            state
376                .update(&mut cx, |state, cx| state.reset_api_key(cx))?
377                .await
378        })
379        .detach_and_log_err(cx);
380
381        cx.notify();
382    }
383
384    fn render_api_key_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
385        let settings = ThemeSettings::get_global(cx);
386        let text_style = TextStyle {
387            color: cx.theme().colors().text,
388            font_family: settings.ui_font.family.clone(),
389            font_features: settings.ui_font.features.clone(),
390            font_fallbacks: settings.ui_font.fallbacks.clone(),
391            font_size: rems(0.875).into(),
392            font_weight: settings.ui_font.weight,
393            font_style: FontStyle::Normal,
394            line_height: relative(1.3),
395            background_color: None,
396            underline: None,
397            strikethrough: None,
398            white_space: WhiteSpace::Normal,
399        };
400        EditorElement::new(
401            &self.api_key_editor,
402            EditorStyle {
403                background: cx.theme().colors().editor_background,
404                local_player: cx.theme().players().local(),
405                text: text_style,
406                ..Default::default()
407            },
408        )
409    }
410
411    fn should_render_editor(&self, cx: &mut ViewContext<Self>) -> bool {
412        !self.state.read(cx).is_authenticated()
413    }
414}
415
416impl Render for ConfigurationView {
417    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
418        const INSTRUCTIONS: [&str; 4] = [
419            "To use the Google AI assistant, you need to add your Google AI API key.",
420            "You can create an API key at: https://makersuite.google.com/app/apikey",
421            "",
422            "Paste your Google AI API key below and hit enter to use the assistant:",
423        ];
424
425        if self.load_credentials_task.is_some() {
426            div().child(Label::new("Loading credentials...")).into_any()
427        } else if self.should_render_editor(cx) {
428            v_flex()
429                .size_full()
430                .on_action(cx.listener(Self::save_api_key))
431                .children(
432                    INSTRUCTIONS.map(|instruction| Label::new(instruction)),
433                )
434                .child(
435                    h_flex()
436                        .w_full()
437                        .my_2()
438                        .px_2()
439                        .py_1()
440                        .bg(cx.theme().colors().editor_background)
441                        .rounded_md()
442                        .child(self.render_api_key_editor(cx)),
443                )
444                .child(
445                    Label::new(
446                        "You can also assign the GOOGLE_AI_API_KEY environment variable and restart Zed.",
447                    )
448                    .size(LabelSize::Small),
449                )
450                .into_any()
451        } else {
452            h_flex()
453                .size_full()
454                .justify_between()
455                .child(
456                    h_flex()
457                        .gap_2()
458                        .child(Indicator::dot().color(Color::Success))
459                        .child(Label::new("API key configured").size(LabelSize::Small)),
460                )
461                .child(
462                    Button::new("reset-key", "Reset key")
463                        .icon(Some(IconName::Trash))
464                        .icon_size(IconSize::Small)
465                        .icon_position(IconPosition::Start)
466                        .on_click(cx.listener(|this, _, cx| this.reset_api_key(cx))),
467                )
468                .into_any()
469        }
470    }
471}