vercel.rs

  1use anyhow::Result;
  2use collections::BTreeMap;
  3use credentials_provider::CredentialsProvider;
  4use futures::{FutureExt, StreamExt, future::BoxFuture};
  5use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, Window};
  6use http_client::HttpClient;
  7use language_model::{
  8    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
  9    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
 10    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
 11    LanguageModelRequest, LanguageModelToolChoice, RateLimiter, env_var,
 12};
 13use open_ai::ResponseStreamEvent;
 14pub use settings::VercelAvailableModel as AvailableModel;
 15use settings::{Settings, SettingsStore};
 16use std::sync::{Arc, LazyLock};
 17use strum::IntoEnumIterator;
 18use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 19use ui_input::InputField;
 20use util::ResultExt;
 21use vercel::VERCEL_API_URL;
 22
 23const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("vercel");
 24const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("Vercel");
 25
 26const API_KEY_ENV_VAR_NAME: &str = "VERCEL_API_KEY";
 27static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
 28
 29#[derive(Clone, Debug, PartialEq)]
 30pub struct VercelSettings {
 31    pub api_url: String,
 32    pub available_models: Vec<AvailableModel>,
 33}
 34
 35pub struct VercelLanguageModelProvider {
 36    http_client: Arc<dyn HttpClient>,
 37    state: Entity<State>,
 38}
 39
 40pub struct State {
 41    api_key_state: ApiKeyState,
 42    credentials_provider: Arc<dyn CredentialsProvider>,
 43}
 44
 45impl State {
 46    fn is_authenticated(&self) -> bool {
 47        self.api_key_state.has_key()
 48    }
 49
 50    fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
 51        let credentials_provider = self.credentials_provider.clone();
 52        let api_url = VercelLanguageModelProvider::api_url(cx);
 53        self.api_key_state.store(
 54            api_url,
 55            api_key,
 56            |this| &mut this.api_key_state,
 57            credentials_provider,
 58            cx,
 59        )
 60    }
 61
 62    fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
 63        let credentials_provider = self.credentials_provider.clone();
 64        let api_url = VercelLanguageModelProvider::api_url(cx);
 65        self.api_key_state.load_if_needed(
 66            api_url,
 67            |this| &mut this.api_key_state,
 68            credentials_provider,
 69            cx,
 70        )
 71    }
 72}
 73
 74impl VercelLanguageModelProvider {
 75    pub fn new(
 76        http_client: Arc<dyn HttpClient>,
 77        credentials_provider: Arc<dyn CredentialsProvider>,
 78        cx: &mut App,
 79    ) -> Self {
 80        let state = cx.new(|cx| {
 81            cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
 82                let credentials_provider = this.credentials_provider.clone();
 83                let api_url = Self::api_url(cx);
 84                this.api_key_state.handle_url_change(
 85                    api_url,
 86                    |this| &mut this.api_key_state,
 87                    credentials_provider,
 88                    cx,
 89                );
 90                cx.notify();
 91            })
 92            .detach();
 93            State {
 94                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
 95                credentials_provider,
 96            }
 97        });
 98
 99        Self { http_client, state }
100    }
101
102    fn create_language_model(&self, model: vercel::Model) -> Arc<dyn LanguageModel> {
103        Arc::new(VercelLanguageModel {
104            id: LanguageModelId::from(model.id().to_string()),
105            model,
106            state: self.state.clone(),
107            http_client: self.http_client.clone(),
108            request_limiter: RateLimiter::new(4),
109        })
110    }
111
112    fn settings(cx: &App) -> &VercelSettings {
113        &crate::AllLanguageModelSettings::get_global(cx).vercel
114    }
115
116    fn api_url(cx: &App) -> SharedString {
117        let api_url = &Self::settings(cx).api_url;
118        if api_url.is_empty() {
119            VERCEL_API_URL.into()
120        } else {
121            SharedString::new(api_url.as_str())
122        }
123    }
124}
125
126impl LanguageModelProviderState for VercelLanguageModelProvider {
127    type ObservableEntity = State;
128
129    fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
130        Some(self.state.clone())
131    }
132}
133
134impl LanguageModelProvider for VercelLanguageModelProvider {
135    fn id(&self) -> LanguageModelProviderId {
136        PROVIDER_ID
137    }
138
139    fn name(&self) -> LanguageModelProviderName {
140        PROVIDER_NAME
141    }
142
143    fn icon(&self) -> IconOrSvg {
144        IconOrSvg::Icon(IconName::AiVZero)
145    }
146
147    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
148        Some(self.create_language_model(vercel::Model::default()))
149    }
150
151    fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
152        Some(self.create_language_model(vercel::Model::default_fast()))
153    }
154
155    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
156        let mut models = BTreeMap::default();
157
158        for model in vercel::Model::iter() {
159            if !matches!(model, vercel::Model::Custom { .. }) {
160                models.insert(model.id().to_string(), model);
161            }
162        }
163
164        for model in &Self::settings(cx).available_models {
165            models.insert(
166                model.name.clone(),
167                vercel::Model::Custom {
168                    name: model.name.clone(),
169                    display_name: model.display_name.clone(),
170                    max_tokens: model.max_tokens,
171                    max_output_tokens: model.max_output_tokens,
172                    max_completion_tokens: model.max_completion_tokens,
173                },
174            );
175        }
176
177        models
178            .into_values()
179            .map(|model| self.create_language_model(model))
180            .collect()
181    }
182
183    fn is_authenticated(&self, cx: &App) -> bool {
184        self.state.read(cx).is_authenticated()
185    }
186
187    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
188        self.state.update(cx, |state, cx| state.authenticate(cx))
189    }
190
191    fn configuration_view(
192        &self,
193        _target_agent: language_model::ConfigurationViewTargetAgent,
194        window: &mut Window,
195        cx: &mut App,
196    ) -> AnyView {
197        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
198            .into()
199    }
200
201    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
202        self.state
203            .update(cx, |state, cx| state.set_api_key(None, cx))
204    }
205}
206
207pub struct VercelLanguageModel {
208    id: LanguageModelId,
209    model: vercel::Model,
210    state: Entity<State>,
211    http_client: Arc<dyn HttpClient>,
212    request_limiter: RateLimiter,
213}
214
215impl VercelLanguageModel {
216    fn stream_completion(
217        &self,
218        request: open_ai::Request,
219        cx: &AsyncApp,
220    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
221    {
222        let http_client = self.http_client.clone();
223
224        let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
225            let api_url = VercelLanguageModelProvider::api_url(cx);
226            (state.api_key_state.key(&api_url), api_url)
227        });
228
229        let future = self.request_limiter.stream(async move {
230            let provider = PROVIDER_NAME;
231            let Some(api_key) = api_key else {
232                return Err(LanguageModelCompletionError::NoApiKey { provider });
233            };
234            let request = open_ai::stream_completion(
235                http_client.as_ref(),
236                provider.0.as_str(),
237                &api_url,
238                &api_key,
239                request,
240            );
241            let response = request.await?;
242            Ok(response)
243        });
244
245        async move { Ok(future.await?.boxed()) }.boxed()
246    }
247}
248
249impl LanguageModel for VercelLanguageModel {
250    fn id(&self) -> LanguageModelId {
251        self.id.clone()
252    }
253
254    fn name(&self) -> LanguageModelName {
255        LanguageModelName::from(self.model.display_name().to_string())
256    }
257
258    fn provider_id(&self) -> LanguageModelProviderId {
259        PROVIDER_ID
260    }
261
262    fn provider_name(&self) -> LanguageModelProviderName {
263        PROVIDER_NAME
264    }
265
266    fn supports_tools(&self) -> bool {
267        true
268    }
269
270    fn supports_images(&self) -> bool {
271        true
272    }
273
274    fn supports_streaming_tools(&self) -> bool {
275        true
276    }
277
278    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
279        match choice {
280            LanguageModelToolChoice::Auto
281            | LanguageModelToolChoice::Any
282            | LanguageModelToolChoice::None => true,
283        }
284    }
285
286    fn telemetry_id(&self) -> String {
287        format!("vercel/{}", self.model.id())
288    }
289
290    fn max_token_count(&self) -> u64 {
291        self.model.max_token_count()
292    }
293
294    fn max_output_tokens(&self) -> Option<u64> {
295        self.model.max_output_tokens()
296    }
297
298    fn stream_completion(
299        &self,
300        request: LanguageModelRequest,
301        cx: &AsyncApp,
302    ) -> BoxFuture<
303        'static,
304        Result<
305            futures::stream::BoxStream<
306                'static,
307                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
308            >,
309            LanguageModelCompletionError,
310        >,
311    > {
312        let request = crate::provider::open_ai::into_open_ai(
313            request,
314            self.model.id(),
315            self.model.supports_parallel_tool_calls(),
316            self.model.supports_prompt_cache_key(),
317            self.max_output_tokens(),
318            None,
319            false,
320        );
321        let completions = self.stream_completion(request, cx);
322        async move {
323            let mapper = crate::provider::open_ai::OpenAiEventMapper::new();
324            Ok(mapper.map_stream(completions.await?).boxed())
325        }
326        .boxed()
327    }
328}
329
330struct ConfigurationView {
331    api_key_editor: Entity<InputField>,
332    state: Entity<State>,
333    load_credentials_task: Option<Task<()>>,
334}
335
336impl ConfigurationView {
337    fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
338        let api_key_editor = cx.new(|cx| {
339            InputField::new(
340                window,
341                cx,
342                "v1:0000000000000000000000000000000000000000000000000",
343            )
344            .label("API key")
345        });
346
347        cx.observe(&state, |_, _, cx| {
348            cx.notify();
349        })
350        .detach();
351
352        let load_credentials_task = Some(cx.spawn_in(window, {
353            let state = state.clone();
354            async move |this, cx| {
355                if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
356                    // We don't log an error, because "not signed in" is also an error.
357                    let _ = task.await;
358                }
359                this.update(cx, |this, cx| {
360                    this.load_credentials_task = None;
361                    cx.notify();
362                })
363                .log_err();
364            }
365        }));
366
367        Self {
368            api_key_editor,
369            state,
370            load_credentials_task,
371        }
372    }
373
374    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
375        let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
376        if api_key.is_empty() {
377            return;
378        }
379
380        // url changes can cause the editor to be displayed again
381        self.api_key_editor
382            .update(cx, |editor, cx| editor.set_text("", window, cx));
383
384        let state = self.state.clone();
385        cx.spawn_in(window, async move |_, cx| {
386            state
387                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
388                .await
389        })
390        .detach_and_log_err(cx);
391    }
392
393    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
394        self.api_key_editor
395            .update(cx, |input, cx| input.set_text("", window, cx));
396
397        let state = self.state.clone();
398        cx.spawn_in(window, async move |_, cx| {
399            state
400                .update(cx, |state, cx| state.set_api_key(None, cx))
401                .await
402        })
403        .detach_and_log_err(cx);
404    }
405
406    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
407        !self.state.read(cx).is_authenticated()
408    }
409}
410
411impl Render for ConfigurationView {
412    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
413        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
414        let configured_card_label = if env_var_set {
415            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
416        } else {
417            let api_url = VercelLanguageModelProvider::api_url(cx);
418            if api_url == VERCEL_API_URL {
419                "API key configured".to_string()
420            } else {
421                format!("API key configured for {}", api_url)
422            }
423        };
424
425        let api_key_section = if self.should_render_editor(cx) {
426            v_flex()
427                .on_action(cx.listener(Self::save_api_key))
428                .child(Label::new("To use Zed's agent with Vercel v0, you need to add an API key. Follow these steps:"))
429                .child(
430                    List::new()
431                        .child(
432                            ListBulletItem::new("")
433                                .child(Label::new("Create one by visiting"))
434                                .child(ButtonLink::new("Vercel v0's console", "https://v0.dev/chat/settings/keys"))
435                        )
436                        .child(
437                            ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
438                        ),
439                )
440                .child(self.api_key_editor.clone())
441                .child(
442                    Label::new(format!(
443                        "You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."
444                    ))
445                    .size(LabelSize::Small)
446                    .color(Color::Muted),
447                )
448                .child(
449                    Label::new("Note that Vercel v0 is a custom OpenAI-compatible provider.")
450                        .size(LabelSize::Small)
451                        .color(Color::Muted),
452                )
453                .into_any_element()
454        } else {
455            ConfiguredApiCard::new(configured_card_label)
456                .disabled(env_var_set)
457                .when(env_var_set, |this| {
458                    this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
459                })
460                .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
461                .into_any_element()
462        };
463
464        if self.load_credentials_task.is_some() {
465            div().child(Label::new("Loading credentials…")).into_any()
466        } else {
467            v_flex().size_full().child(api_key_section).into_any()
468        }
469    }
470}