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: &str = "vercel";
29const PROVIDER_NAME: &str = "Vercel";
30
31#[derive(Default, Clone, Debug, PartialEq)]
32pub struct VercelSettings {
33 pub api_url: String,
34 pub available_models: Vec<AvailableModel>,
35 pub needs_setting_migration: bool,
36}
37
38#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
39pub struct AvailableModel {
40 pub name: String,
41 pub display_name: Option<String>,
42 pub max_tokens: u64,
43 pub max_output_tokens: Option<u64>,
44 pub max_completion_tokens: Option<u64>,
45}
46
47pub struct VercelLanguageModelProvider {
48 http_client: Arc<dyn HttpClient>,
49 state: gpui::Entity<State>,
50}
51
52pub struct State {
53 api_key: Option<String>,
54 api_key_from_env: bool,
55 _subscription: Subscription,
56}
57
58const VERCEL_API_KEY_VAR: &str = "VERCEL_API_KEY";
59
60impl State {
61 fn is_authenticated(&self) -> bool {
62 self.api_key.is_some()
63 }
64
65 fn reset_api_key(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
66 let credentials_provider = <dyn CredentialsProvider>::global(cx);
67 let settings = &AllLanguageModelSettings::get_global(cx).vercel;
68 let api_url = if settings.api_url.is_empty() {
69 vercel::VERCEL_API_URL.to_string()
70 } else {
71 settings.api_url.clone()
72 };
73 cx.spawn(async move |this, cx| {
74 credentials_provider
75 .delete_credentials(&api_url, &cx)
76 .await
77 .log_err();
78 this.update(cx, |this, cx| {
79 this.api_key = None;
80 this.api_key_from_env = false;
81 cx.notify();
82 })
83 })
84 }
85
86 fn set_api_key(&mut self, api_key: String, cx: &mut Context<Self>) -> Task<Result<()>> {
87 let credentials_provider = <dyn CredentialsProvider>::global(cx);
88 let settings = &AllLanguageModelSettings::get_global(cx).vercel;
89 let api_url = if settings.api_url.is_empty() {
90 vercel::VERCEL_API_URL.to_string()
91 } else {
92 settings.api_url.clone()
93 };
94 cx.spawn(async move |this, cx| {
95 credentials_provider
96 .write_credentials(&api_url, "Bearer", api_key.as_bytes(), &cx)
97 .await
98 .log_err();
99 this.update(cx, |this, cx| {
100 this.api_key = Some(api_key);
101 cx.notify();
102 })
103 })
104 }
105
106 fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
107 if self.is_authenticated() {
108 return Task::ready(Ok(()));
109 }
110
111 let credentials_provider = <dyn CredentialsProvider>::global(cx);
112 let settings = &AllLanguageModelSettings::get_global(cx).vercel;
113 let api_url = if settings.api_url.is_empty() {
114 vercel::VERCEL_API_URL.to_string()
115 } else {
116 settings.api_url.clone()
117 };
118 cx.spawn(async move |this, cx| {
119 let (api_key, from_env) = if let Ok(api_key) = std::env::var(VERCEL_API_KEY_VAR) {
120 (api_key, true)
121 } else {
122 let (_, api_key) = credentials_provider
123 .read_credentials(&api_url, &cx)
124 .await?
125 .ok_or(AuthenticateError::CredentialsNotFound)?;
126 (
127 String::from_utf8(api_key).context("invalid {PROVIDER_NAME} API key")?,
128 false,
129 )
130 };
131 this.update(cx, |this, cx| {
132 this.api_key = Some(api_key);
133 this.api_key_from_env = from_env;
134 cx.notify();
135 })?;
136
137 Ok(())
138 })
139 }
140}
141
142impl VercelLanguageModelProvider {
143 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
144 let state = cx.new(|cx| State {
145 api_key: None,
146 api_key_from_env: false,
147 _subscription: cx.observe_global::<SettingsStore>(|_this: &mut State, cx| {
148 cx.notify();
149 }),
150 });
151
152 Self { http_client, state }
153 }
154
155 fn create_language_model(&self, model: vercel::Model) -> Arc<dyn LanguageModel> {
156 Arc::new(VercelLanguageModel {
157 id: LanguageModelId::from(model.id().to_string()),
158 model,
159 state: self.state.clone(),
160 http_client: self.http_client.clone(),
161 request_limiter: RateLimiter::new(4),
162 })
163 }
164}
165
166impl LanguageModelProviderState for VercelLanguageModelProvider {
167 type ObservableEntity = State;
168
169 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
170 Some(self.state.clone())
171 }
172}
173
174impl LanguageModelProvider for VercelLanguageModelProvider {
175 fn id(&self) -> LanguageModelProviderId {
176 LanguageModelProviderId(PROVIDER_ID.into())
177 }
178
179 fn name(&self) -> LanguageModelProviderName {
180 LanguageModelProviderName(PROVIDER_NAME.into())
181 }
182
183 fn icon(&self) -> IconName {
184 IconName::AiVZero
185 }
186
187 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
188 Some(self.create_language_model(vercel::Model::default()))
189 }
190
191 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
192 Some(self.create_language_model(vercel::Model::default_fast()))
193 }
194
195 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
196 let mut models = BTreeMap::default();
197
198 for model in vercel::Model::iter() {
199 if !matches!(model, vercel::Model::Custom { .. }) {
200 models.insert(model.id().to_string(), model);
201 }
202 }
203
204 for model in &AllLanguageModelSettings::get_global(cx)
205 .vercel
206 .available_models
207 {
208 models.insert(
209 model.name.clone(),
210 vercel::Model::Custom {
211 name: model.name.clone(),
212 display_name: model.display_name.clone(),
213 max_tokens: model.max_tokens,
214 max_output_tokens: model.max_output_tokens,
215 max_completion_tokens: model.max_completion_tokens,
216 },
217 );
218 }
219
220 models
221 .into_values()
222 .map(|model| self.create_language_model(model))
223 .collect()
224 }
225
226 fn is_authenticated(&self, cx: &App) -> bool {
227 self.state.read(cx).is_authenticated()
228 }
229
230 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
231 self.state.update(cx, |state, cx| state.authenticate(cx))
232 }
233
234 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
235 cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
236 .into()
237 }
238
239 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
240 self.state.update(cx, |state, cx| state.reset_api_key(cx))
241 }
242}
243
244pub struct VercelLanguageModel {
245 id: LanguageModelId,
246 model: vercel::Model,
247 state: gpui::Entity<State>,
248 http_client: Arc<dyn HttpClient>,
249 request_limiter: RateLimiter,
250}
251
252impl VercelLanguageModel {
253 fn stream_completion(
254 &self,
255 request: open_ai::Request,
256 cx: &AsyncApp,
257 ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
258 {
259 let http_client = self.http_client.clone();
260 let Ok((api_key, api_url)) = cx.read_entity(&self.state, |state, cx| {
261 let settings = &AllLanguageModelSettings::get_global(cx).vercel;
262 let api_url = if settings.api_url.is_empty() {
263 vercel::VERCEL_API_URL.to_string()
264 } else {
265 settings.api_url.clone()
266 };
267 (state.api_key.clone(), api_url)
268 }) else {
269 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
270 };
271
272 let future = self.request_limiter.stream(async move {
273 let api_key = api_key.context("Missing Vercel API Key")?;
274 let request =
275 open_ai::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
276 let response = request.await?;
277 Ok(response)
278 });
279
280 async move { Ok(future.await?.boxed()) }.boxed()
281 }
282}
283
284impl LanguageModel for VercelLanguageModel {
285 fn id(&self) -> LanguageModelId {
286 self.id.clone()
287 }
288
289 fn name(&self) -> LanguageModelName {
290 LanguageModelName::from(self.model.display_name().to_string())
291 }
292
293 fn provider_id(&self) -> LanguageModelProviderId {
294 LanguageModelProviderId(PROVIDER_ID.into())
295 }
296
297 fn provider_name(&self) -> LanguageModelProviderName {
298 LanguageModelProviderName(PROVIDER_NAME.into())
299 }
300
301 fn supports_tools(&self) -> bool {
302 true
303 }
304
305 fn supports_images(&self) -> bool {
306 false
307 }
308
309 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
310 match choice {
311 LanguageModelToolChoice::Auto => true,
312 LanguageModelToolChoice::Any => true,
313 LanguageModelToolChoice::None => true,
314 }
315 }
316
317 fn telemetry_id(&self) -> String {
318 format!("vercel/{}", self.model.id())
319 }
320
321 fn max_token_count(&self) -> u64 {
322 self.model.max_token_count()
323 }
324
325 fn max_output_tokens(&self) -> Option<u64> {
326 self.model.max_output_tokens()
327 }
328
329 fn count_tokens(
330 &self,
331 request: LanguageModelRequest,
332 cx: &App,
333 ) -> BoxFuture<'static, Result<u64>> {
334 count_vercel_tokens(request, self.model.clone(), cx)
335 }
336
337 fn stream_completion(
338 &self,
339 request: LanguageModelRequest,
340 cx: &AsyncApp,
341 ) -> BoxFuture<
342 'static,
343 Result<
344 futures::stream::BoxStream<
345 'static,
346 Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
347 >,
348 LanguageModelCompletionError,
349 >,
350 > {
351 let request = crate::provider::open_ai::into_open_ai(
352 request,
353 self.model.id(),
354 self.model.supports_parallel_tool_calls(),
355 self.max_output_tokens(),
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::VZero => {
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}