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