cloud.rs

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