1use 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