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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
mod private
{
//! Synchronous (blocking) API wrappers.
//!
//! Provides blocking wrappers around the async XAI API client using `tokio::runtime::Runtime`.
//!
//! # ⚠️ Design Warning
//!
//! **This contradicts Rust async-first design.** Use cases : legacy integration, simple scripts, learning.
//! Not recommended due to : performance overhead, thread blocking, poor composability with async code.
//!
//! ## Recommended Alternative
//!
//! Create application-level runtime and use `runtime.block_on()` for async calls:
//!
//! ```no_run
//! use api_xai::{ Client, Secret, XaiEnvironmentImpl, ChatCompletionRequest, Message, ClientApiAccessors };
//! use tokio::runtime::Runtime;
//!
//! # fn example() -> Result< (), Box< dyn std::error::Error > > {
//! let rt = Runtime::new()?;
//! let secret = Secret::new( "xai-key".to_string() )?;
//! let env = XaiEnvironmentImpl::new( secret )?;
//! let client = Client::build( env )?;
//! let request = ChatCompletionRequest::former()
//! .model( "grok-2-1212".to_string() )
//! .messages( vec![ Message::user( "Hello!" ) ] )
//! .form();
//! let response = rt.block_on( client.chat().create( request ) )?;
//! # Ok( () )
//! # }
//! ```
use crate::{ ChatCompletionRequest, ChatCompletionResponse, Client, XaiEnvironment, ClientApiAccessors };
use crate::error::Result;
#[ cfg( feature = "streaming" ) ]
use crate::ChatCompletionChunk;
#[ cfg( feature = "streaming" ) ]
use futures_core::Stream;
#[ cfg( feature = "streaming" ) ]
use std::pin::Pin;
#[ cfg( feature = "sync_api" ) ]
use tokio::runtime::Runtime;
/// A synchronous (blocking) wrapper around the async XAI client.
///
/// **⚠️ WARNING**: This contradicts Rust async-first design principles.
/// Use the async `Client` instead when possible.
///
/// # Performance Note
///
/// Each `SyncClient` owns a `tokio::runtime::Runtime`, which has
/// non-trivial overhead. Do not create many `SyncClient` instances.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( feature = "sync_api") ]
/// # {
/// use api_xai::{ SyncClient, Client, Secret, XaiEnvironmentImpl, ChatCompletionRequest, Message };
///
/// # 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 )?;
///
/// // Wrap in sync client
/// let sync_client = SyncClient::new( client )?;
///
/// let request = ChatCompletionRequest::former()
/// .model( "grok-2-1212".to_string() )
/// .messages( vec![ Message::user( "Hello!" ) ] )
/// .form();
///
/// // Blocking call
/// let response = sync_client.create( request )?;
/// println!( "Response : {:?}", response.choices[ 0 ].message.content );
/// # Ok( () )
/// # }
/// # }
/// ```
#[ cfg( feature = "sync_api" ) ]
#[ derive( Debug ) ]
pub struct SyncClient< E >
where
E : XaiEnvironment,
{
runtime : Runtime,
client : Client< E >,
}
#[ cfg( feature = "sync_api" ) ]
impl< E > SyncClient< E >
where
E : XaiEnvironment,
{
/// Creates a new synchronous client.
///
/// # Arguments
///
/// * `client` - The async client to wrap
///
/// # Errors
///
/// Returns error if the tokio runtime cannot be created.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( feature = "sync_api") ]
/// # {
/// use api_xai::{ SyncClient, Client, Secret, XaiEnvironmentImpl };
///
/// # 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 sync_client = SyncClient::new( client )?;
/// # Ok( () )
/// # }
/// # }
/// ```
pub fn new( client : Client< E > ) -> Result< Self >
{
let runtime = Runtime::new()
.map_err( | e | crate::error::XaiError::ApiError( format!( "Runtime error : {e}" ) ) )?;
Ok
(
Self
{
runtime,
client,
}
)
}
/// Creates a chat completion request (blocking).
///
/// Blocks the current thread until the API request completes.
///
/// # Arguments
///
/// * `request` - The chat completion request
///
/// # Returns
///
/// The chat completion response.
///
/// # Errors
///
/// Returns errors from the underlying API client.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( feature = "sync_api") ]
/// # {
/// use api_xai::{ SyncClient, Client, Secret, XaiEnvironmentImpl, ChatCompletionRequest, Message };
///
/// # 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 sync_client = SyncClient::new( client )?;
///
/// let request = ChatCompletionRequest::former()
/// .model( "grok-2-1212".to_string() )
/// .messages( vec![ Message::user( "Hello!" ) ] )
/// .form();
///
/// let response = sync_client.create( request )?;
/// # Ok( () )
/// # }
/// # }
/// ```
pub fn create( &self, request : ChatCompletionRequest ) -> Result< ChatCompletionResponse >
{
self.runtime.block_on( self.client.chat().create( request ) )
}
/// Creates a streaming chat completion request (blocking iterator).
///
/// Returns a blocking iterator over streaming chunks.
///
/// # Arguments
///
/// * `request` - The chat completion request
///
/// # Returns
///
/// A blocking iterator that yields `ChatCompletionChunk` items.
///
/// # Errors
///
/// Returns errors from the underlying API client.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( all( feature = "sync_api", feature = "streaming" ) ) ]
/// # {
/// use api_xai::{ SyncClient, Client, Secret, XaiEnvironmentImpl, ChatCompletionRequest, Message };
///
/// # 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 sync_client = SyncClient::new( client )?;
///
/// let request = ChatCompletionRequest::former()
/// .model( "grok-2-1212".to_string() )
/// .messages( vec![ Message::user( "Hello!" ) ] )
/// .form();
///
/// let mut stream = sync_client.create_stream( request )?;
/// for chunk in stream
/// {
/// let chunk = chunk?;
/// if let Some( choice ) = chunk.choices.first()
/// {
/// if let Some( ref content ) = choice.delta.content
/// {
/// print!( "{}", content );
/// }
/// }
/// }
/// # Ok( () )
/// # }
/// # }
/// ```
#[ cfg( feature = "streaming" ) ]
pub fn create_stream( &self, request : ChatCompletionRequest ) -> Result< SyncStreamIterator< E > >
{
let stream = self.runtime.block_on( self.client.chat().create_stream( request ) )?;
Ok
(
SyncStreamIterator
{
stream,
runtime : Runtime::new()
.map_err( | e | crate::error::XaiError::ApiError( format!( "Runtime error : {e}" ) ) )?,
_phantom : core::marker::PhantomData,
}
)
}
/// Lists available models (blocking).
///
/// # Returns
///
/// List models response.
///
/// # Errors
///
/// Returns errors from the underlying API client.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( feature = "sync_api") ]
/// # {
/// use api_xai::{ SyncClient, Client, Secret, XaiEnvironmentImpl };
///
/// # 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 sync_client = SyncClient::new( client )?;
///
/// let response = sync_client.list_models()?;
/// for model in response.data
/// {
/// println!( "Model : {}", model.id );
/// }
/// # Ok( () )
/// # }
/// # }
/// ```
pub fn list_models( &self ) -> Result< crate::components::ListModelsResponse >
{
self.runtime.block_on( self.client.models().list() )
}
/// Gets model information (blocking).
///
/// # Arguments
///
/// * `model_id` - The model ID to retrieve
///
/// # Returns
///
/// Model information.
///
/// # Errors
///
/// Returns errors from the underlying API client.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( feature = "sync_api") ]
/// # {
/// use api_xai::{ SyncClient, Client, Secret, XaiEnvironmentImpl };
///
/// # 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 sync_client = SyncClient::new( client )?;
///
/// let model = sync_client.get_model( "grok-2-1212" )?;
/// println!( "Model : {}", model.id );
/// # Ok( () )
/// # }
/// # }
/// ```
pub fn get_model( &self, model_id : &str ) -> Result< crate::components::Model >
{
self.runtime.block_on( self.client.models().get( model_id ) )
}
}
/// Synchronous iterator wrapper around async streaming.
///
/// Provides a blocking iterator over `ChatCompletionChunk` items
/// by wrapping the async stream in a dedicated tokio runtime.
#[ cfg( feature = "streaming" ) ]
pub struct SyncStreamIterator< E >
where
E : XaiEnvironment + Send + Sync + 'static,
{
stream : Pin< Box< dyn Stream< Item = Result< ChatCompletionChunk > > + Send + 'static > >,
runtime : Runtime,
_phantom : core::marker::PhantomData< E >,
}
#[ cfg( feature = "streaming" ) ]
impl< E > core::fmt::Debug for SyncStreamIterator< E >
where
E : XaiEnvironment + Send + Sync + 'static,
{
fn fmt( &self, f : &mut core::fmt::Formatter< '_ > ) -> core::fmt::Result
{
f.debug_struct( "SyncStreamIterator" )
.field( "runtime", &self.runtime )
.finish_non_exhaustive()
}
}
#[ cfg( feature = "streaming" ) ]
impl< E > Iterator for SyncStreamIterator< E >
where
E : XaiEnvironment + Send + Sync + 'static,
{
type Item = Result< ChatCompletionChunk >;
fn next( &mut self ) -> Option< Self::Item >
{
use futures_util::StreamExt;
self.runtime.block_on( self.stream.next() )
}
}
/// Synchronous wrapper for `count_tokens` (requires `count_tokens` feature).
///
/// Counts tokens in a text string for a specific model.
///
/// # Arguments
///
/// * `text` - The text to count tokens for
/// * `model` - The model name
///
/// # Returns
///
/// Number of tokens in the text.
///
/// # Errors
///
/// Returns `XaiError::InvalidModel` if the model is not supported.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( all(feature = "sync_api", feature = "count_tokens")) ]
/// # {
/// use api_xai::sync_count_tokens;
///
/// # fn example() -> Result< (), Box< dyn std::error::Error > > {
/// let count = sync_count_tokens( "Hello, world!", "grok-2-1212" )?;
/// println!( "Token count : {}", count );
/// # Ok( () )
/// # }
/// # }
/// ```
#[ cfg( all( feature = "sync_api", feature = "count_tokens" ) ) ]
pub fn sync_count_tokens( text : &str, model : &str ) -> Result< usize >
{
crate::count_tokens( text, model )
}
/// Synchronous wrapper for `count_tokens_for_request` (requires `count_tokens` feature).
///
/// Counts tokens in a chat completion request.
///
/// # Arguments
///
/// * `request` - The chat completion request
///
/// # Returns
///
/// Estimated total token count for the request.
///
/// # Errors
///
/// Returns `XaiError::InvalidModel` if the model is not supported.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( all(feature = "sync_api", feature = "count_tokens")) ]
/// # {
/// use api_xai::{ sync_count_tokens_for_request, ChatCompletionRequest, Message };
///
/// # fn example() -> Result< (), Box< dyn std::error::Error > > {
/// let request = ChatCompletionRequest::former()
/// .model( "grok-2-1212".to_string() )
/// .messages( vec![ Message::user( "Hello!" ) ] )
/// .form();
///
/// let count = sync_count_tokens_for_request( &request )?;
/// println!( "Total request tokens : {}", count );
/// # Ok( () )
/// # }
/// # }
/// ```
#[ cfg( all( feature = "sync_api", feature = "count_tokens" ) ) ]
pub fn sync_count_tokens_for_request( request : &ChatCompletionRequest ) -> Result< usize >
{
crate::count_tokens_for_request( request )
}
/// Synchronous wrapper for `validate_request_size` (requires `count_tokens` feature).
///
/// Validates that a request fits within the model's context window.
///
/// # Arguments
///
/// * `request` - The chat completion request
/// * `max_tokens` - The model's maximum context window size
///
/// # Returns
///
/// `Ok(())` if the request fits, error otherwise.
///
/// # Errors
///
/// Returns `XaiError::InvalidParameter` if the request exceeds the context window.
///
/// # Examples
///
/// ```no_run
/// # #[ cfg( all(feature = "sync_api", feature = "count_tokens")) ]
/// # {
/// use api_xai::{ sync_validate_request_size, ChatCompletionRequest, Message };
///
/// # fn example() -> Result< (), Box< dyn std::error::Error > > {
/// let request = ChatCompletionRequest::former()
/// .model( "grok-2-1212".to_string() )
/// .messages( vec![ Message::user( "Hello!" ) ] )
/// .form();
///
/// // Grok-3 has 131K context window
/// sync_validate_request_size( &request, 131072 )?;
/// # Ok( () )
/// # }
/// # }
/// ```
#[ cfg( all( feature = "sync_api", feature = "count_tokens" ) ) ]
pub fn sync_validate_request_size
(
request : &ChatCompletionRequest,
max_tokens : usize
)
-> Result< () >
{
crate::validate_request_size( request, max_tokens )
}
/// Synchronous wrapper for `cached_create` (requires `caching` feature).
///
/// **Note**: This is NOT recommended. Caching works better with async
/// because the cache can be shared across concurrent requests.
///
/// For sync usage, prefer using `SyncClient` with application-level caching.
#[ cfg( all( feature = "sync_api", feature = "caching" ) ) ]
#[ derive( Debug ) ]
pub struct SyncCachedClient< E >
where
E : XaiEnvironment,
{
runtime : Runtime,
cached_client : crate::CachedClient< E >,
}
#[ cfg( all( feature = "sync_api", feature = "caching" ) ) ]
impl< E > SyncCachedClient< E >
where
E : XaiEnvironment,
{
/// Creates a new synchronous cached client.
///
/// # Arguments
///
/// * `client` - The async client to wrap
/// * `capacity` - Maximum number of responses to cache
///
/// # Errors
///
/// Returns error if the tokio runtime cannot be created.
pub fn new( client : Client< E >, capacity : usize ) -> Result< Self >
{
let runtime = Runtime::new()
.map_err( | e | crate::error::XaiError::ApiError( format!( "Runtime error : {e}" ) ) )?;
let cached_client = crate::CachedClient::new( client, capacity );
Ok
(
Self
{
runtime,
cached_client,
}
)
}
/// Creates a chat completion request with caching (blocking).
///
/// # Arguments
///
/// * `request` - The chat completion request
///
/// # Returns
///
/// The chat completion response (cached or fresh).
///
/// # Errors
///
/// Returns errors from the underlying API client, including network errors,
/// API errors, authentication failures, and serialization errors.
pub fn create( &self, request : ChatCompletionRequest ) -> Result< ChatCompletionResponse >
{
self.runtime.block_on( self.cached_client.cached_create( request ) )
}
/// Clears all cached responses.
pub fn clear( &self )
{
self.cached_client.clear();
}
/// Returns the number of cached responses.
pub fn len( &self ) -> usize
{
self.cached_client.len()
}
/// Returns true if the cache is empty.
pub fn is_empty( &self ) -> bool
{
self.cached_client.is_empty()
}
}
}
#[ cfg( feature = "sync_api" ) ]
crate::mod_interface!
{
exposed use
{
SyncClient,
};
#[ cfg( all( feature = "sync_api", feature = "streaming" ) ) ]
exposed use
{
SyncStreamIterator,
};
#[ cfg( all( feature = "sync_api", feature = "count_tokens" ) ) ]
exposed use
{
sync_count_tokens,
sync_count_tokens_for_request,
sync_validate_request_size,
};
#[ cfg( all( feature = "sync_api", feature = "caching" ) ) ]
exposed use
{
SyncCachedClient,
};
}