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 telemetry_id(&self) -> String {
561 format!("zed.dev/{}", self.model.id())
562 }
563
564 fn availability(&self) -> LanguageModelAvailability {
565 self.model.availability()
566 }
567
568 fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
569 self.model.tool_input_format()
570 }
571
572 fn max_token_count(&self) -> usize {
573 self.model.max_token_count()
574 }
575
576 fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
577 match &self.model {
578 CloudModel::Anthropic(model) => {
579 model
580 .cache_configuration()
581 .map(|cache| LanguageModelCacheConfiguration {
582 max_cache_anchors: cache.max_cache_anchors,
583 should_speculate: cache.should_speculate,
584 min_total_token: cache.min_total_token,
585 })
586 }
587 CloudModel::OpenAi(_) | CloudModel::Google(_) => None,
588 }
589 }
590
591 fn count_tokens(
592 &self,
593 request: LanguageModelRequest,
594 cx: &App,
595 ) -> BoxFuture<'static, Result<usize>> {
596 match self.model.clone() {
597 CloudModel::Anthropic(_) => count_anthropic_tokens(request, cx),
598 CloudModel::OpenAi(model) => count_open_ai_tokens(request, model, cx),
599 CloudModel::Google(model) => {
600 let client = self.client.clone();
601 let request = into_google(request, model.id().into());
602 let request = google_ai::CountTokensRequest {
603 contents: request.contents,
604 };
605 async move {
606 let request = serde_json::to_string(&request)?;
607 let response = client
608 .request(proto::CountLanguageModelTokens {
609 provider: proto::LanguageModelProvider::Google as i32,
610 request,
611 })
612 .await?;
613 Ok(response.token_count as usize)
614 }
615 .boxed()
616 }
617 }
618 }
619
620 fn stream_completion(
621 &self,
622 request: LanguageModelRequest,
623 _cx: &AsyncApp,
624 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
625 match &self.model {
626 CloudModel::Anthropic(model) => {
627 let request = into_anthropic(
628 request,
629 model.request_id().into(),
630 model.default_temperature(),
631 model.max_output_tokens(),
632 model.mode(),
633 );
634 let client = self.client.clone();
635 let llm_api_token = self.llm_api_token.clone();
636 let future = self.request_limiter.stream(async move {
637 let response = Self::perform_llm_completion(
638 client.clone(),
639 llm_api_token,
640 PerformCompletionParams {
641 provider: client::LanguageModelProvider::Anthropic,
642 model: request.model.clone(),
643 provider_request: RawValue::from_string(serde_json::to_string(
644 &request,
645 )?)?,
646 },
647 )
648 .await?;
649 Ok(
650 crate::provider::anthropic::map_to_language_model_completion_events(
651 Box::pin(response_lines(response).map_err(AnthropicError::Other)),
652 ),
653 )
654 });
655 async move { Ok(future.await?.boxed()) }.boxed()
656 }
657 CloudModel::OpenAi(model) => {
658 let client = self.client.clone();
659 let request = into_open_ai(request, model.id().into(), model.max_output_tokens());
660 let llm_api_token = self.llm_api_token.clone();
661 let future = self.request_limiter.stream(async move {
662 let response = Self::perform_llm_completion(
663 client.clone(),
664 llm_api_token,
665 PerformCompletionParams {
666 provider: client::LanguageModelProvider::OpenAi,
667 model: request.model.clone(),
668 provider_request: RawValue::from_string(serde_json::to_string(
669 &request,
670 )?)?,
671 },
672 )
673 .await?;
674 Ok(open_ai::extract_text_from_events(response_lines(response)))
675 });
676 async move {
677 Ok(future
678 .await?
679 .map(|result| result.map(LanguageModelCompletionEvent::Text))
680 .boxed())
681 }
682 .boxed()
683 }
684 CloudModel::Google(model) => {
685 let client = self.client.clone();
686 let request = into_google(request, model.id().into());
687 let llm_api_token = self.llm_api_token.clone();
688 let future = self.request_limiter.stream(async move {
689 let response = Self::perform_llm_completion(
690 client.clone(),
691 llm_api_token,
692 PerformCompletionParams {
693 provider: client::LanguageModelProvider::Google,
694 model: request.model.clone(),
695 provider_request: RawValue::from_string(serde_json::to_string(
696 &request,
697 )?)?,
698 },
699 )
700 .await?;
701 Ok(
702 crate::provider::google::map_to_language_model_completion_events(Box::pin(
703 response_lines(response),
704 )),
705 )
706 });
707 async move { Ok(future.await?.boxed()) }.boxed()
708 }
709 }
710 }
711
712 fn use_any_tool(
713 &self,
714 request: LanguageModelRequest,
715 tool_name: String,
716 tool_description: String,
717 input_schema: serde_json::Value,
718 _cx: &AsyncApp,
719 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
720 let client = self.client.clone();
721 let llm_api_token = self.llm_api_token.clone();
722
723 match &self.model {
724 CloudModel::Anthropic(model) => {
725 let mut request = into_anthropic(
726 request,
727 model.tool_model_id().into(),
728 model.default_temperature(),
729 model.max_output_tokens(),
730 model.mode(),
731 );
732 request.tool_choice = Some(anthropic::ToolChoice::Tool {
733 name: tool_name.clone(),
734 });
735 request.tools = vec![anthropic::Tool {
736 name: tool_name.clone(),
737 description: tool_description,
738 input_schema,
739 }];
740
741 self.request_limiter
742 .run(async move {
743 let response = Self::perform_llm_completion(
744 client.clone(),
745 llm_api_token,
746 PerformCompletionParams {
747 provider: client::LanguageModelProvider::Anthropic,
748 model: request.model.clone(),
749 provider_request: RawValue::from_string(serde_json::to_string(
750 &request,
751 )?)?,
752 },
753 )
754 .await?;
755
756 Ok(anthropic::extract_tool_args_from_events(
757 tool_name,
758 Box::pin(response_lines(response)),
759 )
760 .await?
761 .boxed())
762 })
763 .boxed()
764 }
765 CloudModel::OpenAi(model) => {
766 let mut request =
767 into_open_ai(request, model.id().into(), model.max_output_tokens());
768 request.tool_choice = Some(open_ai::ToolChoice::Other(
769 open_ai::ToolDefinition::Function {
770 function: open_ai::FunctionDefinition {
771 name: tool_name.clone(),
772 description: None,
773 parameters: None,
774 },
775 },
776 ));
777 request.tools = vec![open_ai::ToolDefinition::Function {
778 function: open_ai::FunctionDefinition {
779 name: tool_name.clone(),
780 description: Some(tool_description),
781 parameters: Some(input_schema),
782 },
783 }];
784
785 self.request_limiter
786 .run(async move {
787 let response = Self::perform_llm_completion(
788 client.clone(),
789 llm_api_token,
790 PerformCompletionParams {
791 provider: client::LanguageModelProvider::OpenAi,
792 model: request.model.clone(),
793 provider_request: RawValue::from_string(serde_json::to_string(
794 &request,
795 )?)?,
796 },
797 )
798 .await?;
799
800 Ok(open_ai::extract_tool_args_from_events(
801 tool_name,
802 Box::pin(response_lines(response)),
803 )
804 .await?
805 .boxed())
806 })
807 .boxed()
808 }
809 CloudModel::Google(_) => {
810 future::ready(Err(anyhow!("tool use not implemented for Google AI"))).boxed()
811 }
812 }
813 }
814}
815
816fn response_lines<T: DeserializeOwned>(
817 response: Response<AsyncBody>,
818) -> impl Stream<Item = Result<T>> {
819 futures::stream::try_unfold(
820 (String::new(), BufReader::new(response.into_body())),
821 move |(mut line, mut body)| async {
822 match body.read_line(&mut line).await {
823 Ok(0) => Ok(None),
824 Ok(_) => {
825 let event: T = serde_json::from_str(&line)?;
826 line.clear();
827 Ok(Some((event, (line, body))))
828 }
829 Err(e) => Err(e.into()),
830 }
831 },
832 )
833}
834
835struct ConfigurationView {
836 state: gpui::Entity<State>,
837}
838
839impl ConfigurationView {
840 fn authenticate(&mut self, cx: &mut Context<Self>) {
841 self.state.update(cx, |state, cx| {
842 state.authenticate(cx).detach_and_log_err(cx);
843 });
844 cx.notify();
845 }
846}
847
848impl Render for ConfigurationView {
849 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
850 const ZED_AI_URL: &str = "https://zed.dev/ai";
851
852 let is_connected = !self.state.read(cx).is_signed_out();
853 let plan = self.state.read(cx).user_store.read(cx).current_plan();
854 let has_accepted_terms = self.state.read(cx).has_accepted_terms_of_service(cx);
855
856 let is_pro = plan == Some(proto::Plan::ZedPro);
857 let subscription_text = Label::new(if is_pro {
858 "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."
859 } else {
860 "You have basic access to models from Anthropic through the Zed AI Free plan."
861 });
862 let manage_subscription_button = if is_pro {
863 Some(
864 h_flex().child(
865 Button::new("manage_settings", "Manage Subscription")
866 .style(ButtonStyle::Tinted(TintColor::Accent))
867 .on_click(
868 cx.listener(|_, _, _, cx| cx.open_url(&zed_urls::account_url(cx))),
869 ),
870 ),
871 )
872 } else if cx.has_flag::<ZedPro>() {
873 Some(
874 h_flex()
875 .gap_2()
876 .child(
877 Button::new("learn_more", "Learn more")
878 .style(ButtonStyle::Subtle)
879 .on_click(cx.listener(|_, _, _, cx| cx.open_url(ZED_AI_URL))),
880 )
881 .child(
882 Button::new("upgrade", "Upgrade")
883 .style(ButtonStyle::Subtle)
884 .color(Color::Accent)
885 .on_click(
886 cx.listener(|_, _, _, cx| cx.open_url(&zed_urls::account_url(cx))),
887 ),
888 ),
889 )
890 } else {
891 None
892 };
893
894 if is_connected {
895 v_flex()
896 .gap_3()
897 .w_full()
898 .children(render_accept_terms(
899 self.state.clone(),
900 LanguageModelProviderTosView::Configuration,
901 cx,
902 ))
903 .when(has_accepted_terms, |this| {
904 this.child(subscription_text)
905 .children(manage_subscription_button)
906 })
907 } else {
908 v_flex()
909 .gap_2()
910 .child(Label::new("Use Zed AI to access hosted language models."))
911 .child(
912 Button::new("sign_in", "Sign In")
913 .icon_color(Color::Muted)
914 .icon(IconName::Github)
915 .icon_position(IconPosition::Start)
916 .on_click(cx.listener(move |this, _, _, cx| this.authenticate(cx))),
917 )
918 }
919 }
920}