use api_xai::{
Client, XaiEnvironmentImpl, Secret, ChatCompletionRequest,
Message, FailoverConfig, ClientApiAccessors
};
use core::time::Duration;
#[ tokio::main ]
async fn main() -> Result< (), Box< dyn core::error::Error > >
{
println!( "🔄 XAI Grok API - Failover Demo\n" );
println!( "================================\n" );
let secret = Secret::load_with_fallbacks( "XAI_API_KEY" )?;
let env = XaiEnvironmentImpl::new( secret )?;
let failover_config = FailoverConfig::default()
.with_max_failures( 3 ) .with_retry_after( Duration::from_secs( 60 ) ) .with_auto_rotate( true );
let client = Client::build( env )?
.with_failover_config(
vec![
"https://api.x.ai/v1/".to_string(),
],
failover_config
);
println!( "📊 Failover Configuration:" );
println!( " - Max failures before unhealthy : 3" );
println!( " - Retry delay : 60 seconds" );
println!( " - Auto-rotation : enabled\n" );
if let Some( ref manager ) = client.failover_manager
{
let health = manager.endpoint_health();
println!( "🏥 Endpoint Health Status:" );
for ( i, ( endpoint, status ) ) in health.iter().enumerate()
{
println!( " {}. {} - {:?}", i + 1, endpoint, status );
}
println!();
println!( "📍 Current endpoint : {}\n", manager.current_endpoint() );
}
println!( "📤 Sending test request..." );
let request = ChatCompletionRequest::former()
.model( "grok-2-1212".to_string() )
.messages( vec![
Message::user( "Explain failover in one sentence." )
] )
.max_tokens( 100u32 )
.form();
match client.chat().create( request ).await
{
Ok( response ) =>
{
println!( "✅ Request successful!\n" );
if let Some( choice ) = response.choices.first()
{
if let Some( ref content ) = choice.message.content
{
println!( "🤖 Response : {content}\n" );
}
}
if let Some( ref manager ) = client.failover_manager
{
let health = manager.endpoint_health();
println!( "🏥 Updated Health Status:" );
for ( i, ( endpoint, status ) ) in health.iter().enumerate()
{
println!( " {}. {} - {:?}", i + 1, endpoint, status );
}
}
}
Err( e ) =>
{
println!( "❌ Request failed : {e}\n" );
if let Some( ref manager ) = client.failover_manager
{
let health = manager.endpoint_health();
println!( "🏥 Health Status After Failure:" );
for ( i, ( endpoint, status ) ) in health.iter().enumerate()
{
println!( " {}. {} - {:?}", i + 1, endpoint, status );
}
}
}
}
println!( "\n💡 In Production:" );
println!( " - Configure multiple distinct backup endpoints" );
println!( " - Monitor endpoint health metrics" );
println!( " - Set appropriate failure thresholds" );
println!( " - Adjust retry delays based on SLAs" );
Ok( () )
}