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