cloud.rs

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