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 future,
33 sync::{Arc, LazyLock},
34 time::Duration,
35};
36use strum::IntoEnumIterator;
37use ui::{TintColor, prelude::*};
38
39use crate::AllLanguageModelSettings;
40use crate::provider::anthropic::{count_anthropic_tokens, into_anthropic};
41use crate::provider::google::into_google;
42use crate::provider::open_ai::{count_open_ai_tokens, into_open_ai};
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 thread_fresh_start = matches!(view_kind, LanguageModelProviderTosView::ThreadFreshStart);
405 let thread_empty_state = matches!(view_kind, LanguageModelProviderTosView::ThreadtEmptyState);
406
407 let terms_button = Button::new("terms_of_service", "Terms of Service")
408 .style(ButtonStyle::Subtle)
409 .icon(IconName::ArrowUpRight)
410 .icon_color(Color::Muted)
411 .icon_size(IconSize::XSmall)
412 .when(thread_empty_state, |this| this.label_size(LabelSize::Small))
413 .on_click(move |_, _window, cx| cx.open_url("https://zed.dev/terms-of-service"));
414
415 let button_container = h_flex().child(
416 Button::new("accept_terms", "I accept the Terms of Service")
417 .when(!thread_empty_state, |this| {
418 this.full_width()
419 .style(ButtonStyle::Tinted(TintColor::Accent))
420 .icon(IconName::Check)
421 .icon_position(IconPosition::Start)
422 .icon_size(IconSize::Small)
423 })
424 .when(thread_empty_state, |this| {
425 this.style(ButtonStyle::Tinted(TintColor::Warning))
426 .label_size(LabelSize::Small)
427 })
428 .disabled(accept_terms_disabled)
429 .on_click({
430 let state = state.downgrade();
431 move |_, _window, cx| {
432 state
433 .update(cx, |state, cx| state.accept_terms_of_service(cx))
434 .ok();
435 }
436 }),
437 );
438
439 let form = if thread_empty_state {
440 h_flex()
441 .w_full()
442 .flex_wrap()
443 .justify_between()
444 .child(
445 h_flex()
446 .child(
447 Label::new("To start using Zed AI, please read and accept the")
448 .size(LabelSize::Small),
449 )
450 .child(terms_button),
451 )
452 .child(button_container)
453 } else {
454 v_flex()
455 .w_full()
456 .gap_2()
457 .child(
458 h_flex()
459 .flex_wrap()
460 .when(thread_fresh_start, |this| this.justify_center())
461 .child(Label::new(
462 "To start using Zed AI, please read and accept the",
463 ))
464 .child(terms_button),
465 )
466 .child({
467 match view_kind {
468 LanguageModelProviderTosView::PromptEditorPopup => {
469 button_container.w_full().justify_end()
470 }
471 LanguageModelProviderTosView::Configuration => {
472 button_container.w_full().justify_start()
473 }
474 LanguageModelProviderTosView::ThreadFreshStart => {
475 button_container.w_full().justify_center()
476 }
477 LanguageModelProviderTosView::ThreadtEmptyState => div().w_0(),
478 }
479 })
480 };
481
482 Some(form.into_any())
483}
484
485pub struct CloudLanguageModel {
486 id: LanguageModelId,
487 model: CloudModel,
488 llm_api_token: LlmApiToken,
489 client: Arc<Client>,
490 request_limiter: RateLimiter,
491}
492
493impl CloudLanguageModel {
494 const MAX_RETRIES: usize = 3;
495
496 async fn perform_llm_completion(
497 client: Arc<Client>,
498 llm_api_token: LlmApiToken,
499 body: PerformCompletionParams,
500 ) -> Result<Response<AsyncBody>> {
501 let http_client = &client.http_client();
502
503 let mut token = llm_api_token.acquire(&client).await?;
504 let mut retries_remaining = Self::MAX_RETRIES;
505 let mut retry_delay = Duration::from_secs(1);
506
507 loop {
508 let request_builder = http_client::Request::builder();
509 let request = request_builder
510 .method(Method::POST)
511 .uri(http_client.build_zed_llm_url("/completion", &[])?.as_ref())
512 .header("Content-Type", "application/json")
513 .header("Authorization", format!("Bearer {token}"))
514 .body(serde_json::to_string(&body)?.into())?;
515 let mut response = http_client.send(request).await?;
516 let status = response.status();
517 if status.is_success() {
518 return Ok(response);
519 } else if response
520 .headers()
521 .get(EXPIRED_LLM_TOKEN_HEADER_NAME)
522 .is_some()
523 {
524 retries_remaining -= 1;
525 token = llm_api_token.refresh(&client).await?;
526 } else if status == StatusCode::FORBIDDEN
527 && response
528 .headers()
529 .get(MAX_LLM_MONTHLY_SPEND_REACHED_HEADER_NAME)
530 .is_some()
531 {
532 return Err(anyhow!(MaxMonthlySpendReachedError));
533 } else if status.as_u16() >= 500 && status.as_u16() < 600 {
534 // If we encounter an error in the 500 range, retry after a delay.
535 // We've seen at least these in the wild from API providers:
536 // * 500 Internal Server Error
537 // * 502 Bad Gateway
538 // * 529 Service Overloaded
539
540 if retries_remaining == 0 {
541 let mut body = String::new();
542 response.body_mut().read_to_string(&mut body).await?;
543 return Err(anyhow!(
544 "cloud language model completion failed after {} retries with status {status}: {body}",
545 Self::MAX_RETRIES
546 ));
547 }
548
549 Timer::after(retry_delay).await;
550
551 retries_remaining -= 1;
552 retry_delay *= 2; // If it fails again, wait longer.
553 } else if status == StatusCode::PAYMENT_REQUIRED {
554 return Err(anyhow!(PaymentRequiredError));
555 } else {
556 let mut body = String::new();
557 response.body_mut().read_to_string(&mut body).await?;
558 return Err(anyhow!(
559 "cloud language model completion failed with status {status}: {body}",
560 ));
561 }
562 }
563 }
564}
565
566impl LanguageModel for CloudLanguageModel {
567 fn id(&self) -> LanguageModelId {
568 self.id.clone()
569 }
570
571 fn name(&self) -> LanguageModelName {
572 LanguageModelName::from(self.model.display_name().to_string())
573 }
574
575 fn icon(&self) -> Option<IconName> {
576 self.model.icon()
577 }
578
579 fn provider_id(&self) -> LanguageModelProviderId {
580 LanguageModelProviderId(ZED_CLOUD_PROVIDER_ID.into())
581 }
582
583 fn provider_name(&self) -> LanguageModelProviderName {
584 LanguageModelProviderName(PROVIDER_NAME.into())
585 }
586
587 fn supports_tools(&self) -> bool {
588 match self.model {
589 CloudModel::Anthropic(_) => true,
590 CloudModel::Google(_) => true,
591 CloudModel::OpenAi(_) => false,
592 }
593 }
594
595 fn telemetry_id(&self) -> String {
596 format!("zed.dev/{}", self.model.id())
597 }
598
599 fn availability(&self) -> LanguageModelAvailability {
600 self.model.availability()
601 }
602
603 fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
604 self.model.tool_input_format()
605 }
606
607 fn max_token_count(&self) -> usize {
608 self.model.max_token_count()
609 }
610
611 fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
612 match &self.model {
613 CloudModel::Anthropic(model) => {
614 model
615 .cache_configuration()
616 .map(|cache| LanguageModelCacheConfiguration {
617 max_cache_anchors: cache.max_cache_anchors,
618 should_speculate: cache.should_speculate,
619 min_total_token: cache.min_total_token,
620 })
621 }
622 CloudModel::OpenAi(_) | CloudModel::Google(_) => None,
623 }
624 }
625
626 fn count_tokens(
627 &self,
628 request: LanguageModelRequest,
629 cx: &App,
630 ) -> BoxFuture<'static, Result<usize>> {
631 match self.model.clone() {
632 CloudModel::Anthropic(_) => count_anthropic_tokens(request, cx),
633 CloudModel::OpenAi(model) => count_open_ai_tokens(request, model, cx),
634 CloudModel::Google(model) => {
635 let client = self.client.clone();
636 let request = into_google(request, model.id().into());
637 let request = google_ai::CountTokensRequest {
638 contents: request.contents,
639 };
640 async move {
641 let request = serde_json::to_string(&request)?;
642 let response = client
643 .request(proto::CountLanguageModelTokens {
644 provider: proto::LanguageModelProvider::Google as i32,
645 request,
646 })
647 .await?;
648 Ok(response.token_count as usize)
649 }
650 .boxed()
651 }
652 }
653 }
654
655 fn stream_completion(
656 &self,
657 request: LanguageModelRequest,
658 _cx: &AsyncApp,
659 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
660 match &self.model {
661 CloudModel::Anthropic(model) => {
662 let request = into_anthropic(
663 request,
664 model.request_id().into(),
665 model.default_temperature(),
666 model.max_output_tokens(),
667 model.mode(),
668 );
669 let client = self.client.clone();
670 let llm_api_token = self.llm_api_token.clone();
671 let future = self.request_limiter.stream(async move {
672 let response = Self::perform_llm_completion(
673 client.clone(),
674 llm_api_token,
675 PerformCompletionParams {
676 provider: client::LanguageModelProvider::Anthropic,
677 model: request.model.clone(),
678 provider_request: RawValue::from_string(serde_json::to_string(
679 &request,
680 )?)?,
681 },
682 )
683 .await?;
684 Ok(
685 crate::provider::anthropic::map_to_language_model_completion_events(
686 Box::pin(response_lines(response).map_err(AnthropicError::Other)),
687 ),
688 )
689 });
690 async move { Ok(future.await?.boxed()) }.boxed()
691 }
692 CloudModel::OpenAi(model) => {
693 let client = self.client.clone();
694 let request = into_open_ai(request, model.id().into(), model.max_output_tokens());
695 let llm_api_token = self.llm_api_token.clone();
696 let future = self.request_limiter.stream(async move {
697 let response = Self::perform_llm_completion(
698 client.clone(),
699 llm_api_token,
700 PerformCompletionParams {
701 provider: client::LanguageModelProvider::OpenAi,
702 model: request.model.clone(),
703 provider_request: RawValue::from_string(serde_json::to_string(
704 &request,
705 )?)?,
706 },
707 )
708 .await?;
709 Ok(open_ai::extract_text_from_events(response_lines(response)))
710 });
711 async move {
712 Ok(future
713 .await?
714 .map(|result| result.map(LanguageModelCompletionEvent::Text))
715 .boxed())
716 }
717 .boxed()
718 }
719 CloudModel::Google(model) => {
720 let client = self.client.clone();
721 let request = into_google(request, model.id().into());
722 let llm_api_token = self.llm_api_token.clone();
723 let future = self.request_limiter.stream(async move {
724 let response = Self::perform_llm_completion(
725 client.clone(),
726 llm_api_token,
727 PerformCompletionParams {
728 provider: client::LanguageModelProvider::Google,
729 model: request.model.clone(),
730 provider_request: RawValue::from_string(serde_json::to_string(
731 &request,
732 )?)?,
733 },
734 )
735 .await?;
736 Ok(
737 crate::provider::google::map_to_language_model_completion_events(Box::pin(
738 response_lines(response),
739 )),
740 )
741 });
742 async move { Ok(future.await?.boxed()) }.boxed()
743 }
744 }
745 }
746
747 fn use_any_tool(
748 &self,
749 request: LanguageModelRequest,
750 tool_name: String,
751 tool_description: String,
752 input_schema: serde_json::Value,
753 _cx: &AsyncApp,
754 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
755 let client = self.client.clone();
756 let llm_api_token = self.llm_api_token.clone();
757
758 match &self.model {
759 CloudModel::Anthropic(model) => {
760 let mut request = into_anthropic(
761 request,
762 model.tool_model_id().into(),
763 model.default_temperature(),
764 model.max_output_tokens(),
765 model.mode(),
766 );
767 request.tool_choice = Some(anthropic::ToolChoice::Tool {
768 name: tool_name.clone(),
769 });
770 request.tools = vec![anthropic::Tool {
771 name: tool_name.clone(),
772 description: tool_description,
773 input_schema,
774 }];
775
776 self.request_limiter
777 .run(async move {
778 let response = Self::perform_llm_completion(
779 client.clone(),
780 llm_api_token,
781 PerformCompletionParams {
782 provider: client::LanguageModelProvider::Anthropic,
783 model: request.model.clone(),
784 provider_request: RawValue::from_string(serde_json::to_string(
785 &request,
786 )?)?,
787 },
788 )
789 .await?;
790
791 Ok(anthropic::extract_tool_args_from_events(
792 tool_name,
793 Box::pin(response_lines(response)),
794 )
795 .await?
796 .boxed())
797 })
798 .boxed()
799 }
800 CloudModel::OpenAi(model) => {
801 let mut request =
802 into_open_ai(request, model.id().into(), model.max_output_tokens());
803 request.tool_choice = Some(open_ai::ToolChoice::Other(
804 open_ai::ToolDefinition::Function {
805 function: open_ai::FunctionDefinition {
806 name: tool_name.clone(),
807 description: None,
808 parameters: None,
809 },
810 },
811 ));
812 request.tools = vec![open_ai::ToolDefinition::Function {
813 function: open_ai::FunctionDefinition {
814 name: tool_name.clone(),
815 description: Some(tool_description),
816 parameters: Some(input_schema),
817 },
818 }];
819
820 self.request_limiter
821 .run(async move {
822 let response = Self::perform_llm_completion(
823 client.clone(),
824 llm_api_token,
825 PerformCompletionParams {
826 provider: client::LanguageModelProvider::OpenAi,
827 model: request.model.clone(),
828 provider_request: RawValue::from_string(serde_json::to_string(
829 &request,
830 )?)?,
831 },
832 )
833 .await?;
834
835 Ok(open_ai::extract_tool_args_from_events(
836 tool_name,
837 Box::pin(response_lines(response)),
838 )
839 .await?
840 .boxed())
841 })
842 .boxed()
843 }
844 CloudModel::Google(_) => {
845 future::ready(Err(anyhow!("tool use not implemented for Google AI"))).boxed()
846 }
847 }
848 }
849}
850
851fn response_lines<T: DeserializeOwned>(
852 response: Response<AsyncBody>,
853) -> impl Stream<Item = Result<T>> {
854 futures::stream::try_unfold(
855 (String::new(), BufReader::new(response.into_body())),
856 move |(mut line, mut body)| async {
857 match body.read_line(&mut line).await {
858 Ok(0) => Ok(None),
859 Ok(_) => {
860 let event: T = serde_json::from_str(&line)?;
861 line.clear();
862 Ok(Some((event, (line, body))))
863 }
864 Err(e) => Err(e.into()),
865 }
866 },
867 )
868}
869
870struct ConfigurationView {
871 state: gpui::Entity<State>,
872}
873
874impl ConfigurationView {
875 fn authenticate(&mut self, cx: &mut Context<Self>) {
876 self.state.update(cx, |state, cx| {
877 state.authenticate(cx).detach_and_log_err(cx);
878 });
879 cx.notify();
880 }
881}
882
883impl Render for ConfigurationView {
884 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
885 const ZED_AI_URL: &str = "https://zed.dev/ai";
886
887 let is_connected = !self.state.read(cx).is_signed_out();
888 let plan = self.state.read(cx).user_store.read(cx).current_plan();
889 let has_accepted_terms = self.state.read(cx).has_accepted_terms_of_service(cx);
890
891 let is_pro = plan == Some(proto::Plan::ZedPro);
892 let subscription_text = Label::new(if is_pro {
893 "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."
894 } else {
895 "You have basic access to models from Anthropic through the Zed AI Free plan."
896 });
897 let manage_subscription_button = if is_pro {
898 Some(
899 h_flex().child(
900 Button::new("manage_settings", "Manage Subscription")
901 .style(ButtonStyle::Tinted(TintColor::Accent))
902 .on_click(
903 cx.listener(|_, _, _, cx| cx.open_url(&zed_urls::account_url(cx))),
904 ),
905 ),
906 )
907 } else if cx.has_flag::<ZedPro>() {
908 Some(
909 h_flex()
910 .gap_2()
911 .child(
912 Button::new("learn_more", "Learn more")
913 .style(ButtonStyle::Subtle)
914 .on_click(cx.listener(|_, _, _, cx| cx.open_url(ZED_AI_URL))),
915 )
916 .child(
917 Button::new("upgrade", "Upgrade")
918 .style(ButtonStyle::Subtle)
919 .color(Color::Accent)
920 .on_click(
921 cx.listener(|_, _, _, cx| cx.open_url(&zed_urls::account_url(cx))),
922 ),
923 ),
924 )
925 } else {
926 None
927 };
928
929 if is_connected {
930 v_flex()
931 .gap_3()
932 .w_full()
933 .children(render_accept_terms(
934 self.state.clone(),
935 LanguageModelProviderTosView::Configuration,
936 cx,
937 ))
938 .when(has_accepted_terms, |this| {
939 this.child(subscription_text)
940 .children(manage_subscription_button)
941 })
942 } else {
943 v_flex()
944 .gap_2()
945 .child(Label::new("Use Zed AI to access hosted language models."))
946 .child(
947 Button::new("sign_in", "Sign In")
948 .icon_color(Color::Muted)
949 .icon(IconName::Github)
950 .icon_position(IconPosition::Start)
951 .on_click(cx.listener(move |this, _, _, cx| this.authenticate(cx))),
952 )
953 }
954 }
955}