Skip to main content

x_ai/
deferred_compl.rs

1// Copyright 2026 Mahmoud Harmouch.
2//
3// Licensed under the MIT license
4// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
5// option. This file may not be copied, modified, or distributed
6// except according to those terms.
7
8//! Reference: [docs/api-reference#deferred-completion](https://docs.x.ai/docs/api-reference#deferred-completion)
9//!
10//! Implements `GET /v1/chat/deferred-completion/{request_id}`.
11//! Returns `200 OK` with the completion when ready, or `202 Accepted` while still processing.
12
13use crate::chat_compl::ChatCompletionResponse;
14use crate::error::XaiError;
15use crate::error::check_for_model_error;
16use crate::traits::{ClientConfig, DeferredCompletionFetcher};
17use reqwest::Method;
18
19#[derive(Debug, Clone)]
20pub struct DeferredCompletionRequestBuilder<T: ClientConfig + Clone + Send + Sync> {
21    client: T,
22    request_id: String,
23}
24
25impl<T> DeferredCompletionRequestBuilder<T>
26where
27    T: ClientConfig + Clone + Send + Sync,
28{
29    pub fn new(client: T, request_id: impl Into<String>) -> Self {
30        Self {
31            client,
32            request_id: request_id.into(),
33        }
34    }
35
36    pub fn build(self) -> Result<String, XaiError> {
37        if self.request_id.trim().is_empty() {
38            return Err(XaiError::Validation(
39                "request_id cannot be empty".to_string(),
40            ));
41        }
42        Ok(self.request_id)
43    }
44}
45
46impl<T> DeferredCompletionFetcher for DeferredCompletionRequestBuilder<T>
47where
48    T: ClientConfig + Clone + Send + Sync,
49{
50    async fn fetch_deferred_completion(
51        &self,
52        request_id: &str,
53    ) -> Result<Option<ChatCompletionResponse>, XaiError> {
54        let url = format!("chat/deferred-completion/{}", request_id);
55        let response = self.client.request(Method::GET, &url)?.send().await?;
56
57        match response.status().as_u16() {
58            200 => {
59                let completion = response.json::<ChatCompletionResponse>().await?;
60                Ok(Some(completion))
61            }
62            202 => Ok(None),
63            _ => {
64                let error_body = response.text().await.unwrap_or_else(|_| "".to_string());
65                if let Some(model_error) = check_for_model_error(&error_body) {
66                    return Err(model_error);
67                }
68                Err(XaiError::Http(error_body))
69            }
70        }
71    }
72}
73// Copyright 2026 Mahmoud Harmouch.
74//
75// Licensed under the MIT license
76// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
77// option. This file may not be copied, modified, or distributed
78// except according to those terms.