api_xai 0.3.0

X.AI Grok API client for accessing large language models (LLMs).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
mod private
{
  //! Batch processing for multiple chat completion requests.
  //!
  //! This module provides client-side parallel request orchestration
  //! for processing multiple chat completion requests efficiently.
  //!
  //! # Design Decisions
  //!
  //! ## Why Client-Side Batch Processing?
  //!
  //! The XAI Grok API does not provide a native batch processing endpoint.
  //! Client-side batching offers:
  //!
  //! 1. **Parallelism**: Process multiple requests concurrently
  //! 2. **Throughput**: Higher total throughput than sequential processing
  //! 3. **Control**: Fine-grained control over concurrency limits
  //! 4. **Rate Limiting**: Respect API rate limits with semaphore
  //!
  //! ## Concurrency Control
  //!
  //! Uses `tokio::sync::Semaphore` to limit concurrent requests:
  //!
  //! - **Prevents Overload**: Avoids overwhelming the API
  //! - **Rate Limit Compliance**: Respects API rate limits
  //! - **Resource Management**: Prevents excessive memory usage
  //! - **Graceful Degradation**: Continues processing on individual failures
  //!
  //! ## Error Handling Strategy
  //!
  //! - **Partial Success**: Returns all results (success + failures)
  //! - **Non-Blocking**: One failure doesn't stop other requests
  //! - **Transparent**: Each result is individually inspected
  //!
  //! ## Alternatives Considered
  //!
  //! - **Sequential Processing**: Too slow for large batches
  //! - **Unbounded Parallelism**: Risk of rate limit violations
  //! - **External Batch API**: XAI doesn't provide this endpoint

  use crate::{ ChatCompletionRequest, ChatCompletionResponse, Client, XaiEnvironment, ClientApiAccessors };
  use crate::error::Result;
  use std::sync::Arc;

  #[ cfg( feature = "batch_operations" ) ]
  use tokio::sync::Semaphore;

  /// A client wrapper that supports batch processing of requests.
  ///
  /// Processes multiple chat completion requests in parallel with
  /// configurable concurrency limits.
  ///
  /// # Concurrency
  ///
  /// The `max_concurrent` parameter controls how many requests can
  /// be in-flight simultaneously. This helps:
  ///
  /// - Respect API rate limits
  /// - Control resource usage
  /// - Prevent overwhelming the API
  ///
  /// # Error Handling
  ///
  /// Failures are returned individually in the results vector.
  /// One request failing does not stop processing of others.
  ///
  /// # Examples
  ///
  /// ```no_run
  /// # #[ cfg( feature = "batch_operations") ]
  /// # {
  /// use api_xai::{ BatchProcessor, Client, Secret, XaiEnvironmentImpl, ChatCompletionRequest, Message };
  ///
  /// # async fn example() -> Result< (), Box< dyn std::error::Error > > {
  /// let secret = Secret::new( "xai-key".to_string() )?;
  /// let env = XaiEnvironmentImpl::new( secret )?;
  /// let client = Client::build( env )?;
  ///
  /// // Create batch processor (max 5 concurrent requests)
  /// let processor = BatchProcessor::new( client, 5 );
  ///
  /// // Prepare multiple requests
  /// let requests = vec!
  /// [
  ///   ChatCompletionRequest::former()
  ///     .model( "grok-2-1212".to_string() )
  ///     .messages( vec![ Message::user( "Hello!" ) ] )
  ///     .form(),
  ///   ChatCompletionRequest::former()
  ///     .model( "grok-2-1212".to_string() )
  ///     .messages( vec![ Message::user( "Goodbye!" ) ] )
  ///     .form(),
  /// ];
  ///
  /// // Process batch
  /// let results = processor.process_batch( requests ).await;
  ///
  /// // Inspect results
  /// for ( idx, result ) in results.iter().enumerate()
  /// {
  ///   match result
  ///   {
  ///     Ok( response ) => println!( "Request {}: Success", idx ),
  ///     Err( e ) => println!( "Request {}: Failed - {}", idx, e ),
  ///   }
  /// }
  /// # Ok( () )
  /// # }
  /// # }
  /// ```
  #[ cfg( feature = "batch_operations" ) ]
  #[ derive( Debug ) ]
  pub struct BatchProcessor< E >
  where
    E : XaiEnvironment + Send + Sync + 'static,
  {
    client : Arc< Client< E > >,
    max_concurrent : usize,
  }

  #[ cfg( feature = "batch_operations" ) ]
  impl< E > BatchProcessor< E >
  where
    E : XaiEnvironment + Send + Sync + 'static,
  {
    /// Creates a new batch processor.
    ///
    /// # Arguments
    ///
    /// * `client` - The XAI client to use for requests
    /// * `max_concurrent` - Maximum number of concurrent requests
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[ cfg( feature = "batch_operations") ]
    /// # {
    /// use api_xai::{ BatchProcessor, Client, Secret, XaiEnvironmentImpl };
    ///
    /// # async fn example() -> Result< (), Box< dyn std::error::Error > > {
    /// let secret = Secret::new( "xai-key".to_string() )?;
    /// let env = XaiEnvironmentImpl::new( secret )?;
    /// let client = Client::build( env )?;
    ///
    /// // Allow up to 10 concurrent requests
    /// let processor = BatchProcessor::new( client, 10 );
    /// # Ok( () )
    /// # }
    /// # }
    /// ```
    pub fn new( client : Client< E >, max_concurrent : usize ) -> Self
    {
      Self
      {
        client : Arc::new( client ),
        max_concurrent,
      }
    }

    /// Processes a batch of chat completion requests.
    ///
    /// Executes all requests in parallel (up to `max_concurrent` at a time)
    /// and returns results in the same order as input requests.
    ///
    /// # Arguments
    ///
    /// * `requests` - Vector of chat completion requests to process
    ///
    /// # Returns
    ///
    /// Vector of results (one per request, in same order).
    /// Successful requests return `Ok(ChatCompletionResponse)`,
    /// failed requests return `Err`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[ cfg( feature = "batch_operations") ]
    /// # {
    /// use api_xai::{ BatchProcessor, Client, Secret, XaiEnvironmentImpl, ChatCompletionRequest, Message };
    ///
    /// # async fn example() -> Result< (), Box< dyn std::error::Error > > {
    /// let secret = Secret::new( "xai-key".to_string() )?;
    /// let env = XaiEnvironmentImpl::new( secret )?;
    /// let client = Client::build( env )?;
    /// let processor = BatchProcessor::new( client, 5 );
    ///
    /// let requests = vec!
    /// [
    ///   ChatCompletionRequest::former()
    ///     .model( "grok-2-1212".to_string() )
    ///     .messages( vec![ Message::user( "Request 1" ) ] )
    ///     .form(),
    ///   ChatCompletionRequest::former()
    ///     .model( "grok-2-1212".to_string() )
    ///     .messages( vec![ Message::user( "Request 2" ) ] )
    ///     .form(),
    /// ];
    ///
    /// let results = processor.process_batch( requests ).await;
    ///
    /// let successes = results.iter().filter( | r | r.is_ok() ).count();
    /// println!( "Successful : {}/{}", successes, results.len() );
    /// # Ok( () )
    /// # }
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the semaphore is closed.
    pub async fn process_batch
    (
      &self,
      requests : Vec< ChatCompletionRequest >
    )
    -> Vec< Result< ChatCompletionResponse > >
    {
      let semaphore = Arc::new( Semaphore::new( self.max_concurrent ) );
      let mut handles = Vec::new();

      for request in requests
      {
        let client = Arc::clone( &self.client );
        let semaphore = Arc::clone( &semaphore );

        let handle = tokio::spawn
        (
          async move
          {
            // Acquire permit (blocks if max_concurrent reached)
            let _permit = semaphore.acquire().await.unwrap();

            // Execute request
            client.chat().create( request ).await
          }
        );

        handles.push( handle );
      }

      // Collect results in order
      let mut results = Vec::new();
      for handle in handles
      {
        match handle.await
        {
          Ok( result ) => results.push( result ),
          Err( e ) =>
          {
            // Task join error (very rare)
            results.push
            (
              Err
              (
                crate::error::XaiError::ApiError
                (
                  format!( "Task join error : {e}" )
                ).into()
              )
            );
          }
        }
      }

      results
    }

    /// Processes a batch with progress callback.
    ///
    /// Same as `process_batch` but calls a callback for each completed request,
    /// allowing progress tracking.
    ///
    /// # Arguments
    ///
    /// * `requests` - Vector of chat completion requests to process
    /// * `on_complete` - Callback invoked for each completed request
    ///
    /// # Returns
    ///
    /// Vector of results (one per request, in same order).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[ cfg( feature = "batch_operations") ]
    /// # {
    /// use api_xai::{ BatchProcessor, Client, Secret, XaiEnvironmentImpl, ChatCompletionRequest, Message };
    ///
    /// # async fn example() -> Result< (), Box< dyn std::error::Error > > {
    /// let secret = Secret::new( "xai-key".to_string() )?;
    /// let env = XaiEnvironmentImpl::new( secret )?;
    /// let client = Client::build( env )?;
    /// let processor = BatchProcessor::new( client, 5 );
    ///
    /// let requests = vec!
    /// [
    ///   ChatCompletionRequest::former()
    ///     .model( "grok-2-1212".to_string() )
    ///     .messages( vec![ Message::user( "Request 1" ) ] )
    ///     .form(),
    ///   ChatCompletionRequest::former()
    ///     .model( "grok-2-1212".to_string() )
    ///     .messages( vec![ Message::user( "Request 2" ) ] )
    ///     .form(),
    /// ];
    ///
    /// let total = requests.len();
    /// let results = processor.process_batch_with_progress
    /// (
    ///   requests,
    ///   move | idx, result |
    ///   {
    ///     println!
    ///     (
    ///       "Completed {}/{}: {}",
    ///       idx + 1,
    ///       total,
    ///       if result.is_ok() { "Success" } else { "Failed" }
    ///     );
    ///   }
    /// ).await;
    /// # Ok( () )
    /// # }
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the semaphore is closed.
    pub async fn process_batch_with_progress< F >
    (
      &self,
      requests : Vec< ChatCompletionRequest >,
      on_complete : F
    )
    -> Vec< Result< ChatCompletionResponse > >
    where
      F : Fn( usize, &Result< ChatCompletionResponse > ) + Send + Sync + 'static,
    {
      let semaphore = Arc::new( Semaphore::new( self.max_concurrent ) );
      let callback = Arc::new( on_complete );
      let mut handles = Vec::new();

      for ( idx, request ) in requests.into_iter().enumerate()
      {
        let client = Arc::clone( &self.client );
        let semaphore = Arc::clone( &semaphore );
        let callback = Arc::clone( &callback );

        let handle = tokio::spawn
        (
          async move
          {
            let _permit = semaphore.acquire().await.unwrap();
            let result = client.chat().create( request ).await;

            // Call progress callback
            callback( idx, &result );

            result
          }
        );

        handles.push( handle );
      }

      // Collect results
      let mut results = Vec::new();
      for handle in handles
      {
        match handle.await
        {
          Ok( result ) => results.push( result ),
          Err( e ) =>
          {
            results.push
            (
              Err
              (
                crate::error::XaiError::ApiError
                (
                  format!( "Task join error : {e}" )
                ).into()
              )
            );
          }
        }
      }

      results
    }
  }
}

#[ cfg( feature = "batch_operations" ) ]
crate::mod_interface!
{
  exposed use
  {
    BatchProcessor,
  };
}