vercel.rs

  1use anyhow::{Context as _, Result, anyhow};
  2use collections::BTreeMap;
  3use credentials_provider::CredentialsProvider;
  4use futures::{FutureExt, StreamExt, future::BoxFuture};
  5use gpui::{AnyView, App, AsyncApp, Context, Entity, Subscription, Task, Window};
  6use http_client::HttpClient;
  7use language_model::{
  8    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
  9    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
 10    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
 11    LanguageModelToolChoice, RateLimiter, Role,
 12};
 13use menu;
 14use open_ai::ResponseStreamEvent;
 15use schemars::JsonSchema;
 16use serde::{Deserialize, Serialize};
 17use settings::{Settings, SettingsStore};
 18use std::sync::Arc;
 19use strum::IntoEnumIterator;
 20use vercel::Model;
 21
 22use ui::{ElevationIndex, List, Tooltip, prelude::*};
 23use ui_input::SingleLineInput;
 24use util::ResultExt;
 25
 26use crate::{AllLanguageModelSettings, ui::InstructionListItem};
 27
 28const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("vercel");
 29const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("Vercel");
 30
 31#[derive(Default, Clone, Debug, PartialEq)]
 32pub struct VercelSettings {
 33    pub api_url: String,
 34    pub available_models: Vec<AvailableModel>,
 35}
 36
 37#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 38pub struct AvailableModel {
 39    pub name: String,
 40    pub display_name: Option<String>,
 41    pub max_tokens: u64,
 42    pub max_output_tokens: Option<u64>,
 43    pub max_completion_tokens: Option<u64>,
 44}
 45
 46pub struct VercelLanguageModelProvider {
 47    http_client: Arc<dyn HttpClient>,
 48    state: gpui::Entity<State>,
 49}
 50
 51pub struct State {
 52    api_key: Option<String>,
 53    api_key_from_env: bool,
 54    _subscription: Subscription,
 55}
 56
 57const VERCEL_API_KEY_VAR: &str = "VERCEL_API_KEY";
 58
 59impl State {
 60    fn is_authenticated(&self) -> bool {
 61        self.api_key.is_some()
 62    }
 63
 64    fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 65        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 66        let settings = &AllLanguageModelSettings::get_global(cx).vercel;
 67        let api_url = if settings.api_url.is_empty() {
 68            vercel::VERCEL_API_URL.to_string()
 69        } else {
 70            settings.api_url.clone()
 71        };
 72        cx.spawn(async move |this, cx| {
 73            credentials_provider
 74                .delete_credentials(&api_url, cx)
 75                .await
 76                .log_err();
 77            this.update(cx, |this, cx| {
 78                this.api_key = None;
 79                this.api_key_from_env = false;
 80                cx.notify();
 81            })
 82        })
 83    }
 84
 85    fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
 86        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 87        let settings = &AllLanguageModelSettings::get_global(cx).vercel;
 88        let api_url = if settings.api_url.is_empty() {
 89            vercel::VERCEL_API_URL.to_string()
 90        } else {
 91            settings.api_url.clone()
 92        };
 93        cx.spawn(async move |this, cx| {
 94            credentials_provider
 95                .write_credentials(&api_url, "Bearer", api_key.as_bytes(), cx)
 96                .await
 97                .log_err();
 98            this.update(cx, |this, cx| {
 99                this.api_key = Some(api_key);
100                cx.notify();
101            })
102        })
103    }
104
105    fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
106        if self.is_authenticated() {
107            return Task::ready(Ok(()));
108        }
109
110        let credentials_provider = <dyn CredentialsProvider>::global(cx);
111        let settings = &AllLanguageModelSettings::get_global(cx).vercel;
112        let api_url = if settings.api_url.is_empty() {
113            vercel::VERCEL_API_URL.to_string()
114        } else {
115            settings.api_url.clone()
116        };
117        cx.spawn(async move |this, cx| {
118            let (api_key, from_env) = if let Ok(api_key) = std::env::var(VERCEL_API_KEY_VAR) {
119                (api_key, true)
120            } else {
121                let (_, api_key) = credentials_provider
122                    .read_credentials(&api_url, cx)
123                    .await?
124                    .ok_or(AuthenticateError::CredentialsNotFound)?;
125                (
126                    String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
127                    false,
128                )
129            };
130            this.update(cx, |this, cx| {
131                this.api_key = Some(api_key);
132                this.api_key_from_env = from_env;
133                cx.notify();
134            })?;
135
136            Ok(())
137        })
138    }
139}
140
141impl VercelLanguageModelProvider {
142    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
143        let state = cx.new(|cx| State {
144            api_key: None,
145            api_key_from_env: false,
146            _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
147                cx.notify();
148            }),
149        });
150
151        Self { http_client, state }
152    }
153
154    fn create_language_model(&self, model: vercel::Model) -> Arc<dyn LanguageModel> {
155        Arc::new(VercelLanguageModel {
156            id: LanguageModelId::from(model.id().to_string()),
157            model,
158            state: self.state.clone(),
159            http_client: self.http_client.clone(),
160            request_limiter: RateLimiter::new(4),
161        })
162    }
163}
164
165impl LanguageModelProviderState for VercelLanguageModelProvider {
166    type ObservableEntity = State;
167
168    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
169        Some(self.state.clone())
170    }
171}
172
173impl LanguageModelProvider for VercelLanguageModelProvider {
174    fn id(&self) -> LanguageModelProviderId {
175        PROVIDER_ID
176    }
177
178    fn name(&self) -> LanguageModelProviderName {
179        PROVIDER_NAME
180    }
181
182    fn icon(&self) -> IconName {
183        IconName::AiVZero
184    }
185
186    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
187        Some(self.create_language_model(vercel::Model::default()))
188    }
189
190    fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
191        Some(self.create_language_model(vercel::Model::default_fast()))
192    }
193
194    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
195        let mut models = BTreeMap::default();
196
197        for model in vercel::Model::iter() {
198            if !matches!(model, vercel::Model::Custom { .. }) {
199                models.insert(model.id().to_string(), model);
200            }
201        }
202
203        for model in &AllLanguageModelSettings::get_global(cx)
204            .vercel
205            .available_models
206        {
207            models.insert(
208                model.name.clone(),
209                vercel::Model::Custom {
210                    name: model.name.clone(),
211                    display_name: model.display_name.clone(),
212                    max_tokens: model.max_tokens,
213                    max_output_tokens: model.max_output_tokens,
214                    max_completion_tokens: model.max_completion_tokens,
215                },
216            );
217        }
218
219        models
220            .into_values()
221            .map(|model| self.create_language_model(model))
222            .collect()
223    }
224
225    fn is_authenticated(&self, cx: &App) -> bool {
226        self.state.read(cx).is_authenticated()
227    }
228
229    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
230        self.state.update(cx, |state, cx| state.authenticate(cx))
231    }
232
233    fn configuration_view(
234        &self,
235        _target_agent: language_model::ConfigurationViewTargetAgent,
236        window: &mut Window,
237        cx: &mut App,
238    ) -> AnyView {
239        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
240            .into()
241    }
242
243    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
244        self.state.update(cx, |state, cx| state.reset_api_key(cx))
245    }
246}
247
248pub struct VercelLanguageModel {
249    id: LanguageModelId,
250    model: vercel::Model,
251    state: gpui::Entity<State>,
252    http_client: Arc<dyn HttpClient>,
253    request_limiter: RateLimiter,
254}
255
256impl VercelLanguageModel {
257    fn stream_completion(
258        &self,
259        request: open_ai::Request,
260        cx: &AsyncApp,
261    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
262    {
263        let http_client = self.http_client.clone();
264        let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
265            let settings = &AllLanguageModelSettings::get_global(cx).vercel;
266            let api_url = if settings.api_url.is_empty() {
267                vercel::VERCEL_API_URL.to_string()
268            } else {
269                settings.api_url.clone()
270            };
271            (state.api_key.clone(), api_url)
272        }) else {
273            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
274        };
275
276        let future = self.request_limiter.stream(async move {
277            let Some(api_key) = api_key else {
278                return Err(LanguageModelCompletionError::NoApiKey {
279                    provider: PROVIDER_NAME,
280                });
281            };
282            let request =
283                open_ai::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
284            let response = request.await?;
285            Ok(response)
286        });
287
288        async move { Ok(future.await?.boxed()) }.boxed()
289    }
290}
291
292impl LanguageModel for VercelLanguageModel {
293    fn id(&self) -> LanguageModelId {
294        self.id.clone()
295    }
296
297    fn name(&self) -> LanguageModelName {
298        LanguageModelName::from(self.model.display_name().to_string())
299    }
300
301    fn provider_id(&self) -> LanguageModelProviderId {
302        PROVIDER_ID
303    }
304
305    fn provider_name(&self) -> LanguageModelProviderName {
306        PROVIDER_NAME
307    }
308
309    fn supports_tools(&self) -> bool {
310        true
311    }
312
313    fn supports_images(&self) -> bool {
314        true
315    }
316
317    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
318        match choice {
319            LanguageModelToolChoice::Auto
320            | LanguageModelToolChoice::Any
321            | LanguageModelToolChoice::None => true,
322        }
323    }
324
325    fn telemetry_id(&self) -> String {
326        format!("vercel/{}", self.model.id())
327    }
328
329    fn max_token_count(&self) -> u64 {
330        self.model.max_token_count()
331    }
332
333    fn max_output_tokens(&self) -> Option<u64> {
334        self.model.max_output_tokens()
335    }
336
337    fn count_tokens(
338        &self,
339        request: LanguageModelRequest,
340        cx: &App,
341    ) -> BoxFuture<'static, Result<u64>> {
342        count_vercel_tokens(request, self.model.clone(), cx)
343    }
344
345    fn stream_completion(
346        &self,
347        request: LanguageModelRequest,
348        cx: &AsyncApp,
349    ) -> BoxFuture<
350        'static,
351        Result<
352            futures::stream::BoxStream<
353                'static,
354                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
355            >,
356            LanguageModelCompletionError,
357        >,
358    > {
359        let request = crate::provider::open_ai::into_open_ai(
360            request,
361            self.model.id(),
362            self.model.supports_parallel_tool_calls(),
363            self.model.supports_prompt_cache_key(),
364            self.max_output_tokens(),
365            None,
366        );
367        let completions = self.stream_completion(request, cx);
368        async move {
369            let mapper = crate::provider::open_ai::OpenAiEventMapper::new();
370            Ok(mapper.map_stream(completions.await?).boxed())
371        }
372        .boxed()
373    }
374}
375
376pub fn count_vercel_tokens(
377    request: LanguageModelRequest,
378    model: Model,
379    cx: &App,
380) -> BoxFuture<'static, Result<u64>> {
381    cx.background_spawn(async move {
382        let messages = request
383            .messages
384            .into_iter()
385            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
386                role: match message.role {
387                    Role::User => "user".into(),
388                    Role::Assistant => "assistant".into(),
389                    Role::System => "system".into(),
390                },
391                content: Some(message.string_contents()),
392                name: None,
393                function_call: None,
394            })
395            .collect::<Vec<_>>();
396
397        match model {
398            Model::Custom { max_tokens, .. } => {
399                let model = if max_tokens >= 100_000 {
400                    // If the max tokens is 100k or more, it is likely the o200k_base tokenizer from gpt4o
401                    "gpt-4o"
402                } else {
403                    // Otherwise fallback to gpt-4, since only cl100k_base and o200k_base are
404                    // supported with this tiktoken method
405                    "gpt-4"
406                };
407                tiktoken_rs::num_tokens_from_messages(model, &messages)
408            }
409            // Map Vercel models to appropriate OpenAI models for token counting
410            // since Vercel uses OpenAI-compatible API
411            Model::VZeroOnePointFiveMedium => {
412                // Vercel v0 is similar to GPT-4o, so use gpt-4o for token counting
413                tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages)
414            }
415        }
416        .map(|tokens| tokens as u64)
417    })
418    .boxed()
419}
420
421struct ConfigurationView {
422    api_key_editor: Entity<SingleLineInput>,
423    state: gpui::Entity<State>,
424    load_credentials_task: Option<Task<()>>,
425}
426
427impl ConfigurationView {
428    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
429        let api_key_editor = cx.new(|cx| {
430            SingleLineInput::new(
431                window,
432                cx,
433                "v1:0000000000000000000000000000000000000000000000000",
434            )
435            .label("API key")
436        });
437
438        cx.observe(&state, |_, _, cx| {
439            cx.notify();
440        })
441        .detach();
442
443        let load_credentials_task = Some(cx.spawn_in(window, {
444            let state = state.clone();
445            async move |this, cx| {
446                if let Some(task) = state
447                    .update(cx, |state, cx| state.authenticate(cx))
448                    .log_err()
449                {
450                    // We don't log an error, because "not signed in" is also an error.
451                    let _ = task.await;
452                }
453                this.update(cx, |this, cx| {
454                    this.load_credentials_task = None;
455                    cx.notify();
456                })
457                .log_err();
458            }
459        }));
460
461        Self {
462            api_key_editor,
463            state,
464            load_credentials_task,
465        }
466    }
467
468    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
469        let api_key = self
470            .api_key_editor
471            .read(cx)
472            .editor()
473            .read(cx)
474            .text(cx)
475            .trim()
476            .to_string();
477
478        // Don't proceed if no API key is provided and we're not authenticated
479        if api_key.is_empty() && !self.state.read(cx).is_authenticated() {
480            return;
481        }
482
483        let state = self.state.clone();
484        cx.spawn_in(window, async move |_, cx| {
485            state
486                .update(cx, |state, cx| state.set_api_key(api_key, cx))?
487                .await
488        })
489        .detach_and_log_err(cx);
490
491        cx.notify();
492    }
493
494    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
495        self.api_key_editor.update(cx, |input, cx| {
496            input.editor.update(cx, |editor, cx| {
497                editor.set_text("", window, cx);
498            });
499        });
500
501        let state = self.state.clone();
502        cx.spawn_in(window, async move |_, cx| {
503            state.update(cx, |state, cx| state.reset_api_key(cx))?.await
504        })
505        .detach_and_log_err(cx);
506
507        cx.notify();
508    }
509
510    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
511        !self.state.read(cx).is_authenticated()
512    }
513}
514
515impl Render for ConfigurationView {
516    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
517        let env_var_set = self.state.read(cx).api_key_from_env;
518
519        let api_key_section = if self.should_render_editor(cx) {
520            v_flex()
521                .on_action(cx.listener(Self::save_api_key))
522                .child(Label::new("To use Zed's agent with Vercel v0, you need to add an API key. Follow these steps:"))
523                .child(
524                    List::new()
525                        .child(InstructionListItem::new(
526                            "Create one by visiting",
527                            Some("Vercel v0's console"),
528                            Some("https://v0.dev/chat/settings/keys"),
529                        ))
530                        .child(InstructionListItem::text_only(
531                            "Paste your API key below and hit enter to start using the agent",
532                        )),
533                )
534                .child(self.api_key_editor.clone())
535                .child(
536                    Label::new(format!(
537                        "You can also assign the {VERCEL_API_KEY_VAR} environment variable and restart Zed."
538                    ))
539                    .size(LabelSize::Small)
540                    .color(Color::Muted),
541                )
542                .child(
543                    Label::new("Note that Vercel v0 is a custom OpenAI-compatible provider.")
544                        .size(LabelSize::Small)
545                        .color(Color::Muted),
546                )
547                .into_any()
548        } else {
549            h_flex()
550                .mt_1()
551                .p_1()
552                .justify_between()
553                .rounded_md()
554                .border_1()
555                .border_color(cx.theme().colors().border)
556                .bg(cx.theme().colors().background)
557                .child(
558                    h_flex()
559                        .gap_1()
560                        .child(Icon::new(IconName::Check).color(Color::Success))
561                        .child(Label::new(if env_var_set {
562                            format!("API key set in {VERCEL_API_KEY_VAR} environment variable.")
563                        } else {
564                            "API key configured.".to_string()
565                        })),
566                )
567                .child(
568                    Button::new("reset-api-key", "Reset API Key")
569                        .label_size(LabelSize::Small)
570                        .icon(IconName::Undo)
571                        .icon_size(IconSize::Small)
572                        .icon_position(IconPosition::Start)
573                        .layer(ElevationIndex::ModalSurface)
574                        .when(env_var_set, |this| {
575                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {VERCEL_API_KEY_VAR} environment variable.")))
576                        })
577                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
578                )
579                .into_any()
580        };
581
582        if self.load_credentials_task.is_some() {
583            div().child(Label::new("Loading credentials…")).into_any()
584        } else {
585            v_flex().size_full().child(api_key_section).into_any()
586        }
587    }
588}