use dotenvy::dotenv;
use openai4rs::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
dotenv().ok();
let mut client = OpenAI::from_env()?;
client.add_chat_interceptor(ChatSpecificInterceptor::new());
let model = "Qwen/Qwen3-235B-A22B-Instruct-2507";
let messages = vec![
system!("You are a helpful assistant."),
user!("Explain the benefits of using interceptors in API clients."),
];
let request = chat_request(model, &messages);
println!("Sending request with module-specific interceptors...");
let response = client.chat().create(request).await?;
if let Some(content) = response.content() {
println!("\nResponse:\n{}", content);
} else {
println!("\nNo content in response.");
}
Ok(())
}
#[derive(Debug)]
struct ChatSpecificInterceptor {
call_count: std::sync::atomic::AtomicUsize,
}
impl ChatSpecificInterceptor {
fn new() -> Self {
Self {
call_count: std::sync::atomic::AtomicUsize::new(0),
}
}
}
#[async_trait]
impl Interceptor for ChatSpecificInterceptor {
fn priority(&self) -> InterceptorPriority {
InterceptorPriority::Medium
}
async fn on_request(&self, request: Request) -> Result<Request, OpenAIError> {
let count = self
.call_count
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ 1;
println!(
"[CHAT] ChatSpecificInterceptor: Chat request #{} to {}",
count,
request.url()
);
let mut request = request;
request.headers_mut().insert(
"X-Chat-Request-ID".to_string(),
format!("chat-req-{}", count),
);
Ok(request)
}
async fn on_response(
&self,
response: reqwest::Response,
) -> Result<reqwest::Response, OpenAIError> {
println!(
"[CHAT] ChatSpecificInterceptor: Processing chat response with status {}",
response.status()
);
Ok(response)
}
}