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