api_openai 0.3.0

OpenAI's API 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
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
//! Region Management Module
//!
//! This module handles multi-region deployment, failover, and latency optimization
//! for enterprise `OpenAI` API usage.

use serde::{ Deserialize, Serialize };

/// Available `OpenAI` API regions
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash ) ]
pub enum Region
{
  /// US East 1 (Primary)
  UsEast1,
  /// US West 2
  UsWest2,
  /// Europe West 1
  EuropeWest1,
  /// Asia Pacific Southeast 1
  AsiaPacificSoutheast1,
  /// Custom region with endpoint URL
  Custom( String ),
}

impl core::fmt::Display for Region
{
  #[ inline ]
  fn fmt( &self, f : &mut core::fmt::Formatter< '_ > ) -> core::fmt::Result
  {
    match self
    {
      Region::UsEast1 => write!( f, "us-east-1" ),
      Region::UsWest2 => write!( f, "us-west-2" ),
      Region::EuropeWest1 => write!( f, "europe-west-1" ),
      Region::AsiaPacificSoutheast1 => write!( f, "asia-pacific-southeast-1" ),
      Region::Custom( url ) => write!( f, "custom:{url}" ),
    }
  }
}

/// Regional configuration and preferences
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct RegionConfig
{
  /// Primary region for requests
  pub primary_region : Region,
  /// Fallback regions in order of preference
  pub fallback_regions : Vec< Region >,
  /// Latency preferences
  pub latency_preferences : LatencyPreferences,
  /// Compliance requirements
  pub compliance_requirements : ComplianceRequirements,
  /// Enable automatic failover
  pub enable_automatic_failover : bool,
  /// Health check configuration
  pub health_check_config : HealthCheckConfig,
}

/// Latency optimization preferences
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct LatencyPreferences
{
  /// Maximum acceptable latency in milliseconds
  pub max_latency_ms : u32,
  /// Preferred latency in milliseconds
  pub preferred_latency_ms : u32,
  /// Enable latency-based routing
  pub enable_latency_routing : bool,
  /// Weight factor for latency vs other factors (0.0-1.0)
  pub latency_weight : f64,
}

/// Data compliance and regulatory requirements
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct ComplianceRequirements
{
  /// Require data residency in specific regions
  pub data_residency_regions : Vec< Region >,
  /// GDPR compliance required
  pub gdpr_required : bool,
  /// HIPAA compliance required
  pub hipaa_required : bool,
  /// SOC 2 compliance required
  pub soc2_required : bool,
  /// Additional compliance standards
  pub additional_standards : Vec< String >,
}

/// Health check configuration for regions
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct HealthCheckConfig
{
  /// Health check interval in seconds
  pub interval_seconds : u32,
  /// Timeout for health checks in seconds
  pub timeout_seconds : u32,
  /// Number of consecutive failures before marking unhealthy
  pub failure_threshold : u32,
  /// Number of consecutive successes before marking healthy
  pub success_threshold : u32,
  /// Enable detailed health metrics
  pub enable_detailed_metrics : bool,
}

/// Current status of a region
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct RegionStatus
{
  /// Region identifier
  pub region : Region,
  /// Whether region is currently healthy
  pub is_healthy : bool,
  /// Current latency in milliseconds
  pub latency_ms : Option< u32 >,
  /// Last health check timestamp
  pub last_check : u64,
  /// Error rate (0.0-1.0)
  pub error_rate : f64,
  /// Current load (0.0-1.0)
  pub current_load : f64,
  /// Additional status details
  pub details : String,
}

/// Comprehensive latency metrics across regions
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct LatencyMetrics
{
  /// Overall average latency in milliseconds
  pub avg_latency_ms : f64,
  /// Minimum recorded latency
  pub min_latency_ms : u32,
  /// Maximum recorded latency
  pub max_latency_ms : u32,
  /// Latency percentiles
  pub percentiles : LatencyPercentiles,
  /// Per-region latency breakdown
  pub region_metrics : Vec< RegionLatencyMetrics >,
}

/// Latency percentile measurements
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct LatencyPercentiles
{
  /// 50th percentile (median)
  pub p50 : f64,
  /// 90th percentile
  pub p90 : f64,
  /// 95th percentile
  pub p95 : f64,
  /// 99th percentile
  pub p99 : f64,
  /// 99.9th percentile
  pub p999 : f64,
}

/// Latency metrics for a specific region
#[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
pub struct RegionLatencyMetrics
{
  /// Region identifier
  pub region : Region,
  /// Average latency for this region
  pub avg_latency_ms : f64,
  /// Request count for this region
  pub request_count : u64,
  /// Success rate for this region
  pub success_rate : f64,
  /// Last updated timestamp
  pub last_updated : u64,
}

impl Default for LatencyPreferences
{
  #[ inline ]
  fn default() -> Self
  {
    Self
    {
      max_latency_ms : 5000,    // 5 seconds max
      preferred_latency_ms : 1000, // 1 second preferred
      enable_latency_routing : true,
      latency_weight : 0.7,     // 70% weight on latency
    }
  }
}

impl Default for ComplianceRequirements
{
  #[ inline ]
  fn default() -> Self
  {
    Self
    {
      data_residency_regions : Vec::new(),
      gdpr_required : false,
      hipaa_required : false,
      soc2_required : false,
      additional_standards : Vec::new(),
    }
  }
}

impl Default for HealthCheckConfig
{
  #[ inline ]
  fn default() -> Self
  {
    Self
    {
      interval_seconds : 30,
      timeout_seconds : 10,
      failure_threshold : 3,
      success_threshold : 2,
      enable_detailed_metrics : true,
    }
  }
}

impl Default for RegionConfig
{
  #[ inline ]
  fn default() -> Self
  {
    Self
    {
      primary_region : Region::UsEast1,
      fallback_regions : vec![ Region::UsWest2, Region::EuropeWest1 ],
      latency_preferences : LatencyPreferences::default(),
      compliance_requirements : ComplianceRequirements::default(),
      enable_automatic_failover : true,
      health_check_config : HealthCheckConfig::default(),
    }
  }
}

impl Region
{
  /// Get the base URL for this region
  #[ must_use ]
  #[ inline ]
  pub fn base_url( &self ) -> &str
  {
    match self
    {
      Region::UsEast1 => "https://api.openai.com",
      Region::UsWest2 => "https://api-west.openai.com",
      Region::EuropeWest1 => "https://api-eu.openai.com",
      Region::AsiaPacificSoutheast1 => "https://api-asia.openai.com",
      Region::Custom( url ) => url,
    }
  }

  /// Get the display name for this region
  #[ must_use ]
  #[ inline ]
  pub fn display_name( &self ) -> &str
  {
    match self
    {
      Region::UsEast1 => "US East 1",
      Region::UsWest2 => "US West 2",
      Region::EuropeWest1 => "Europe West 1",
      Region::AsiaPacificSoutheast1 => "Asia Pacific Southeast 1",
      Region::Custom( _ ) => "Custom Region",
    }
  }

  /// Check if region supports GDPR compliance
  #[ must_use ]
  #[ inline ]
  pub fn supports_gdpr( &self ) -> bool
  {
    matches!( self, Region::EuropeWest1 )
  }

  /// Get expected latency zone for region (for routing optimization)
  #[ must_use ]
  #[ inline ]
  pub fn latency_zone( &self ) -> &str
  {
    match self
    {
      Region::UsEast1 | Region::UsWest2 => "North America",
      Region::EuropeWest1 => "Europe",
      Region::AsiaPacificSoutheast1 => "Asia Pacific",
      Region::Custom( _ ) => "Custom",
    }
  }
}

impl RegionConfig
{
  /// Create new region config with primary region
  #[ must_use ]
  #[ inline ]
  pub fn with_primary_region( primary_region : Region ) -> Self
  {
    Self
    {
      primary_region,
      ..Self::default()
    }
  }

  /// Add fallback region
  #[ must_use ]
  #[ inline ]
  pub fn add_fallback_region( mut self, region : Region ) -> Self
  {
    if !self.fallback_regions.contains( &region ) && region != self.primary_region
    {
      self.fallback_regions.push( region );
    }
    self
  }

  /// Set maximum acceptable latency
  #[ must_use ]
  #[ inline ]
  pub fn with_max_latency( mut self, max_latency_ms : u32 ) -> Self
  {
    self.latency_preferences.max_latency_ms = max_latency_ms;
    self
  }

  /// Enable GDPR compliance
  #[ must_use ]
  #[ inline ]
  pub fn with_gdpr_compliance( mut self ) -> Self
  {
    self.compliance_requirements.gdpr_required = true;
    // Ensure only GDPR-compliant regions are used
    self.fallback_regions.retain( Region::supports_gdpr );
    if !self.primary_region.supports_gdpr()
    {
      self.primary_region = Region::EuropeWest1;
    }
    self
  }

  /// Add data residency requirement
  #[ must_use ]
  #[ inline ]
  pub fn with_data_residency( mut self, regions : Vec< Region > ) -> Self
  {
    self.compliance_requirements.data_residency_regions = regions;
    self
  }

  /// Get all usable regions based on compliance requirements
  #[ must_use ]
  #[ inline ]
  pub fn get_compliant_regions( &self ) -> Vec< Region >
  {
    let mut regions = vec![ self.primary_region.clone() ];
    regions.extend( self.fallback_regions.clone() );

    // Filter by data residency requirements
    if !self.compliance_requirements.data_residency_regions.is_empty()
    {
      regions.retain( | region |
        self.compliance_requirements.data_residency_regions.contains( region )
      );
    }

    // Filter by GDPR requirements
    if self.compliance_requirements.gdpr_required
    {
      regions.retain( Region::supports_gdpr );
    }

    regions
  }

  /// Select best region based on current metrics
  #[ must_use ]
  #[ inline ]
  pub fn select_optimal_region( &self, region_statuses : &[ RegionStatus ] ) -> Option< Region >
  {
    let compliant_regions = self.get_compliant_regions();
    let mut candidate_regions : Vec< _ > = region_statuses.iter()
      .filter( | status | compliant_regions.contains( &status.region ) && status.is_healthy )
      .collect();

    if candidate_regions.is_empty()
    {
      return None;
    }

    // Sort by scoring algorithm
    candidate_regions.sort_by( | a, b |
    {
      let score_a = self.calculate_region_score( a );
      let score_b = self.calculate_region_score( b );
      score_b.partial_cmp( &score_a ).unwrap_or( core::cmp::Ordering::Equal )
    } );

    Some( candidate_regions[ 0 ].region.clone() )
  }

  /// Calculate score for region selection (higher is better)
  fn calculate_region_score( &self, status : &RegionStatus ) -> f64
  {
    let mut score = 0.0;

    // Latency component (higher score for lower latency)
    if let Some( latency ) = status.latency_ms
    {
      let latency_score = if latency <= self.latency_preferences.preferred_latency_ms
      {
        1.0
      }
      else if latency <= self.latency_preferences.max_latency_ms
      {
        1.0 - f64::from( latency - self.latency_preferences.preferred_latency_ms )
          / f64::from( self.latency_preferences.max_latency_ms - self.latency_preferences.preferred_latency_ms )
      }
      else
      {
        0.0
      };
      score += latency_score * self.latency_preferences.latency_weight;
    }

    // Error rate component (higher score for lower error rate)
    let error_score = 1.0 - status.error_rate;
    score += error_score * 0.2;

    // Load component (higher score for lower load)
    let load_score = 1.0 - status.current_load;
    score += load_score * 0.1;

    score
  }
}

impl RegionStatus
{
  /// Create healthy region status
  ///
  /// # Panics
  /// Panics if the system time is before the Unix epoch.
  #[ must_use ]
  #[ inline ]
  pub fn healthy( region : Region, latency_ms : u32 ) -> Self
  {
    Self
    {
      region,
      is_healthy : true,
      latency_ms : Some( latency_ms ),
      last_check : std::time::SystemTime::now()
        .duration_since( std::time::UNIX_EPOCH )
        .unwrap()
        .as_secs(),
      error_rate : 0.0,
      current_load : 0.5, // Moderate load
      details : "Healthy".to_string(),
    }
  }

  /// Create unhealthy region status
  ///
  /// # Panics
  /// Panics if the system time is before the Unix epoch.
  #[ must_use ]
  #[ inline ]
  pub fn unhealthy( region : Region, reason : String ) -> Self
  {
    Self
    {
      region,
      is_healthy : false,
      latency_ms : None,
      last_check : std::time::SystemTime::now()
        .duration_since( std::time::UNIX_EPOCH )
        .unwrap()
        .as_secs(),
      error_rate : 1.0,
      current_load : 0.0,
      details : reason,
    }
  }
}

#[ cfg( test ) ]
mod tests
{
  use super::*;

  #[ test ]
  fn test_region_base_urls()
  {
    assert_eq!( Region::UsEast1.base_url(), "https://api.openai.com" );
    assert_eq!( Region::EuropeWest1.base_url(), "https://api-eu.openai.com" );
    assert_eq!( Region::Custom( "https://custom.com".to_string() ).base_url(), "https://custom.com" );
  }

  #[ test ]
  fn test_region_gdpr_support()
  {
    assert!( !Region::UsEast1.supports_gdpr() );
    assert!( Region::EuropeWest1.supports_gdpr() );
  }

  #[ test ]
  fn test_region_config_with_gdpr()
  {
    let config = RegionConfig::default().with_gdpr_compliance();
    assert!( config.compliance_requirements.gdpr_required );
    assert_eq!( config.primary_region, Region::EuropeWest1 );
  }

  #[ test ]
  fn test_compliant_regions_filtering()
  {
    let config = RegionConfig::default()
      .with_data_residency( vec![ Region::UsEast1, Region::UsWest2 ] );

    let compliant = config.get_compliant_regions();
    assert!( compliant.contains( &Region::UsEast1 ) );
    assert!( !compliant.contains( &Region::EuropeWest1 ) );
  }

  #[ test ]
  fn test_region_selection()
  {
    let config = RegionConfig::default();
    let statuses = vec![
      RegionStatus::healthy( Region::UsEast1, 100 ),
      RegionStatus::healthy( Region::UsWest2, 200 ),
      RegionStatus::unhealthy( Region::EuropeWest1, "Network issues".to_string() ),
    ];

    let selected = config.select_optimal_region( &statuses );
    assert_eq!( selected, Some( Region::UsEast1 ) ); // Should select lowest latency
  }

  #[ test ]
  fn test_region_config_builder()
  {
    let config = RegionConfig::with_primary_region( Region::EuropeWest1 )
      .add_fallback_region( Region::UsEast1 )
      .with_max_latency( 2000 );

    assert_eq!( config.primary_region, Region::EuropeWest1 );
    assert!( config.fallback_regions.contains( &Region::UsEast1 ) );
    assert_eq!( config.latency_preferences.max_latency_ms, 2000 );
  }
}