cloud_llm_client.rs

  1pub mod predict_edits_v3;
  2
  3use std::str::FromStr;
  4use std::sync::Arc;
  5
  6use anyhow::Context as _;
  7use serde::{Deserialize, Serialize};
  8use strum::{Display, EnumIter, EnumString};
  9use uuid::Uuid;
 10
 11/// The name of the header used to indicate which version of Zed the client is running.
 12pub const ZED_VERSION_HEADER_NAME: &str = "x-zed-version";
 13
 14/// The name of the header used to indicate when a request failed due to an
 15/// expired LLM token.
 16///
 17/// The client may use this as a signal to refresh the token.
 18pub const EXPIRED_LLM_TOKEN_HEADER_NAME: &str = "x-zed-expired-token";
 19
 20/// The name of the header used to indicate when a request failed due to an outdated LLM token.
 21///
 22/// A token is considered "outdated" when we can't parse the claims (e.g., after adding a new required claim).
 23///
 24/// This is distinct from [`EXPIRED_LLM_TOKEN_HEADER_NAME`] which indicates the token's time-based validity has passed.
 25/// An outdated token means the token's structure is incompatible with the current server expectations.
 26pub const OUTDATED_LLM_TOKEN_HEADER_NAME: &str = "x-zed-outdated-token";
 27
 28/// The name of the header used to indicate the usage limit for edit predictions.
 29pub const EDIT_PREDICTIONS_USAGE_LIMIT_HEADER_NAME: &str = "x-zed-edit-predictions-usage-limit";
 30
 31/// The name of the header used to indicate the usage amount for edit predictions.
 32pub const EDIT_PREDICTIONS_USAGE_AMOUNT_HEADER_NAME: &str = "x-zed-edit-predictions-usage-amount";
 33
 34pub const EDIT_PREDICTIONS_RESOURCE_HEADER_VALUE: &str = "edit_predictions";
 35
 36/// The name of the header used to indicate the minimum required Zed version.
 37///
 38/// This can be used to force a Zed upgrade in order to continue communicating
 39/// with the LLM service.
 40pub const MINIMUM_REQUIRED_VERSION_HEADER_NAME: &str = "x-zed-minimum-required-version";
 41
 42/// The name of the header used by the client to indicate to the server that it supports receiving status messages.
 43pub const CLIENT_SUPPORTS_STATUS_MESSAGES_HEADER_NAME: &str =
 44    "x-zed-client-supports-status-messages";
 45
 46/// The name of the header used by the client to indicate to the server that it supports receiving a "stream_ended" request completion status.
 47pub const CLIENT_SUPPORTS_STATUS_STREAM_ENDED_HEADER_NAME: &str =
 48    "x-zed-client-supports-stream-ended-request-completion-status";
 49
 50/// The name of the header used by the server to indicate to the client that it supports sending status messages.
 51pub const SERVER_SUPPORTS_STATUS_MESSAGES_HEADER_NAME: &str =
 52    "x-zed-server-supports-status-messages";
 53
 54/// The name of the header used by the client to indicate that it supports receiving xAI models.
 55pub const CLIENT_SUPPORTS_X_AI_HEADER_NAME: &str = "x-zed-client-supports-x-ai";
 56
 57/// The maximum number of edit predictions that can be rejected per request.
 58pub const MAX_EDIT_PREDICTION_REJECTIONS_PER_REQUEST: usize = 100;
 59
 60#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
 61#[serde(rename_all = "snake_case")]
 62pub enum UsageLimit {
 63    Limited(i32),
 64    Unlimited,
 65}
 66
 67impl FromStr for UsageLimit {
 68    type Err = anyhow::Error;
 69
 70    fn from_str(value: &str) -> Result<Self, Self::Err> {
 71        match value {
 72            "unlimited" => Ok(Self::Unlimited),
 73            limit => limit
 74                .parse::<i32>()
 75                .map(Self::Limited)
 76                .context("failed to parse limit"),
 77        }
 78    }
 79}
 80
 81#[derive(
 82    Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize, EnumString, EnumIter, Display,
 83)]
 84#[serde(rename_all = "snake_case")]
 85#[strum(serialize_all = "snake_case")]
 86pub enum LanguageModelProvider {
 87    Anthropic,
 88    OpenAi,
 89    Google,
 90    XAi,
 91}
 92
 93#[derive(Debug, Clone, Serialize, Deserialize)]
 94pub struct PredictEditsBody {
 95    #[serde(skip_serializing_if = "Option::is_none", default)]
 96    pub outline: Option<String>,
 97    pub input_events: String,
 98    pub input_excerpt: String,
 99    #[serde(skip_serializing_if = "Option::is_none", default)]
100    pub speculated_output: Option<String>,
101    /// Whether the user provided consent for sampling this interaction.
102    #[serde(default, alias = "data_collection_permission")]
103    pub can_collect_data: bool,
104    #[serde(skip_serializing_if = "Option::is_none", default)]
105    pub diagnostic_groups: Option<Vec<(String, serde_json::Value)>>,
106    /// Info about the git repository state, only present when can_collect_data is true.
107    #[serde(skip_serializing_if = "Option::is_none", default)]
108    pub git_info: Option<PredictEditsGitInfo>,
109    /// The trigger for this request.
110    #[serde(default)]
111    pub trigger: PredictEditsRequestTrigger,
112}
113
114#[derive(Default, Debug, Clone, Copy, Serialize, Deserialize)]
115pub enum PredictEditsRequestTrigger {
116    Testing,
117    Diagnostics,
118    Cli,
119    #[default]
120    Other,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct PredictEditsGitInfo {
125    /// SHA of git HEAD commit at time of prediction.
126    #[serde(skip_serializing_if = "Option::is_none", default)]
127    pub head_sha: Option<String>,
128    /// URL of the remote called `origin`.
129    #[serde(skip_serializing_if = "Option::is_none", default)]
130    pub remote_origin_url: Option<String>,
131    /// URL of the remote called `upstream`.
132    #[serde(skip_serializing_if = "Option::is_none", default)]
133    pub remote_upstream_url: Option<String>,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct PredictEditsResponse {
138    pub request_id: String,
139    pub output_excerpt: String,
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct AcceptEditPredictionBody {
144    pub request_id: String,
145}
146
147#[derive(Debug, Clone, Deserialize)]
148pub struct RejectEditPredictionsBody {
149    pub rejections: Vec<EditPredictionRejection>,
150}
151
152#[derive(Debug, Clone, Serialize)]
153pub struct RejectEditPredictionsBodyRef<'a> {
154    pub rejections: &'a [EditPredictionRejection],
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
158pub struct EditPredictionRejection {
159    pub request_id: String,
160    #[serde(default)]
161    pub reason: EditPredictionRejectReason,
162    pub was_shown: bool,
163}
164
165#[derive(Default, Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
166pub enum EditPredictionRejectReason {
167    /// New requests were triggered before this one completed
168    Canceled,
169    /// No edits returned
170    Empty,
171    /// Edits returned, but none remained after interpolation
172    InterpolatedEmpty,
173    /// The new prediction was preferred over the current one
174    Replaced,
175    /// The current prediction was preferred over the new one
176    CurrentPreferred,
177    /// The current prediction was discarded
178    #[default]
179    Discarded,
180    /// The current prediction was explicitly rejected by the user
181    Rejected,
182}
183
184#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
185#[serde(rename_all = "snake_case")]
186pub enum CompletionIntent {
187    UserPrompt,
188    ToolResults,
189    ThreadSummarization,
190    ThreadContextSummarization,
191    CreateFile,
192    EditFile,
193    InlineAssist,
194    TerminalInlineAssist,
195    GenerateGitCommitMessage,
196}
197
198#[derive(Debug, Serialize, Deserialize)]
199pub struct CompletionBody {
200    #[serde(skip_serializing_if = "Option::is_none", default)]
201    pub thread_id: Option<String>,
202    #[serde(skip_serializing_if = "Option::is_none", default)]
203    pub prompt_id: Option<String>,
204    #[serde(skip_serializing_if = "Option::is_none", default)]
205    pub intent: Option<CompletionIntent>,
206    pub provider: LanguageModelProvider,
207    pub model: String,
208    pub provider_request: serde_json::Value,
209}
210
211#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
212#[serde(rename_all = "snake_case")]
213pub enum CompletionRequestStatus {
214    Queued {
215        position: usize,
216    },
217    Started,
218    Failed {
219        code: String,
220        message: String,
221        request_id: Uuid,
222        /// Retry duration in seconds.
223        retry_after: Option<f64>,
224    },
225    /// The cloud sends a StreamEnded message when the stream from the LLM provider finishes.
226    StreamEnded,
227    #[serde(other)]
228    Unknown,
229}
230
231#[derive(Serialize, Deserialize)]
232#[serde(rename_all = "snake_case")]
233pub enum CompletionEvent<T> {
234    Status(CompletionRequestStatus),
235    Event(T),
236}
237
238impl<T> CompletionEvent<T> {
239    pub fn into_status(self) -> Option<CompletionRequestStatus> {
240        match self {
241            Self::Status(status) => Some(status),
242            Self::Event(_) => None,
243        }
244    }
245
246    pub fn into_event(self) -> Option<T> {
247        match self {
248            Self::Event(event) => Some(event),
249            Self::Status(_) => None,
250        }
251    }
252}
253
254#[derive(Serialize, Deserialize)]
255pub struct WebSearchBody {
256    pub query: String,
257}
258
259#[derive(Debug, Serialize, Deserialize, Clone)]
260pub struct WebSearchResponse {
261    pub results: Vec<WebSearchResult>,
262}
263
264#[derive(Debug, Serialize, Deserialize, Clone)]
265pub struct WebSearchResult {
266    pub title: String,
267    pub url: String,
268    pub text: String,
269}
270
271#[derive(Serialize, Deserialize)]
272pub struct CountTokensBody {
273    pub provider: LanguageModelProvider,
274    pub model: String,
275    pub provider_request: serde_json::Value,
276}
277
278#[derive(Serialize, Deserialize)]
279pub struct CountTokensResponse {
280    pub tokens: usize,
281}
282
283#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
284pub struct LanguageModelId(pub Arc<str>);
285
286impl std::fmt::Display for LanguageModelId {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        write!(f, "{}", self.0)
289    }
290}
291
292#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
293pub struct LanguageModel {
294    pub provider: LanguageModelProvider,
295    pub id: LanguageModelId,
296    pub display_name: String,
297    #[serde(default)]
298    pub is_latest: bool,
299    pub max_token_count: usize,
300    pub max_token_count_in_max_mode: Option<usize>,
301    pub max_output_tokens: usize,
302    pub supports_tools: bool,
303    pub supports_images: bool,
304    pub supports_thinking: bool,
305    pub supported_effort_levels: Vec<SupportedEffortLevel>,
306    #[serde(default)]
307    pub supports_streaming_tools: bool,
308    /// Only used by OpenAI and xAI.
309    #[serde(default)]
310    pub supports_parallel_tool_calls: bool,
311}
312
313#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
314pub struct SupportedEffortLevel {
315    pub name: Arc<str>,
316    pub value: Arc<str>,
317    #[serde(default, skip_serializing_if = "Option::is_none")]
318    pub is_default: Option<bool>,
319}
320
321#[derive(Debug, Serialize, Deserialize)]
322pub struct ListModelsResponse {
323    pub models: Vec<LanguageModel>,
324    pub default_model: Option<LanguageModelId>,
325    pub default_fast_model: Option<LanguageModelId>,
326    pub recommended_models: Vec<LanguageModelId>,
327}
328
329#[derive(Debug, PartialEq, Serialize, Deserialize)]
330pub struct CurrentUsage {
331    pub edit_predictions: UsageData,
332}
333
334#[derive(Debug, PartialEq, Serialize, Deserialize)]
335pub struct UsageData {
336    pub used: u32,
337    pub limit: UsageLimit,
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    #[test]
345    fn test_usage_limit_from_str() {
346        let limit = UsageLimit::from_str("unlimited").unwrap();
347        assert!(matches!(limit, UsageLimit::Unlimited));
348
349        let limit = UsageLimit::from_str(&0.to_string()).unwrap();
350        assert!(matches!(limit, UsageLimit::Limited(0)));
351
352        let limit = UsageLimit::from_str(&50.to_string()).unwrap();
353        assert!(matches!(limit, UsageLimit::Limited(50)));
354
355        for value in ["not_a_number", "50xyz"] {
356            let limit = UsageLimit::from_str(value);
357            assert!(limit.is_err());
358        }
359    }
360}