1use std::fmt;
2use std::sync::Arc;
3
4use anyhow::Result;
5use client::Client;
6use gpui::{
7 App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, ReadGlobal as _,
8};
9use proto::{Plan, TypedEnvelope};
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12use smol::lock::{RwLock, RwLockUpgradableReadGuard, RwLockWriteGuard};
13use strum::EnumIter;
14use thiserror::Error;
15
16use crate::{LanguageModelAvailability, LanguageModelToolSchemaFormat};
17
18#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
19#[serde(tag = "provider", rename_all = "lowercase")]
20pub enum CloudModel {
21 Anthropic(anthropic::Model),
22 OpenAi(open_ai::Model),
23 Google(google_ai::Model),
24}
25
26#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, EnumIter)]
27pub enum ZedModel {
28 #[serde(rename = "Qwen/Qwen2-7B-Instruct")]
29 Qwen2_7bInstruct,
30}
31
32impl Default for CloudModel {
33 fn default() -> Self {
34 Self::Anthropic(anthropic::Model::default())
35 }
36}
37
38impl CloudModel {
39 pub fn id(&self) -> &str {
40 match self {
41 Self::Anthropic(model) => model.id(),
42 Self::OpenAi(model) => model.id(),
43 Self::Google(model) => model.id(),
44 }
45 }
46
47 pub fn display_name(&self) -> &str {
48 match self {
49 Self::Anthropic(model) => model.display_name(),
50 Self::OpenAi(model) => model.display_name(),
51 Self::Google(model) => model.display_name(),
52 }
53 }
54
55 pub fn max_token_count(&self) -> usize {
56 match self {
57 Self::Anthropic(model) => model.max_token_count(),
58 Self::OpenAi(model) => model.max_token_count(),
59 Self::Google(model) => model.max_token_count(),
60 }
61 }
62
63 /// Returns the availability of this model.
64 pub fn availability(&self) -> LanguageModelAvailability {
65 match self {
66 Self::Anthropic(model) => match model {
67 anthropic::Model::Claude3_5Sonnet
68 | anthropic::Model::Claude3_7Sonnet
69 | anthropic::Model::Claude3_7SonnetThinking => {
70 LanguageModelAvailability::RequiresPlan(Plan::Free)
71 }
72 anthropic::Model::Claude3Opus
73 | anthropic::Model::Claude3Sonnet
74 | anthropic::Model::Claude3Haiku
75 | anthropic::Model::Claude3_5Haiku
76 | anthropic::Model::Custom { .. } => {
77 LanguageModelAvailability::RequiresPlan(Plan::ZedPro)
78 }
79 },
80 Self::OpenAi(model) => match model {
81 open_ai::Model::ThreePointFiveTurbo
82 | open_ai::Model::Four
83 | open_ai::Model::FourTurbo
84 | open_ai::Model::FourOmni
85 | open_ai::Model::FourOmniMini
86 | open_ai::Model::FourPointOne
87 | open_ai::Model::FourPointOneMini
88 | open_ai::Model::FourPointOneNano
89 | open_ai::Model::O1Mini
90 | open_ai::Model::O1Preview
91 | open_ai::Model::O1
92 | open_ai::Model::O3Mini
93 | open_ai::Model::Custom { .. } => {
94 LanguageModelAvailability::RequiresPlan(Plan::ZedPro)
95 }
96 },
97 Self::Google(model) => match model {
98 google_ai::Model::Gemini15Pro
99 | google_ai::Model::Gemini15Flash
100 | google_ai::Model::Gemini20Pro
101 | google_ai::Model::Gemini20Flash
102 | google_ai::Model::Gemini20FlashThinking
103 | google_ai::Model::Gemini20FlashLite
104 | google_ai::Model::Gemini25ProExp0325
105 | google_ai::Model::Gemini25ProPreview0325
106 | google_ai::Model::Custom { .. } => {
107 LanguageModelAvailability::RequiresPlan(Plan::ZedPro)
108 }
109 },
110 }
111 }
112
113 pub fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
114 match self {
115 Self::Anthropic(_) | Self::OpenAi(_) => LanguageModelToolSchemaFormat::JsonSchema,
116 Self::Google(_) => LanguageModelToolSchemaFormat::JsonSchemaSubset,
117 }
118 }
119}
120
121#[derive(Error, Debug)]
122pub struct PaymentRequiredError;
123
124impl fmt::Display for PaymentRequiredError {
125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126 write!(
127 f,
128 "Payment required to use this language model. Please upgrade your account."
129 )
130 }
131}
132
133#[derive(Error, Debug)]
134pub struct MaxMonthlySpendReachedError;
135
136impl fmt::Display for MaxMonthlySpendReachedError {
137 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138 write!(
139 f,
140 "Maximum spending limit reached for this month. For more usage, increase your spending limit."
141 )
142 }
143}
144
145#[derive(Error, Debug)]
146pub struct ModelRequestLimitReachedError {
147 pub plan: Plan,
148}
149
150impl fmt::Display for ModelRequestLimitReachedError {
151 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152 let message = match self.plan {
153 Plan::Free => "Model request limit reached. Upgrade to Zed Pro for more requests.",
154 Plan::ZedPro => {
155 "Model request limit reached. Upgrade to usage-based billing for more requests."
156 }
157 Plan::ZedProTrial => {
158 "Model request limit reached. Upgrade to Zed Pro for more requests."
159 }
160 };
161
162 write!(f, "{message}")
163 }
164}
165
166#[derive(Clone, Default)]
167pub struct LlmApiToken(Arc<RwLock<Option<String>>>);
168
169impl LlmApiToken {
170 pub async fn acquire(&self, client: &Arc<Client>) -> Result<String> {
171 let lock = self.0.upgradable_read().await;
172 if let Some(token) = lock.as_ref() {
173 Ok(token.to_string())
174 } else {
175 Self::fetch(RwLockUpgradableReadGuard::upgrade(lock).await, client).await
176 }
177 }
178
179 pub async fn refresh(&self, client: &Arc<Client>) -> Result<String> {
180 Self::fetch(self.0.write().await, client).await
181 }
182
183 async fn fetch(
184 mut lock: RwLockWriteGuard<'_, Option<String>>,
185 client: &Arc<Client>,
186 ) -> Result<String> {
187 let response = client.request(proto::GetLlmToken {}).await?;
188 *lock = Some(response.token.clone());
189 Ok(response.token.clone())
190 }
191}
192
193struct GlobalRefreshLlmTokenListener(Entity<RefreshLlmTokenListener>);
194
195impl Global for GlobalRefreshLlmTokenListener {}
196
197pub struct RefreshLlmTokenEvent;
198
199pub struct RefreshLlmTokenListener {
200 _llm_token_subscription: client::Subscription,
201}
202
203impl EventEmitter<RefreshLlmTokenEvent> for RefreshLlmTokenListener {}
204
205impl RefreshLlmTokenListener {
206 pub fn register(client: Arc<Client>, cx: &mut App) {
207 let listener = cx.new(|cx| RefreshLlmTokenListener::new(client, cx));
208 cx.set_global(GlobalRefreshLlmTokenListener(listener));
209 }
210
211 pub fn global(cx: &App) -> Entity<Self> {
212 GlobalRefreshLlmTokenListener::global(cx).0.clone()
213 }
214
215 fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
216 Self {
217 _llm_token_subscription: client
218 .add_message_handler(cx.weak_entity(), Self::handle_refresh_llm_token),
219 }
220 }
221
222 async fn handle_refresh_llm_token(
223 this: Entity<Self>,
224 _: TypedEnvelope<proto::RefreshLlmToken>,
225 mut cx: AsyncApp,
226 ) -> Result<()> {
227 this.update(&mut cx, |_this, cx| cx.emit(RefreshLlmTokenEvent))
228 }
229}