cloud.rs

   1use anthropic::{AnthropicModelMode, parse_prompt_too_long};
   2use anyhow::{Result, anyhow};
   3use client::{Client, UserStore, zed_urls};
   4use collections::BTreeMap;
   5use feature_flags::{FeatureFlagAppExt, LlmClosedBetaFeatureFlag, ZedProFeatureFlag};
   6use futures::{
   7    AsyncBufReadExt, FutureExt, Stream, StreamExt, future::BoxFuture, stream::BoxStream,
   8};
   9use gpui::{AnyElement, AnyView, App, AsyncApp, Context, Entity, Subscription, Task};
  10use http_client::{AsyncBody, HttpClient, Method, Response, StatusCode};
  11use language_model::{
  12    AuthenticateError, CloudModel, LanguageModel, LanguageModelCacheConfiguration,
  13    LanguageModelCompletionError, LanguageModelId, LanguageModelKnownError, LanguageModelName,
  14    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
  15    LanguageModelProviderTosView, LanguageModelRequest, LanguageModelToolSchemaFormat,
  16    ModelRequestLimitReachedError, QueueState, RateLimiter, RequestUsage, ZED_CLOUD_PROVIDER_ID,
  17};
  18use language_model::{
  19    LanguageModelAvailability, LanguageModelCompletionEvent, LanguageModelProvider, LlmApiToken,
  20    MaxMonthlySpendReachedError, PaymentRequiredError, RefreshLlmTokenListener,
  21};
  22use proto::Plan;
  23use schemars::JsonSchema;
  24use serde::{Deserialize, Serialize, de::DeserializeOwned};
  25use settings::{Settings, SettingsStore};
  26use smol::Timer;
  27use smol::io::{AsyncReadExt, BufReader};
  28use std::pin::Pin;
  29use std::str::FromStr as _;
  30use std::{
  31    sync::{Arc, LazyLock},
  32    time::Duration,
  33};
  34use strum::IntoEnumIterator;
  35use thiserror::Error;
  36use ui::{TintColor, prelude::*};
  37use zed_llm_client::{
  38    CURRENT_PLAN_HEADER_NAME, CompletionBody, CountTokensBody, CountTokensResponse,
  39    EXPIRED_LLM_TOKEN_HEADER_NAME, MAX_LLM_MONTHLY_SPEND_REACHED_HEADER_NAME,
  40    MODEL_REQUESTS_RESOURCE_HEADER_VALUE, SUBSCRIPTION_LIMIT_RESOURCE_HEADER_NAME,
  41};
  42
  43use crate::AllLanguageModelSettings;
  44use crate::provider::anthropic::{AnthropicEventMapper, count_anthropic_tokens, into_anthropic};
  45use crate::provider::google::{GoogleEventMapper, into_google};
  46use crate::provider::open_ai::{OpenAiEventMapper, count_open_ai_tokens, into_open_ai};
  47
  48pub const PROVIDER_NAME: &str = "Zed";
  49
  50const ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: Option<&str> =
  51    option_env!("ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON");
  52
  53fn zed_cloud_provider_additional_models() -> &'static [AvailableModel] {
  54    static ADDITIONAL_MODELS: LazyLock<Vec<AvailableModel>> = LazyLock::new(|| {
  55        ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON
  56            .map(|json| serde_json::from_str(json).unwrap())
  57            .unwrap_or_default()
  58    });
  59    ADDITIONAL_MODELS.as_slice()
  60}
  61
  62#[derive(Default, Clone, Debug, PartialEq)]
  63pub struct ZedDotDevSettings {
  64    pub available_models: Vec<AvailableModel>,
  65}
  66
  67#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
  68#[serde(rename_all = "lowercase")]
  69pub enum AvailableProvider {
  70    Anthropic,
  71    OpenAi,
  72    Google,
  73}
  74
  75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
  76pub struct AvailableModel {
  77    /// The provider of the language model.
  78    pub provider: AvailableProvider,
  79    /// The model's name in the provider's API. e.g. claude-3-5-sonnet-20240620
  80    pub name: String,
  81    /// The name displayed in the UI, such as in the assistant panel model dropdown menu.
  82    pub display_name: Option<String>,
  83    /// The size of the context window, indicating the maximum number of tokens the model can process.
  84    pub max_tokens: usize,
  85    /// The maximum number of output tokens allowed by the model.
  86    pub max_output_tokens: Option<u32>,
  87    /// The maximum number of completion tokens allowed by the model (o1-* only)
  88    pub max_completion_tokens: Option<u32>,
  89    /// Override this model with a different Anthropic model for tool calls.
  90    pub tool_override: Option<String>,
  91    /// Indicates whether this custom model supports caching.
  92    pub cache_configuration: Option<LanguageModelCacheConfiguration>,
  93    /// The default temperature to use for this model.
  94    pub default_temperature: Option<f32>,
  95    /// Any extra beta headers to provide when using the model.
  96    #[serde(default)]
  97    pub extra_beta_headers: Vec<String>,
  98    /// The model's mode (e.g. thinking)
  99    pub mode: Option<ModelMode>,
 100}
 101
 102#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 103#[serde(tag = "type", rename_all = "lowercase")]
 104pub enum ModelMode {
 105    #[default]
 106    Default,
 107    Thinking {
 108        /// The maximum number of tokens to use for reasoning. Must be lower than the model's `max_output_tokens`.
 109        budget_tokens: Option<u32>,
 110    },
 111}
 112
 113impl From<ModelMode> for AnthropicModelMode {
 114    fn from(value: ModelMode) -> Self {
 115        match value {
 116            ModelMode::Default => AnthropicModelMode::Default,
 117            ModelMode::Thinking { budget_tokens } => AnthropicModelMode::Thinking { budget_tokens },
 118        }
 119    }
 120}
 121
 122pub struct CloudLanguageModelProvider {
 123    client: Arc<Client>,
 124    state: gpui::Entity<State>,
 125    _maintain_client_status: Task<()>,
 126}
 127
 128pub struct State {
 129    client: Arc<Client>,
 130    llm_api_token: LlmApiToken,
 131    user_store: Entity<UserStore>,
 132    status: client::Status,
 133    accept_terms: Option<Task<Result<()>>>,
 134    _settings_subscription: Subscription,
 135    _llm_token_subscription: Subscription,
 136}
 137
 138impl State {
 139    fn new(
 140        client: Arc<Client>,
 141        user_store: Entity<UserStore>,
 142        status: client::Status,
 143        cx: &mut Context<Self>,
 144    ) -> Self {
 145        let refresh_llm_token_listener = RefreshLlmTokenListener::global(cx);
 146
 147        Self {
 148            client: client.clone(),
 149            llm_api_token: LlmApiToken::default(),
 150            user_store,
 151            status,
 152            accept_terms: None,
 153            _settings_subscription: cx.observe_global::<SettingsStore>(|_, cx| {
 154                cx.notify();
 155            }),
 156            _llm_token_subscription: cx.subscribe(
 157                &refresh_llm_token_listener,
 158                |this, _listener, _event, cx| {
 159                    let client = this.client.clone();
 160                    let llm_api_token = this.llm_api_token.clone();
 161                    cx.spawn(async move |_this, _cx| {
 162                        llm_api_token.refresh(&client).await?;
 163                        anyhow::Ok(())
 164                    })
 165                    .detach_and_log_err(cx);
 166                },
 167            ),
 168        }
 169    }
 170
 171    fn is_signed_out(&self) -> bool {
 172        self.status.is_signed_out()
 173    }
 174
 175    fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 176        let client = self.client.clone();
 177        cx.spawn(async move |this, cx| {
 178            client.authenticate_and_connect(true, &cx).await?;
 179            this.update(cx, |_, cx| cx.notify())
 180        })
 181    }
 182
 183    fn has_accepted_terms_of_service(&self, cx: &App) -> bool {
 184        self.user_store
 185            .read(cx)
 186            .current_user_has_accepted_terms()
 187            .unwrap_or(false)
 188    }
 189
 190    fn accept_terms_of_service(&mut self, cx: &mut Context<Self>) {
 191        let user_store = self.user_store.clone();
 192        self.accept_terms = Some(cx.spawn(async move |this, cx| {
 193            let _ = user_store
 194                .update(cx, |store, cx| store.accept_terms_of_service(cx))?
 195                .await;
 196            this.update(cx, |this, cx| {
 197                this.accept_terms = None;
 198                cx.notify()
 199            })
 200        }));
 201    }
 202}
 203
 204impl CloudLanguageModelProvider {
 205    pub fn new(user_store: Entity<UserStore>, client: Arc<Client>, cx: &mut App) -> Self {
 206        let mut status_rx = client.status();
 207        let status = *status_rx.borrow();
 208
 209        let state = cx.new(|cx| State::new(client.clone(), user_store.clone(), status, cx));
 210
 211        let state_ref = state.downgrade();
 212        let maintain_client_status = cx.spawn(async move |cx| {
 213            while let Some(status) = status_rx.next().await {
 214                if let Some(this) = state_ref.upgrade() {
 215                    _ = this.update(cx, |this, cx| {
 216                        if this.status != status {
 217                            this.status = status;
 218                            cx.notify();
 219                        }
 220                    });
 221                } else {
 222                    break;
 223                }
 224            }
 225        });
 226
 227        Self {
 228            client,
 229            state: state.clone(),
 230            _maintain_client_status: maintain_client_status,
 231        }
 232    }
 233
 234    fn create_language_model(
 235        &self,
 236        model: CloudModel,
 237        llm_api_token: LlmApiToken,
 238    ) -> Arc<dyn LanguageModel> {
 239        Arc::new(CloudLanguageModel {
 240            id: LanguageModelId::from(model.id().to_string()),
 241            model,
 242            llm_api_token: llm_api_token.clone(),
 243            client: self.client.clone(),
 244            request_limiter: RateLimiter::new(4),
 245        })
 246    }
 247}
 248
 249impl LanguageModelProviderState for CloudLanguageModelProvider {
 250    type ObservableEntity = State;
 251
 252    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
 253        Some(self.state.clone())
 254    }
 255}
 256
 257impl LanguageModelProvider for CloudLanguageModelProvider {
 258    fn id(&self) -> LanguageModelProviderId {
 259        LanguageModelProviderId(ZED_CLOUD_PROVIDER_ID.into())
 260    }
 261
 262    fn name(&self) -> LanguageModelProviderName {
 263        LanguageModelProviderName(PROVIDER_NAME.into())
 264    }
 265
 266    fn icon(&self) -> IconName {
 267        IconName::AiZed
 268    }
 269
 270    fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
 271        let llm_api_token = self.state.read(cx).llm_api_token.clone();
 272        let model = CloudModel::Anthropic(anthropic::Model::Claude3_7Sonnet);
 273        Some(self.create_language_model(model, llm_api_token))
 274    }
 275
 276    fn default_fast_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
 277        let llm_api_token = self.state.read(cx).llm_api_token.clone();
 278        let model = CloudModel::Anthropic(anthropic::Model::Claude3_5Sonnet);
 279        Some(self.create_language_model(model, llm_api_token))
 280    }
 281
 282    fn recommended_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
 283        let llm_api_token = self.state.read(cx).llm_api_token.clone();
 284        [
 285            CloudModel::Anthropic(anthropic::Model::Claude3_7Sonnet),
 286            CloudModel::Anthropic(anthropic::Model::Claude3_7SonnetThinking),
 287        ]
 288        .into_iter()
 289        .map(|model| self.create_language_model(model, llm_api_token.clone()))
 290        .collect()
 291    }
 292
 293    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
 294        let mut models = BTreeMap::default();
 295
 296        if cx.is_staff() {
 297            for model in anthropic::Model::iter() {
 298                if !matches!(model, anthropic::Model::Custom { .. }) {
 299                    models.insert(model.id().to_string(), CloudModel::Anthropic(model));
 300                }
 301            }
 302            for model in open_ai::Model::iter() {
 303                if !matches!(model, open_ai::Model::Custom { .. }) {
 304                    models.insert(model.id().to_string(), CloudModel::OpenAi(model));
 305                }
 306            }
 307            for model in google_ai::Model::iter() {
 308                if !matches!(model, google_ai::Model::Custom { .. }) {
 309                    models.insert(model.id().to_string(), CloudModel::Google(model));
 310                }
 311            }
 312        } else {
 313            models.insert(
 314                anthropic::Model::Claude3_5Sonnet.id().to_string(),
 315                CloudModel::Anthropic(anthropic::Model::Claude3_5Sonnet),
 316            );
 317            models.insert(
 318                anthropic::Model::Claude3_7Sonnet.id().to_string(),
 319                CloudModel::Anthropic(anthropic::Model::Claude3_7Sonnet),
 320            );
 321            models.insert(
 322                anthropic::Model::Claude3_7SonnetThinking.id().to_string(),
 323                CloudModel::Anthropic(anthropic::Model::Claude3_7SonnetThinking),
 324            );
 325        }
 326
 327        let llm_closed_beta_models = if cx.has_flag::<LlmClosedBetaFeatureFlag>() {
 328            zed_cloud_provider_additional_models()
 329        } else {
 330            &[]
 331        };
 332
 333        // Override with available models from settings
 334        for model in AllLanguageModelSettings::get_global(cx)
 335            .zed_dot_dev
 336            .available_models
 337            .iter()
 338            .chain(llm_closed_beta_models)
 339            .cloned()
 340        {
 341            let model = match model.provider {
 342                AvailableProvider::Anthropic => CloudModel::Anthropic(anthropic::Model::Custom {
 343                    name: model.name.clone(),
 344                    display_name: model.display_name.clone(),
 345                    max_tokens: model.max_tokens,
 346                    tool_override: model.tool_override.clone(),
 347                    cache_configuration: model.cache_configuration.as_ref().map(|config| {
 348                        anthropic::AnthropicModelCacheConfiguration {
 349                            max_cache_anchors: config.max_cache_anchors,
 350                            should_speculate: config.should_speculate,
 351                            min_total_token: config.min_total_token,
 352                        }
 353                    }),
 354                    default_temperature: model.default_temperature,
 355                    max_output_tokens: model.max_output_tokens,
 356                    extra_beta_headers: model.extra_beta_headers.clone(),
 357                    mode: model.mode.unwrap_or_default().into(),
 358                }),
 359                AvailableProvider::OpenAi => CloudModel::OpenAi(open_ai::Model::Custom {
 360                    name: model.name.clone(),
 361                    display_name: model.display_name.clone(),
 362                    max_tokens: model.max_tokens,
 363                    max_output_tokens: model.max_output_tokens,
 364                    max_completion_tokens: model.max_completion_tokens,
 365                }),
 366                AvailableProvider::Google => CloudModel::Google(google_ai::Model::Custom {
 367                    name: model.name.clone(),
 368                    display_name: model.display_name.clone(),
 369                    max_tokens: model.max_tokens,
 370                }),
 371            };
 372            models.insert(model.id().to_string(), model.clone());
 373        }
 374
 375        let llm_api_token = self.state.read(cx).llm_api_token.clone();
 376        models
 377            .into_values()
 378            .map(|model| self.create_language_model(model, llm_api_token.clone()))
 379            .collect()
 380    }
 381
 382    fn is_authenticated(&self, cx: &App) -> bool {
 383        !self.state.read(cx).is_signed_out()
 384    }
 385
 386    fn authenticate(&self, _cx: &mut App) -> Task<Result<(), AuthenticateError>> {
 387        Task::ready(Ok(()))
 388    }
 389
 390    fn configuration_view(&self, _: &mut Window, cx: &mut App) -> AnyView {
 391        cx.new(|_| ConfigurationView {
 392            state: self.state.clone(),
 393        })
 394        .into()
 395    }
 396
 397    fn must_accept_terms(&self, cx: &App) -> bool {
 398        !self.state.read(cx).has_accepted_terms_of_service(cx)
 399    }
 400
 401    fn render_accept_terms(
 402        &self,
 403        view: LanguageModelProviderTosView,
 404        cx: &mut App,
 405    ) -> Option<AnyElement> {
 406        render_accept_terms(self.state.clone(), view, cx)
 407    }
 408
 409    fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
 410        Task::ready(Ok(()))
 411    }
 412}
 413
 414fn render_accept_terms(
 415    state: Entity<State>,
 416    view_kind: LanguageModelProviderTosView,
 417    cx: &mut App,
 418) -> Option<AnyElement> {
 419    if state.read(cx).has_accepted_terms_of_service(cx) {
 420        return None;
 421    }
 422
 423    let accept_terms_disabled = state.read(cx).accept_terms.is_some();
 424
 425    let thread_fresh_start = matches!(view_kind, LanguageModelProviderTosView::ThreadFreshStart);
 426    let thread_empty_state = matches!(view_kind, LanguageModelProviderTosView::ThreadtEmptyState);
 427
 428    let terms_button = Button::new("terms_of_service", "Terms of Service")
 429        .style(ButtonStyle::Subtle)
 430        .icon(IconName::ArrowUpRight)
 431        .icon_color(Color::Muted)
 432        .icon_size(IconSize::XSmall)
 433        .when(thread_empty_state, |this| this.label_size(LabelSize::Small))
 434        .on_click(move |_, _window, cx| cx.open_url("https://zed.dev/terms-of-service"));
 435
 436    let button_container = h_flex().child(
 437        Button::new("accept_terms", "I accept the Terms of Service")
 438            .when(!thread_empty_state, |this| {
 439                this.full_width()
 440                    .style(ButtonStyle::Tinted(TintColor::Accent))
 441                    .icon(IconName::Check)
 442                    .icon_position(IconPosition::Start)
 443                    .icon_size(IconSize::Small)
 444            })
 445            .when(thread_empty_state, |this| {
 446                this.style(ButtonStyle::Tinted(TintColor::Warning))
 447                    .label_size(LabelSize::Small)
 448            })
 449            .disabled(accept_terms_disabled)
 450            .on_click({
 451                let state = state.downgrade();
 452                move |_, _window, cx| {
 453                    state
 454                        .update(cx, |state, cx| state.accept_terms_of_service(cx))
 455                        .ok();
 456                }
 457            }),
 458    );
 459
 460    let form = if thread_empty_state {
 461        h_flex()
 462            .w_full()
 463            .flex_wrap()
 464            .justify_between()
 465            .child(
 466                h_flex()
 467                    .child(
 468                        Label::new("To start using Zed AI, please read and accept the")
 469                            .size(LabelSize::Small),
 470                    )
 471                    .child(terms_button),
 472            )
 473            .child(button_container)
 474    } else {
 475        v_flex()
 476            .w_full()
 477            .gap_2()
 478            .child(
 479                h_flex()
 480                    .flex_wrap()
 481                    .when(thread_fresh_start, |this| this.justify_center())
 482                    .child(Label::new(
 483                        "To start using Zed AI, please read and accept the",
 484                    ))
 485                    .child(terms_button),
 486            )
 487            .child({
 488                match view_kind {
 489                    LanguageModelProviderTosView::PromptEditorPopup => {
 490                        button_container.w_full().justify_end()
 491                    }
 492                    LanguageModelProviderTosView::Configuration => {
 493                        button_container.w_full().justify_start()
 494                    }
 495                    LanguageModelProviderTosView::ThreadFreshStart => {
 496                        button_container.w_full().justify_center()
 497                    }
 498                    LanguageModelProviderTosView::ThreadtEmptyState => div().w_0(),
 499                }
 500            })
 501    };
 502
 503    Some(form.into_any())
 504}
 505
 506pub struct CloudLanguageModel {
 507    id: LanguageModelId,
 508    model: CloudModel,
 509    llm_api_token: LlmApiToken,
 510    client: Arc<Client>,
 511    request_limiter: RateLimiter,
 512}
 513
 514impl CloudLanguageModel {
 515    const MAX_RETRIES: usize = 3;
 516
 517    async fn perform_llm_completion(
 518        client: Arc<Client>,
 519        llm_api_token: LlmApiToken,
 520        body: CompletionBody,
 521    ) -> Result<(Response<AsyncBody>, Option<RequestUsage>, bool)> {
 522        let http_client = &client.http_client();
 523
 524        let mut token = llm_api_token.acquire(&client).await?;
 525        let mut retries_remaining = Self::MAX_RETRIES;
 526        let mut retry_delay = Duration::from_secs(1);
 527
 528        loop {
 529            let request_builder = http_client::Request::builder().method(Method::POST);
 530            let request_builder = if let Ok(completions_url) = std::env::var("ZED_COMPLETIONS_URL")
 531            {
 532                request_builder.uri(completions_url)
 533            } else {
 534                request_builder.uri(http_client.build_zed_llm_url("/completions", &[])?.as_ref())
 535            };
 536            let request = request_builder
 537                .header("Content-Type", "application/json")
 538                .header("Authorization", format!("Bearer {token}"))
 539                .header("x-zed-client-supports-queueing", "true")
 540                .body(serde_json::to_string(&body)?.into())?;
 541            let mut response = http_client.send(request).await?;
 542            let status = response.status();
 543            if status.is_success() {
 544                let includes_queue_events = response
 545                    .headers()
 546                    .get("x-zed-server-supports-queueing")
 547                    .is_some();
 548                let usage = RequestUsage::from_headers(response.headers()).ok();
 549
 550                return Ok((response, usage, includes_queue_events));
 551            } else if response
 552                .headers()
 553                .get(EXPIRED_LLM_TOKEN_HEADER_NAME)
 554                .is_some()
 555            {
 556                retries_remaining -= 1;
 557                token = llm_api_token.refresh(&client).await?;
 558            } else if status == StatusCode::FORBIDDEN
 559                && response
 560                    .headers()
 561                    .get(MAX_LLM_MONTHLY_SPEND_REACHED_HEADER_NAME)
 562                    .is_some()
 563            {
 564                return Err(anyhow!(MaxMonthlySpendReachedError));
 565            } else if status == StatusCode::FORBIDDEN
 566                && response
 567                    .headers()
 568                    .get(SUBSCRIPTION_LIMIT_RESOURCE_HEADER_NAME)
 569                    .is_some()
 570            {
 571                if let Some(MODEL_REQUESTS_RESOURCE_HEADER_VALUE) = response
 572                    .headers()
 573                    .get(SUBSCRIPTION_LIMIT_RESOURCE_HEADER_NAME)
 574                    .and_then(|resource| resource.to_str().ok())
 575                {
 576                    if let Some(plan) = response
 577                        .headers()
 578                        .get(CURRENT_PLAN_HEADER_NAME)
 579                        .and_then(|plan| plan.to_str().ok())
 580                        .and_then(|plan| zed_llm_client::Plan::from_str(plan).ok())
 581                    {
 582                        let plan = match plan {
 583                            zed_llm_client::Plan::Free => Plan::Free,
 584                            zed_llm_client::Plan::ZedPro => Plan::ZedPro,
 585                            zed_llm_client::Plan::ZedProTrial => Plan::ZedProTrial,
 586                        };
 587                        return Err(anyhow!(ModelRequestLimitReachedError { plan }));
 588                    }
 589                }
 590
 591                return Err(anyhow!("Forbidden"));
 592            } else if status.as_u16() >= 500 && status.as_u16() < 600 {
 593                // If we encounter an error in the 500 range, retry after a delay.
 594                // We've seen at least these in the wild from API providers:
 595                // * 500 Internal Server Error
 596                // * 502 Bad Gateway
 597                // * 529 Service Overloaded
 598
 599                if retries_remaining == 0 {
 600                    let mut body = String::new();
 601                    response.body_mut().read_to_string(&mut body).await?;
 602                    return Err(anyhow!(
 603                        "cloud language model completion failed after {} retries with status {status}: {body}",
 604                        Self::MAX_RETRIES
 605                    ));
 606                }
 607
 608                Timer::after(retry_delay).await;
 609
 610                retries_remaining -= 1;
 611                retry_delay *= 2; // If it fails again, wait longer.
 612            } else if status == StatusCode::PAYMENT_REQUIRED {
 613                return Err(anyhow!(PaymentRequiredError));
 614            } else {
 615                let mut body = String::new();
 616                response.body_mut().read_to_string(&mut body).await?;
 617                return Err(anyhow!(ApiError { status, body }));
 618            }
 619        }
 620    }
 621}
 622
 623#[derive(Debug, Error)]
 624#[error("cloud language model completion failed with status {status}: {body}")]
 625struct ApiError {
 626    status: StatusCode,
 627    body: String,
 628}
 629
 630impl LanguageModel for CloudLanguageModel {
 631    fn id(&self) -> LanguageModelId {
 632        self.id.clone()
 633    }
 634
 635    fn name(&self) -> LanguageModelName {
 636        LanguageModelName::from(self.model.display_name().to_string())
 637    }
 638
 639    fn provider_id(&self) -> LanguageModelProviderId {
 640        LanguageModelProviderId(ZED_CLOUD_PROVIDER_ID.into())
 641    }
 642
 643    fn provider_name(&self) -> LanguageModelProviderName {
 644        LanguageModelProviderName(PROVIDER_NAME.into())
 645    }
 646
 647    fn supports_tools(&self) -> bool {
 648        match self.model {
 649            CloudModel::Anthropic(_) => true,
 650            CloudModel::Google(_) => true,
 651            CloudModel::OpenAi(_) => true,
 652        }
 653    }
 654
 655    fn telemetry_id(&self) -> String {
 656        format!("zed.dev/{}", self.model.id())
 657    }
 658
 659    fn availability(&self) -> LanguageModelAvailability {
 660        self.model.availability()
 661    }
 662
 663    fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
 664        self.model.tool_input_format()
 665    }
 666
 667    fn max_token_count(&self) -> usize {
 668        self.model.max_token_count()
 669    }
 670
 671    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
 672        match &self.model {
 673            CloudModel::Anthropic(model) => {
 674                model
 675                    .cache_configuration()
 676                    .map(|cache| LanguageModelCacheConfiguration {
 677                        max_cache_anchors: cache.max_cache_anchors,
 678                        should_speculate: cache.should_speculate,
 679                        min_total_token: cache.min_total_token,
 680                    })
 681            }
 682            CloudModel::OpenAi(_) | CloudModel::Google(_) => None,
 683        }
 684    }
 685
 686    fn count_tokens(
 687        &self,
 688        request: LanguageModelRequest,
 689        cx: &App,
 690    ) -> BoxFuture<'static, Result<usize>> {
 691        match self.model.clone() {
 692            CloudModel::Anthropic(_) => count_anthropic_tokens(request, cx),
 693            CloudModel::OpenAi(model) => count_open_ai_tokens(request, model, cx),
 694            CloudModel::Google(model) => {
 695                let client = self.client.clone();
 696                let llm_api_token = self.llm_api_token.clone();
 697                let request = into_google(request, model.id().into());
 698                async move {
 699                    let http_client = &client.http_client();
 700                    let token = llm_api_token.acquire(&client).await?;
 701
 702                    let request_builder = http_client::Request::builder().method(Method::POST);
 703                    let request_builder =
 704                        if let Ok(completions_url) = std::env::var("ZED_COUNT_TOKENS_URL") {
 705                            request_builder.uri(completions_url)
 706                        } else {
 707                            request_builder.uri(
 708                                http_client
 709                                    .build_zed_llm_url("/count_tokens", &[])?
 710                                    .as_ref(),
 711                            )
 712                        };
 713                    let request_body = CountTokensBody {
 714                        provider: zed_llm_client::LanguageModelProvider::Google,
 715                        model: model.id().into(),
 716                        provider_request: serde_json::to_value(&google_ai::CountTokensRequest {
 717                            contents: request.contents,
 718                        })?,
 719                    };
 720                    let request = request_builder
 721                        .header("Content-Type", "application/json")
 722                        .header("Authorization", format!("Bearer {token}"))
 723                        .body(serde_json::to_string(&request_body)?.into())?;
 724                    let mut response = http_client.send(request).await?;
 725                    let status = response.status();
 726                    let mut response_body = String::new();
 727                    response
 728                        .body_mut()
 729                        .read_to_string(&mut response_body)
 730                        .await?;
 731
 732                    if status.is_success() {
 733                        let response_body: CountTokensResponse =
 734                            serde_json::from_str(&response_body)?;
 735
 736                        Ok(response_body.tokens)
 737                    } else {
 738                        Err(anyhow!(ApiError {
 739                            status,
 740                            body: response_body
 741                        }))
 742                    }
 743                }
 744                .boxed()
 745            }
 746        }
 747    }
 748
 749    fn stream_completion(
 750        &self,
 751        request: LanguageModelRequest,
 752        cx: &AsyncApp,
 753    ) -> BoxFuture<
 754        'static,
 755        Result<
 756            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
 757        >,
 758    > {
 759        self.stream_completion_with_usage(request, cx)
 760            .map(|result| result.map(|(stream, _)| stream))
 761            .boxed()
 762    }
 763
 764    fn stream_completion_with_usage(
 765        &self,
 766        request: LanguageModelRequest,
 767        _cx: &AsyncApp,
 768    ) -> BoxFuture<
 769        'static,
 770        Result<(
 771            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
 772            Option<RequestUsage>,
 773        )>,
 774    > {
 775        let thread_id = request.thread_id.clone();
 776        let prompt_id = request.prompt_id.clone();
 777        let mode = request.mode;
 778        match &self.model {
 779            CloudModel::Anthropic(model) => {
 780                let request = into_anthropic(
 781                    request,
 782                    model.request_id().into(),
 783                    model.default_temperature(),
 784                    model.max_output_tokens(),
 785                    model.mode(),
 786                );
 787                let client = self.client.clone();
 788                let llm_api_token = self.llm_api_token.clone();
 789                let future = self.request_limiter.stream_with_usage(async move {
 790                    let (response, usage, includes_queue_events) = Self::perform_llm_completion(
 791                        client.clone(),
 792                        llm_api_token,
 793                        CompletionBody {
 794                            thread_id,
 795                            prompt_id,
 796                            mode,
 797                            provider: zed_llm_client::LanguageModelProvider::Anthropic,
 798                            model: request.model.clone(),
 799                            provider_request: serde_json::to_value(&request)?,
 800                        },
 801                    )
 802                    .await
 803                    .map_err(|err| match err.downcast::<ApiError>() {
 804                        Ok(api_err) => {
 805                            if api_err.status == StatusCode::BAD_REQUEST {
 806                                if let Some(tokens) = parse_prompt_too_long(&api_err.body) {
 807                                    return anyhow!(
 808                                        LanguageModelKnownError::ContextWindowLimitExceeded {
 809                                            tokens
 810                                        }
 811                                    );
 812                                }
 813                            }
 814                            anyhow!(api_err)
 815                        }
 816                        Err(err) => anyhow!(err),
 817                    })?;
 818
 819                    let mut mapper = AnthropicEventMapper::new();
 820                    Ok((
 821                        map_cloud_completion_events(
 822                            Box::pin(response_lines(response, includes_queue_events)),
 823                            move |event| mapper.map_event(event),
 824                        ),
 825                        usage,
 826                    ))
 827                });
 828                async move {
 829                    let (stream, usage) = future.await?;
 830                    Ok((stream.boxed(), usage))
 831                }
 832                .boxed()
 833            }
 834            CloudModel::OpenAi(model) => {
 835                let client = self.client.clone();
 836                let request = into_open_ai(request, model, model.max_output_tokens());
 837                let llm_api_token = self.llm_api_token.clone();
 838                let future = self.request_limiter.stream_with_usage(async move {
 839                    let (response, usage, includes_queue_events) = Self::perform_llm_completion(
 840                        client.clone(),
 841                        llm_api_token,
 842                        CompletionBody {
 843                            thread_id,
 844                            prompt_id,
 845                            mode,
 846                            provider: zed_llm_client::LanguageModelProvider::OpenAi,
 847                            model: request.model.clone(),
 848                            provider_request: serde_json::to_value(&request)?,
 849                        },
 850                    )
 851                    .await?;
 852
 853                    let mut mapper = OpenAiEventMapper::new();
 854                    Ok((
 855                        map_cloud_completion_events(
 856                            Box::pin(response_lines(response, includes_queue_events)),
 857                            move |event| mapper.map_event(event),
 858                        ),
 859                        usage,
 860                    ))
 861                });
 862                async move {
 863                    let (stream, usage) = future.await?;
 864                    Ok((stream.boxed(), usage))
 865                }
 866                .boxed()
 867            }
 868            CloudModel::Google(model) => {
 869                let client = self.client.clone();
 870                let request = into_google(request, model.id().into());
 871                let llm_api_token = self.llm_api_token.clone();
 872                let future = self.request_limiter.stream_with_usage(async move {
 873                    let (response, usage, includes_queue_events) = Self::perform_llm_completion(
 874                        client.clone(),
 875                        llm_api_token,
 876                        CompletionBody {
 877                            thread_id,
 878                            prompt_id,
 879                            mode,
 880                            provider: zed_llm_client::LanguageModelProvider::Google,
 881                            model: request.model.clone(),
 882                            provider_request: serde_json::to_value(&request)?,
 883                        },
 884                    )
 885                    .await?;
 886                    let mut mapper = GoogleEventMapper::new();
 887                    Ok((
 888                        map_cloud_completion_events(
 889                            Box::pin(response_lines(response, includes_queue_events)),
 890                            move |event| mapper.map_event(event),
 891                        ),
 892                        usage,
 893                    ))
 894                });
 895                async move {
 896                    let (stream, usage) = future.await?;
 897                    Ok((stream.boxed(), usage))
 898                }
 899                .boxed()
 900            }
 901        }
 902    }
 903}
 904
 905#[derive(Serialize, Deserialize)]
 906#[serde(rename_all = "snake_case")]
 907pub enum CloudCompletionEvent<T> {
 908    Queue(QueueState),
 909    Event(T),
 910}
 911
 912fn map_cloud_completion_events<T, F>(
 913    stream: Pin<Box<dyn Stream<Item = Result<CloudCompletionEvent<T>>> + Send>>,
 914    mut map_callback: F,
 915) -> BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
 916where
 917    T: DeserializeOwned + 'static,
 918    F: FnMut(T) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
 919        + Send
 920        + 'static,
 921{
 922    stream
 923        .flat_map(move |event| {
 924            futures::stream::iter(match event {
 925                Err(error) => {
 926                    vec![Err(LanguageModelCompletionError::Other(error))]
 927                }
 928                Ok(CloudCompletionEvent::Queue(event)) => {
 929                    vec![Ok(LanguageModelCompletionEvent::QueueUpdate(event))]
 930                }
 931                Ok(CloudCompletionEvent::Event(event)) => map_callback(event),
 932            })
 933        })
 934        .boxed()
 935}
 936
 937fn response_lines<T: DeserializeOwned>(
 938    response: Response<AsyncBody>,
 939    includes_queue_events: bool,
 940) -> impl Stream<Item = Result<CloudCompletionEvent<T>>> {
 941    futures::stream::try_unfold(
 942        (String::new(), BufReader::new(response.into_body())),
 943        move |(mut line, mut body)| async move {
 944            match body.read_line(&mut line).await {
 945                Ok(0) => Ok(None),
 946                Ok(_) => {
 947                    let event = if includes_queue_events {
 948                        serde_json::from_str::<CloudCompletionEvent<T>>(&line)?
 949                    } else {
 950                        CloudCompletionEvent::Event(serde_json::from_str::<T>(&line)?)
 951                    };
 952
 953                    line.clear();
 954                    Ok(Some((event, (line, body))))
 955                }
 956                Err(e) => Err(e.into()),
 957            }
 958        },
 959    )
 960}
 961
 962struct ConfigurationView {
 963    state: gpui::Entity<State>,
 964}
 965
 966impl ConfigurationView {
 967    fn authenticate(&mut self, cx: &mut Context<Self>) {
 968        self.state.update(cx, |state, cx| {
 969            state.authenticate(cx).detach_and_log_err(cx);
 970        });
 971        cx.notify();
 972    }
 973}
 974
 975impl Render for ConfigurationView {
 976    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 977        const ZED_AI_URL: &str = "https://zed.dev/ai";
 978
 979        let is_connected = !self.state.read(cx).is_signed_out();
 980        let plan = self.state.read(cx).user_store.read(cx).current_plan();
 981        let has_accepted_terms = self.state.read(cx).has_accepted_terms_of_service(cx);
 982
 983        let is_pro = plan == Some(proto::Plan::ZedPro);
 984        let subscription_text = Label::new(if is_pro {
 985            "You have full access to Zed's hosted LLMs, which include models from Anthropic, OpenAI, and Google. They come with faster speeds and higher limits through Zed Pro."
 986        } else {
 987            "You have basic access to models from Anthropic through the Zed AI Free plan."
 988        });
 989        let manage_subscription_button = if is_pro {
 990            Some(
 991                h_flex().child(
 992                    Button::new("manage_settings", "Manage Subscription")
 993                        .style(ButtonStyle::Tinted(TintColor::Accent))
 994                        .on_click(
 995                            cx.listener(|_, _, _, cx| cx.open_url(&zed_urls::account_url(cx))),
 996                        ),
 997                ),
 998            )
 999        } else if cx.has_flag::<ZedProFeatureFlag>() {
1000            Some(
1001                h_flex()
1002                    .gap_2()
1003                    .child(
1004                        Button::new("learn_more", "Learn more")
1005                            .style(ButtonStyle::Subtle)
1006                            .on_click(cx.listener(|_, _, _, cx| cx.open_url(ZED_AI_URL))),
1007                    )
1008                    .child(
1009                        Button::new("upgrade", "Upgrade")
1010                            .style(ButtonStyle::Subtle)
1011                            .color(Color::Accent)
1012                            .on_click(
1013                                cx.listener(|_, _, _, cx| cx.open_url(&zed_urls::account_url(cx))),
1014                            ),
1015                    ),
1016            )
1017        } else {
1018            None
1019        };
1020
1021        if is_connected {
1022            v_flex()
1023                .gap_3()
1024                .w_full()
1025                .children(render_accept_terms(
1026                    self.state.clone(),
1027                    LanguageModelProviderTosView::Configuration,
1028                    cx,
1029                ))
1030                .when(has_accepted_terms, |this| {
1031                    this.child(subscription_text)
1032                        .children(manage_subscription_button)
1033                })
1034        } else {
1035            v_flex()
1036                .gap_2()
1037                .child(Label::new("Use Zed AI to access hosted language models."))
1038                .child(
1039                    Button::new("sign_in", "Sign In")
1040                        .icon_color(Color::Muted)
1041                        .icon(IconName::Github)
1042                        .icon_position(IconPosition::Start)
1043                        .on_click(cx.listener(move |this, _, _, cx| this.authenticate(cx))),
1044                )
1045        }
1046    }
1047}