use api_xai::{ CachedClient, Client, XaiEnvironmentImpl, Secret, ChatCompletionRequest, Message };
use std::io::{ self, Write };
#[ tokio::main ]
async fn main() -> Result< (), Box< dyn core::error::Error > >
{
let secret = Secret::load_with_fallbacks( "XAI_API_KEY" )?;
let env = XaiEnvironmentImpl::new( secret )?;
let client = Client::build( env )?;
let cached_client = CachedClient::new( client, 100 );
println!( "🚀 XAI Grok API - Interactive Chat (with caching)" );
println!( "================================================" );
println!( "Type 'exit' or 'quit' to end the conversation." );
println!( "Type 'clear' to reset conversation and cache." );
println!( "Type 'cache' to show cache statistics.\n" );
let mut messages : Vec< Message > = Vec::new();
loop
{
print!( "You : " );
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line( &mut input )?;
let input = input.trim();
match input.to_lowercase().as_str()
{
"exit" | "quit" =>
{
println!( "\n👋 Goodbye!" );
println!( " Final cache size : {} entries", cached_client.len() );
break;
}
"clear" =>
{
messages.clear();
cached_client.clear();
println!( "✨ Conversation history and cache cleared.\n" );
continue;
}
"cache" =>
{
println!( "📊 Cache Statistics:" );
println!( " Size : {} entries", cached_client.len() );
println!( " Empty : {}\n", cached_client.is_empty() );
continue;
}
"" => continue,
_ => {}
}
messages.push( Message::user( input ) );
let request = ChatCompletionRequest::former()
.model( "grok-2-1212".to_string() )
.messages( messages.clone() )
.max_tokens( 500u32 )
.form();
print!( "🤖 Assistant : " );
io::stdout().flush()?;
match cached_client.cached_create( request ).await
{
Ok( response ) =>
{
if let Some( choice ) = response.choices.first()
{
if let Some( ref content ) = choice.message.content
{
println!( "{content}\n" );
messages.push( choice.message.clone() );
println!( " [Tokens : {} prompt + {} completion = {} total]",
response.usage.prompt_tokens,
response.usage.completion_tokens,
response.usage.total_tokens
);
println!( " [Cache : {} entries]", cached_client.len() );
println!();
}
else
{
println!( "[No content in response]\n" );
}
}
else
{
println!( "[No choices in response]\n" );
}
}
Err( e ) =>
{
println!( "\n❌ Error : {e}\n" );
messages.pop();
}
}
}
Ok( () )
}