cloud_llm_client.rs

  1use std::str::FromStr;
  2use std::sync::Arc;
  3
  4use anyhow::Context as _;
  5use serde::{Deserialize, Serialize};
  6use strum::{Display, EnumIter, EnumString};
  7use uuid::Uuid;
  8
  9/// The name of the header used to indicate which version of Zed the client is running.
 10pub const ZED_VERSION_HEADER_NAME: &str = "x-zed-version";
 11
 12/// The name of the header used to indicate when a request failed due to an
 13/// expired LLM token.
 14///
 15/// The client may use this as a signal to refresh the token.
 16pub const EXPIRED_LLM_TOKEN_HEADER_NAME: &str = "x-zed-expired-token";
 17
 18/// The name of the header used to indicate what plan the user is currently on.
 19pub const CURRENT_PLAN_HEADER_NAME: &str = "x-zed-plan";
 20
 21/// The name of the header used to indicate the usage limit for model requests.
 22pub const MODEL_REQUESTS_USAGE_LIMIT_HEADER_NAME: &str = "x-zed-model-requests-usage-limit";
 23
 24/// The name of the header used to indicate the usage amount for model requests.
 25pub const MODEL_REQUESTS_USAGE_AMOUNT_HEADER_NAME: &str = "x-zed-model-requests-usage-amount";
 26
 27/// The name of the header used to indicate the usage limit for edit predictions.
 28pub const EDIT_PREDICTIONS_USAGE_LIMIT_HEADER_NAME: &str = "x-zed-edit-predictions-usage-limit";
 29
 30/// The name of the header used to indicate the usage amount for edit predictions.
 31pub const EDIT_PREDICTIONS_USAGE_AMOUNT_HEADER_NAME: &str = "x-zed-edit-predictions-usage-amount";
 32
 33/// The name of the header used to indicate the resource for which the subscription limit has been reached.
 34pub const SUBSCRIPTION_LIMIT_RESOURCE_HEADER_NAME: &str = "x-zed-subscription-limit-resource";
 35
 36pub const MODEL_REQUESTS_RESOURCE_HEADER_VALUE: &str = "model_requests";
 37pub const EDIT_PREDICTIONS_RESOURCE_HEADER_VALUE: &str = "edit_predictions";
 38
 39/// The name of the header used to indicate that the maximum number of consecutive tool uses has been reached.
 40pub const TOOL_USE_LIMIT_REACHED_HEADER_NAME: &str = "x-zed-tool-use-limit-reached";
 41
 42/// The name of the header used to indicate the the minimum required Zed version.
 43///
 44/// This can be used to force a Zed upgrade in order to continue communicating
 45/// with the LLM service.
 46pub const MINIMUM_REQUIRED_VERSION_HEADER_NAME: &str = "x-zed-minimum-required-version";
 47
 48/// The name of the header used by the client to indicate to the server that it supports receiving status messages.
 49pub const CLIENT_SUPPORTS_STATUS_MESSAGES_HEADER_NAME: &str =
 50    "x-zed-client-supports-status-messages";
 51
 52/// The name of the header used by the server to indicate to the client that it supports sending status messages.
 53pub const SERVER_SUPPORTS_STATUS_MESSAGES_HEADER_NAME: &str =
 54    "x-zed-server-supports-status-messages";
 55
 56#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
 57#[serde(rename_all = "snake_case")]
 58pub enum UsageLimit {
 59    Limited(i32),
 60    Unlimited,
 61}
 62
 63impl FromStr for UsageLimit {
 64    type Err = anyhow::Error;
 65
 66    fn from_str(value: &str) -> Result<Self, Self::Err> {
 67        match value {
 68            "unlimited" => Ok(Self::Unlimited),
 69            limit => limit
 70                .parse::<i32>()
 71                .map(Self::Limited)
 72                .context("failed to parse limit"),
 73        }
 74    }
 75}
 76
 77#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
 78#[serde(rename_all = "snake_case")]
 79pub enum Plan {
 80    #[default]
 81    #[serde(alias = "Free")]
 82    ZedFree,
 83    #[serde(alias = "ZedPro")]
 84    ZedPro,
 85    #[serde(alias = "ZedProTrial")]
 86    ZedProTrial,
 87}
 88
 89impl Plan {
 90    pub fn as_str(&self) -> &'static str {
 91        match self {
 92            Plan::ZedFree => "zed_free",
 93            Plan::ZedPro => "zed_pro",
 94            Plan::ZedProTrial => "zed_pro_trial",
 95        }
 96    }
 97
 98    pub fn model_requests_limit(&self) -> UsageLimit {
 99        match self {
100            Plan::ZedPro => UsageLimit::Limited(500),
101            Plan::ZedProTrial => UsageLimit::Limited(150),
102            Plan::ZedFree => UsageLimit::Limited(50),
103        }
104    }
105
106    pub fn edit_predictions_limit(&self) -> UsageLimit {
107        match self {
108            Plan::ZedPro => UsageLimit::Unlimited,
109            Plan::ZedProTrial => UsageLimit::Unlimited,
110            Plan::ZedFree => UsageLimit::Limited(2_000),
111        }
112    }
113}
114
115impl FromStr for Plan {
116    type Err = anyhow::Error;
117
118    fn from_str(value: &str) -> Result<Self, Self::Err> {
119        match value {
120            "zed_free" => Ok(Plan::ZedFree),
121            "zed_pro" => Ok(Plan::ZedPro),
122            "zed_pro_trial" => Ok(Plan::ZedProTrial),
123            plan => Err(anyhow::anyhow!("invalid plan: {plan:?}")),
124        }
125    }
126}
127
128#[derive(
129    Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize, EnumString, EnumIter, Display,
130)]
131#[serde(rename_all = "snake_case")]
132#[strum(serialize_all = "snake_case")]
133pub enum LanguageModelProvider {
134    Anthropic,
135    OpenAi,
136    Google,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct PredictEditsBody {
141    #[serde(skip_serializing_if = "Option::is_none", default)]
142    pub outline: Option<String>,
143    pub input_events: String,
144    pub input_excerpt: String,
145    #[serde(skip_serializing_if = "Option::is_none", default)]
146    pub speculated_output: Option<String>,
147    /// Whether the user provided consent for sampling this interaction.
148    #[serde(default, alias = "data_collection_permission")]
149    pub can_collect_data: bool,
150    #[serde(skip_serializing_if = "Option::is_none", default)]
151    pub diagnostic_groups: Option<Vec<(String, serde_json::Value)>>,
152}
153
154#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct PredictEditsResponse {
156    pub request_id: Uuid,
157    pub output_excerpt: String,
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct AcceptEditPredictionBody {
162    pub request_id: Uuid,
163}
164
165#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
166#[serde(rename_all = "snake_case")]
167pub enum CompletionMode {
168    Normal,
169    Max,
170}
171
172#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
173#[serde(rename_all = "snake_case")]
174pub enum CompletionIntent {
175    UserPrompt,
176    ToolResults,
177    ThreadSummarization,
178    ThreadContextSummarization,
179    CreateFile,
180    EditFile,
181    InlineAssist,
182    TerminalInlineAssist,
183    GenerateGitCommitMessage,
184}
185
186#[derive(Debug, Serialize, Deserialize)]
187pub struct CompletionBody {
188    #[serde(skip_serializing_if = "Option::is_none", default)]
189    pub thread_id: Option<String>,
190    #[serde(skip_serializing_if = "Option::is_none", default)]
191    pub prompt_id: Option<String>,
192    #[serde(skip_serializing_if = "Option::is_none", default)]
193    pub intent: Option<CompletionIntent>,
194    #[serde(skip_serializing_if = "Option::is_none", default)]
195    pub mode: Option<CompletionMode>,
196    pub provider: LanguageModelProvider,
197    pub model: String,
198    pub provider_request: serde_json::Value,
199}
200
201#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
202#[serde(rename_all = "snake_case")]
203pub enum CompletionRequestStatus {
204    Queued {
205        position: usize,
206    },
207    Started,
208    Failed {
209        code: String,
210        message: String,
211        request_id: Uuid,
212        /// Retry duration in seconds.
213        retry_after: Option<f64>,
214    },
215    UsageUpdated {
216        amount: usize,
217        limit: UsageLimit,
218    },
219    ToolUseLimitReached,
220}
221
222#[derive(Serialize, Deserialize)]
223#[serde(rename_all = "snake_case")]
224pub enum CompletionEvent<T> {
225    Status(CompletionRequestStatus),
226    Event(T),
227}
228
229impl<T> CompletionEvent<T> {
230    pub fn into_status(self) -> Option<CompletionRequestStatus> {
231        match self {
232            Self::Status(status) => Some(status),
233            Self::Event(_) => None,
234        }
235    }
236
237    pub fn into_event(self) -> Option<T> {
238        match self {
239            Self::Event(event) => Some(event),
240            Self::Status(_) => None,
241        }
242    }
243}
244
245#[derive(Serialize, Deserialize)]
246pub struct WebSearchBody {
247    pub query: String,
248}
249
250#[derive(Serialize, Deserialize, Clone)]
251pub struct WebSearchResponse {
252    pub results: Vec<WebSearchResult>,
253}
254
255#[derive(Serialize, Deserialize, Clone)]
256pub struct WebSearchResult {
257    pub title: String,
258    pub url: String,
259    pub text: String,
260}
261
262#[derive(Serialize, Deserialize)]
263pub struct CountTokensBody {
264    pub provider: LanguageModelProvider,
265    pub model: String,
266    pub provider_request: serde_json::Value,
267}
268
269#[derive(Serialize, Deserialize)]
270pub struct CountTokensResponse {
271    pub tokens: usize,
272}
273
274#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
275pub struct LanguageModelId(pub Arc<str>);
276
277impl std::fmt::Display for LanguageModelId {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        write!(f, "{}", self.0)
280    }
281}
282
283#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
284pub struct LanguageModel {
285    pub provider: LanguageModelProvider,
286    pub id: LanguageModelId,
287    pub display_name: String,
288    pub max_token_count: usize,
289    pub max_token_count_in_max_mode: Option<usize>,
290    pub max_output_tokens: usize,
291    pub supports_tools: bool,
292    pub supports_images: bool,
293    pub supports_thinking: bool,
294    pub supports_max_mode: bool,
295}
296
297#[derive(Debug, Serialize, Deserialize)]
298pub struct ListModelsResponse {
299    pub models: Vec<LanguageModel>,
300    pub default_model: LanguageModelId,
301    pub default_fast_model: LanguageModelId,
302    pub recommended_models: Vec<LanguageModelId>,
303}
304
305#[derive(Debug, Serialize, Deserialize)]
306pub struct GetSubscriptionResponse {
307    pub plan: Plan,
308    pub usage: Option<CurrentUsage>,
309}
310
311#[derive(Debug, PartialEq, Serialize, Deserialize)]
312pub struct CurrentUsage {
313    pub model_requests: UsageData,
314    pub edit_predictions: UsageData,
315}
316
317#[derive(Debug, PartialEq, Serialize, Deserialize)]
318pub struct UsageData {
319    pub used: u32,
320    pub limit: UsageLimit,
321}
322
323#[cfg(test)]
324mod tests {
325    use pretty_assertions::assert_eq;
326    use serde_json::json;
327
328    use super::*;
329
330    #[test]
331    fn test_plan_deserialize_snake_case() {
332        let plan = serde_json::from_value::<Plan>(json!("zed_free")).unwrap();
333        assert_eq!(plan, Plan::ZedFree);
334
335        let plan = serde_json::from_value::<Plan>(json!("zed_pro")).unwrap();
336        assert_eq!(plan, Plan::ZedPro);
337
338        let plan = serde_json::from_value::<Plan>(json!("zed_pro_trial")).unwrap();
339        assert_eq!(plan, Plan::ZedProTrial);
340    }
341
342    #[test]
343    fn test_plan_deserialize_aliases() {
344        let plan = serde_json::from_value::<Plan>(json!("Free")).unwrap();
345        assert_eq!(plan, Plan::ZedFree);
346
347        let plan = serde_json::from_value::<Plan>(json!("ZedPro")).unwrap();
348        assert_eq!(plan, Plan::ZedPro);
349
350        let plan = serde_json::from_value::<Plan>(json!("ZedProTrial")).unwrap();
351        assert_eq!(plan, Plan::ZedProTrial);
352    }
353
354    #[test]
355    fn test_usage_limit_from_str() {
356        let limit = UsageLimit::from_str("unlimited").unwrap();
357        assert!(matches!(limit, UsageLimit::Unlimited));
358
359        let limit = UsageLimit::from_str(&0.to_string()).unwrap();
360        assert!(matches!(limit, UsageLimit::Limited(0)));
361
362        let limit = UsageLimit::from_str(&50.to_string()).unwrap();
363        assert!(matches!(limit, UsageLimit::Limited(50)));
364
365        for value in ["not_a_number", "50xyz"] {
366            let limit = UsageLimit::from_str(value);
367            assert!(limit.is_err());
368        }
369    }
370}