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,
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
327struct ConfigurationView {
328 api_key_editor: Entity<Editor>,
329 state: gpui::Entity<State>,
330 load_credentials_task: Option<Task<()>>,
331}
332
333impl ConfigurationView {
334 fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
335 cx.observe(&state, |_, _, cx| {
336 cx.notify();
337 })
338 .detach();
339
340 let load_credentials_task = Some(cx.spawn_in(window, {
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(|cx| {
360 let mut editor = Editor::single_line(window, 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, window: &mut Window, cx: &mut Context<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_in(window, |_, 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, window: &mut Window, cx: &mut Context<Self>) {
387 self.api_key_editor
388 .update(cx, |editor, cx| editor.set_text("", window, cx));
389
390 let state = self.state.clone();
391 cx.spawn_in(window, |_, 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 Context<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 white_space: WhiteSpace::Normal,
413 ..Default::default()
414 };
415 EditorElement::new(
416 &self.api_key_editor,
417 EditorStyle {
418 background: cx.theme().colors().editor_background,
419 local_player: cx.theme().players().local(),
420 text: text_style,
421 ..Default::default()
422 },
423 )
424 }
425
426 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
427 !self.state.read(cx).is_authenticated()
428 }
429}
430
431impl Render for ConfigurationView {
432 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
433 const GOOGLE_CONSOLE_URL: &str = "https://aistudio.google.com/app/apikey";
434 const INSTRUCTIONS: [&str; 3] = [
435 "To use Zed's assistant with Google AI, you need to add an API key. Follow these steps:",
436 "- Create one by visiting:",
437 "- Paste your API key below and hit enter to use the assistant",
438 ];
439
440 let env_var_set = self.state.read(cx).api_key_from_env;
441
442 if self.load_credentials_task.is_some() {
443 div().child(Label::new("Loading credentials...")).into_any()
444 } else if self.should_render_editor(cx) {
445 v_flex()
446 .size_full()
447 .on_action(cx.listener(Self::save_api_key))
448 .child(Label::new(INSTRUCTIONS[0]))
449 .child(h_flex().child(Label::new(INSTRUCTIONS[1])).child(
450 Button::new("google_console", GOOGLE_CONSOLE_URL)
451 .style(ButtonStyle::Subtle)
452 .icon(IconName::ArrowUpRight)
453 .icon_size(IconSize::XSmall)
454 .icon_color(Color::Muted)
455 .on_click(move |_, _, cx| cx.open_url(GOOGLE_CONSOLE_URL))
456 )
457 )
458 .child(Label::new(INSTRUCTIONS[2]))
459 .child(
460 h_flex()
461 .w_full()
462 .my_2()
463 .px_2()
464 .py_1()
465 .bg(cx.theme().colors().editor_background)
466 .border_1()
467 .border_color(cx.theme().colors().border_variant)
468 .rounded_md()
469 .child(self.render_api_key_editor(cx)),
470 )
471 .child(
472 Label::new(
473 format!("You can also assign the {GOOGLE_AI_API_KEY_VAR} environment variable and restart Zed."),
474 )
475 .size(LabelSize::Small),
476 )
477 .into_any()
478 } else {
479 h_flex()
480 .size_full()
481 .justify_between()
482 .child(
483 h_flex()
484 .gap_1()
485 .child(Icon::new(IconName::Check).color(Color::Success))
486 .child(Label::new(if env_var_set {
487 format!("API key set in {GOOGLE_AI_API_KEY_VAR} environment variable.")
488 } else {
489 "API key configured.".to_string()
490 })),
491 )
492 .child(
493 Button::new("reset-key", "Reset key")
494 .icon(Some(IconName::Trash))
495 .icon_size(IconSize::Small)
496 .icon_position(IconPosition::Start)
497 .disabled(env_var_set)
498 .when(env_var_set, |this| {
499 this.tooltip(Tooltip::text(format!("To reset your API key, unset the {GOOGLE_AI_API_KEY_VAR} environment variable.")))
500 })
501 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
502 )
503 .into_any()
504 }
505 }
506}