vercel.rs

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