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