cloud.rs

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