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