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