use api_huggingface::
{
Client,
environment::HuggingFaceEnvironmentImpl,
cache::{ Cache, CacheConfig },
components::input::InferenceParameters,
secret::Secret,
};
use std::io::{ self, Write as IoWrite };
use core::time::Duration;
fn normalize_query( query : &str ) -> String
{
query.trim().to_lowercase()
}
#[ tokio::main ]
async fn main() -> Result< (), Box< dyn std::error::Error > >
{
println!( "🤖 HuggingFace Cached Interactive Chat" );
println!( "======================================\n" );
let api_key = Secret::load_from_env( "HUGGINGFACE_API_KEY" )?;
let env = HuggingFaceEnvironmentImpl::build( api_key, None )?;
let client = Client::build( env )?;
let cache_config = CacheConfig
{
max_entries : 100,
default_ttl : Some( Duration::from_secs( 300 ) ), };
let cache : Cache< String, String > = Cache::new( cache_config );
let params = InferenceParameters::new()
.with_temperature( 0.7 )
.with_max_new_tokens( 200 );
let model = "moonshotai/Kimi-K2-Instruct-0905:groq";
println!( "ℹ️ Cache configured : 100 entries max, 5-minute TTL" );
println!( "ℹ️ Model : {model}" );
println!( "\n💡 Commands:" );
println!( " /stats - Show cache statistics" );
println!( " /clear - Clear cache" );
println!( " /exit - Exit chat\n" );
loop
{
print!( "You : " );
io::stdout().flush()?;
let mut user_input = String::new();
io::stdin().read_line( &mut user_input )?;
let user_input = user_input.trim();
if user_input.is_empty()
{
continue;
}
match user_input
{
"/exit" | "/quit" =>
{
println!( "\n👋 Goodbye!" );
break;
}
"/stats" =>
{
let stats = cache.stats().await;
println!( "\n📊 Cache Statistics:" );
println!( " Total requests : {}", stats.total_requests() );
println!( " Cache hits : {}", stats.hits );
println!( " Cache misses : {}", stats.misses );
println!( " Hit rate : {:.1}%", stats.hit_rate() * 100.0 );
println!( " Current entries : {}", stats.entries );
println!( " Evictions : {}\n", stats.evictions );
continue;
}
"/clear" =>
{
cache.clear().await;
println!( "✅ Cache cleared\n" );
continue;
}
_ => {}
}
let cache_key = normalize_query( user_input );
if let Some( cached_response ) = cache.get( &cache_key ).await
{
println!( "Assistant (cached): {cached_response}" );
let stats = cache.stats().await;
println!( "💾 Cache hit! Hit rate : {:.1}%\n", stats.hit_rate() * 100.0 );
continue;
}
print!( "Assistant : " );
io::stdout().flush()?;
match client.inference().create_with_parameters(
user_input,
model,
params.clone()
).await
{
Ok( response ) =>
{
let response_text = response.extract_text_or_default( "" );
println!( "{response_text}" );
cache.insert( cache_key, response_text, None ).await;
let stats = cache.stats().await;
println!( "🌐 API call made. Hit rate : {:.1}%\n", stats.hit_rate() * 100.0 );
}
Err( e ) =>
{
println!( "❌ Error : {e}\n" );
}
}
}
let final_stats = cache.stats().await;
println!( "\n📊 Final Cache Statistics:" );
println!( " Total requests : {}", final_stats.total_requests() );
println!( " Cache hits : {}", final_stats.hits );
println!( " Cache misses : {}", final_stats.misses );
println!( " Final hit rate : {:.1}%", final_stats.hit_rate() * 100.0 );
println!( " Entries cached : {}", final_stats.entries );
let api_calls_saved = final_stats.hits;
let estimated_savings = api_calls_saved as f64 * 0.0001; println!( " 💰 Estimated savings : ${estimated_savings:.4}\n" );
Ok( () )
}