use reqwest::Client;
use super::{error::LlmError, request::ChatRequest, response::ChatResponse};
const OPENROUTER_BASE_URL: &str = "https://openrouter.ai/api/v1/chat/completions";
#[derive(Debug, Clone)]
pub struct LlmClientConfig {
pub api_key: String,
pub http_referer: Option<String>,
pub x_title: Option<String>,
}
impl LlmClientConfig {
pub fn new(api_key: impl Into<String>) -> Result<Self, LlmError> {
let api_key = api_key.into();
if api_key.is_empty() {
return Err(LlmError::MissingConfig("api_key must not be empty".into()));
}
Ok(Self {
api_key,
http_referer: None,
x_title: None,
})
}
pub fn from_env() -> Result<Self, LlmError> {
let key = std::env::var("OPENROUTER_API_KEY").unwrap_or_default();
Self::new(key)
}
pub fn with_referer(mut self, referer: impl Into<String>) -> Self {
self.http_referer = Some(referer.into());
self
}
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.x_title = Some(title.into());
self
}
}
#[derive(Debug, Clone)]
pub struct LlmClient {
http: Client,
config: LlmClientConfig,
}
impl LlmClient {
pub fn from_config(config: LlmClientConfig) -> Result<Self, LlmError> {
let http = Client::builder()
.use_rustls_tls()
.build()
.map_err(LlmError::Transport)?;
Ok(Self { http, config })
}
pub fn from_env() -> Result<Self, LlmError> {
Self::from_config(LlmClientConfig::from_env()?)
}
pub async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
let mut builder = self
.http
.post(OPENROUTER_BASE_URL)
.header("Authorization", format!("Bearer {}", self.config.api_key))
.header("Content-Type", "application/json");
if let Some(referer) = &self.config.http_referer {
builder = builder.header("HTTP-Referer", referer.as_str());
}
if let Some(title) = &self.config.x_title {
builder = builder.header("X-Title", title.as_str());
}
let resp = builder.json(req).send().await?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
return Err(LlmError::ApiError {
status: status.as_u16(),
body,
});
}
let body = resp.text().await?;
serde_json::from_str::<ChatResponse>(&body)
.map_err(|source| LlmError::Deserialise { source, body })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::llm::{ChatMessage, ChatRequest};
#[test]
fn client_config_rejects_empty_key() {
let err = LlmClientConfig::new("").unwrap_err();
assert!(
matches!(err, LlmError::MissingConfig(_)),
"expected MissingConfig, got: {err:?}"
);
}
#[test]
fn client_config_direct_construction() {
let cfg = LlmClientConfig::new("sk-or-test-key").expect("should succeed");
assert_eq!(cfg.api_key, "sk-or-test-key");
assert!(cfg.http_referer.is_none());
assert!(cfg.x_title.is_none());
}
#[test]
fn client_config_builder() {
let cfg = LlmClientConfig::new("sk-or-x")
.unwrap()
.with_referer("https://example.com")
.with_title("trusty-code");
assert_eq!(cfg.http_referer.as_deref(), Some("https://example.com"));
assert_eq!(cfg.x_title.as_deref(), Some("trusty-code"));
}
#[test]
fn client_config_from_env_missing() {
let prev = std::env::var("OPENROUTER_API_KEY").ok();
unsafe {
std::env::remove_var("OPENROUTER_API_KEY");
}
let result = LlmClientConfig::from_env();
if let Some(k) = prev {
unsafe { std::env::set_var("OPENROUTER_API_KEY", k) };
}
assert!(
result.is_err(),
"expected Err when OPENROUTER_API_KEY is unset"
);
}
#[test]
fn lm_client_from_config() {
let cfg = LlmClientConfig::new("sk-or-test").unwrap();
let client = LlmClient::from_config(cfg);
assert!(client.is_ok(), "expected Ok, got: {client:?}");
}
#[tokio::test]
#[ignore = "requires OPENROUTER_API_KEY; skipped in CI"]
async fn live_openrouter_call() {
let Ok(key) = std::env::var("OPENROUTER_API_KEY") else {
eprintln!("OPENROUTER_API_KEY not set — skipping live test");
return;
};
if key.is_empty() {
eprintln!("OPENROUTER_API_KEY is empty — skipping live test");
return;
}
let config = LlmClientConfig::new(key)
.unwrap()
.with_referer("https://github.com/bobmatnyc/trusty-tools")
.with_title("trusty-code-integration-test");
let client = LlmClient::from_config(config).expect("build client");
let req = ChatRequest {
model: "openai/gpt-4o-mini".into(),
messages: vec![
ChatMessage::system("You are a concise assistant."),
ChatMessage::user("Reply with exactly the word: pong"),
],
temperature: Some(0.0),
max_tokens: Some(16),
tools: None,
tool_choice: None,
usage: None,
};
let resp = client.chat(&req).await.expect("chat call succeeded");
let text = resp.first_text().expect("assistant produced text");
assert!(!text.is_empty(), "assistant text was empty");
let usage = resp.token_usage();
assert!(usage.prompt_tokens > 0, "prompt_tokens should be > 0");
assert!(
usage.completion_tokens > 0,
"completion_tokens should be > 0"
);
eprintln!("live test passed — text: {text:?}, usage: {usage:?}");
}
}