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