trusty_code/llm/client.rs
1//! HTTP client for the OpenRouter `/v1/chat/completions` endpoint.
2//!
3//! Why: trusty-code needs a native LLM client that speaks the OpenAI
4//! chat-completions schema and works with any OpenRouter-hosted model slug —
5//! without pulling in the `async-openai` crate (which adds dependency weight
6//! and couples us to Anthropic's published API directly).
7//! What: `LlmClient` wraps a `reqwest::Client`, holds the API key and optional
8//! HTTP-Referer header, and exposes a single `chat` method that posts a
9//! `ChatRequest` and returns a `ChatResponse`. API-key injection happens at
10//! construction time so library code never reads from `std::env` itself.
11//! Test: Unit tests in `llm::types::tests` cover serialisation / deserialisation.
12//! The ignore-gated integration test `live_openrouter_call` in this file sends a
13//! real request (requires `OPENROUTER_API_KEY` in env).
14
15use reqwest::Client;
16
17use super::{error::LlmError, request::ChatRequest, response::ChatResponse};
18
19/// Base URL for OpenRouter's chat-completions endpoint.
20const OPENROUTER_BASE_URL: &str = "https://openrouter.ai/api/v1/chat/completions";
21
22/// Configuration for `LlmClient`.
23///
24/// Why: Separating config from the client struct makes it easy to construct the
25/// client from different sources (env, TOML config, tests) without duplicating
26/// the validation logic.
27/// What: Carries the API key (mandatory), an optional HTTP-Referer, and an
28/// optional X-Title header forwarded to OpenRouter for analytics.
29/// Test: `LlmClientConfig::from_env` unit-tested in `client_config_from_env`.
30#[derive(Debug, Clone)]
31pub struct LlmClientConfig {
32 /// OpenRouter API key (Bearer token).
33 pub api_key: String,
34
35 /// Optional HTTP-Referer sent to OpenRouter for request attribution.
36 pub http_referer: Option<String>,
37
38 /// Optional X-Title header sent to OpenRouter (appears in dashboards).
39 pub x_title: Option<String>,
40}
41
42impl LlmClientConfig {
43 /// Construct from an explicit API key string.
44 ///
45 /// Why: Tests and callers that already hold the key don't need an env read.
46 /// What: Validates that `api_key` is non-empty; returns `MissingConfig` if
47 /// it is.
48 /// Test: `client_config_direct_construction`.
49 pub fn new(api_key: impl Into<String>) -> Result<Self, LlmError> {
50 let api_key = api_key.into();
51 if api_key.is_empty() {
52 return Err(LlmError::MissingConfig("api_key must not be empty".into()));
53 }
54 Ok(Self {
55 api_key,
56 http_referer: None,
57 x_title: None,
58 })
59 }
60
61 /// Read the API key from the `OPENROUTER_API_KEY` environment variable.
62 ///
63 /// Why: Binary entry points call this once at startup; library helpers
64 /// never read env variables directly (convention from CLAUDE.md).
65 /// What: Reads `OPENROUTER_API_KEY`; returns `MissingConfig` if unset or
66 /// empty.
67 /// Test: `client_config_from_env_missing` (key absent → error).
68 pub fn from_env() -> Result<Self, LlmError> {
69 let key = std::env::var("OPENROUTER_API_KEY").unwrap_or_default();
70 Self::new(key)
71 }
72
73 /// Set the optional HTTP-Referer attribution header.
74 ///
75 /// Why: OpenRouter uses this for per-project analytics in their dashboard.
76 /// What: Builder-style setter; returns `self` for chaining.
77 /// Test: `client_config_builder`.
78 pub fn with_referer(mut self, referer: impl Into<String>) -> Self {
79 self.http_referer = Some(referer.into());
80 self
81 }
82
83 /// Set the optional X-Title attribution header.
84 ///
85 /// Why: Appears in OpenRouter's request logs as a human-readable label.
86 /// What: Builder-style setter; returns `self` for chaining.
87 /// Test: `client_config_builder`.
88 pub fn with_title(mut self, title: impl Into<String>) -> Self {
89 self.x_title = Some(title.into());
90 self
91 }
92}
93
94/// Async HTTP client for the OpenRouter chat-completions API.
95///
96/// Why: Centralises all HTTP mechanics (header injection, error handling,
97/// response parsing) so call sites only deal with `ChatRequest` / `ChatResponse`.
98/// What: Wraps a `reqwest::Client` and `LlmClientConfig`; exposes `chat` as the
99/// sole public method. The client is cheaply cloneable (`reqwest::Client` uses
100/// an `Arc` internally).
101/// Test: Serialisation/deserialisation unit tests live in `llm::types::tests`.
102/// The `#[ignore]`-gated `live_openrouter_call` test below validates the full
103/// HTTP round-trip.
104#[derive(Debug, Clone)]
105pub struct LlmClient {
106 http: Client,
107 config: LlmClientConfig,
108}
109
110impl LlmClient {
111 /// Construct an `LlmClient` from an explicit config.
112 ///
113 /// Why: Allows dependency injection in tests and in callers that manage
114 /// their own key source.
115 /// What: Builds a `reqwest::Client` with rustls TLS; returns an error if
116 /// the HTTP client cannot be constructed (extremely rare).
117 /// Test: `lm_client_from_config`.
118 pub fn from_config(config: LlmClientConfig) -> Result<Self, LlmError> {
119 let http = Client::builder()
120 .use_rustls_tls()
121 .build()
122 .map_err(LlmError::Transport)?;
123 Ok(Self { http, config })
124 }
125
126 /// Construct from the `OPENROUTER_API_KEY` environment variable.
127 ///
128 /// Why: Convenience entry point for binary code that reads config from env.
129 /// What: Delegates to `LlmClientConfig::from_env`, then `from_config`.
130 /// Test: Integration test `live_openrouter_call` uses this path.
131 pub fn from_env() -> Result<Self, LlmError> {
132 Self::from_config(LlmClientConfig::from_env()?)
133 }
134
135 /// POST a `ChatRequest` to OpenRouter and return the parsed `ChatResponse`.
136 ///
137 /// Why: Single-method surface keeps call sites simple and makes mocking
138 /// (for future test doubles) easy.
139 /// What: Serialises `req` to JSON, adds required OpenRouter headers
140 /// (`Authorization`, optional `HTTP-Referer`, optional `X-Title`), sends
141 /// the POST, and deserialises the response body. Non-2xx responses are
142 /// mapped to `LlmError::ApiError` with the raw body included.
143 /// Test: `live_openrouter_call` (#[ignore]) validates the happy path.
144 /// Unit tests in `types.rs` cover the serialisation/deserialisation paths.
145 pub async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
146 let mut builder = self
147 .http
148 .post(OPENROUTER_BASE_URL)
149 .header("Authorization", format!("Bearer {}", self.config.api_key))
150 .header("Content-Type", "application/json");
151
152 if let Some(referer) = &self.config.http_referer {
153 builder = builder.header("HTTP-Referer", referer.as_str());
154 }
155 if let Some(title) = &self.config.x_title {
156 builder = builder.header("X-Title", title.as_str());
157 }
158
159 let resp = builder.json(req).send().await?;
160
161 let status = resp.status();
162 if !status.is_success() {
163 let body = resp.text().await.unwrap_or_default();
164 return Err(LlmError::ApiError {
165 status: status.as_u16(),
166 body,
167 });
168 }
169
170 // Read the full body first so we can include it in deserialisation errors.
171 let body = resp.text().await?;
172 serde_json::from_str::<ChatResponse>(&body)
173 .map_err(|source| LlmError::Deserialise { source, body })
174 }
175}
176
177// ── Tests ─────────────────────────────────────────────────────────────────────
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182 use crate::llm::{ChatMessage, ChatRequest};
183
184 /// `LlmClientConfig::new` rejects an empty API key.
185 ///
186 /// Why: An empty key would produce a confusing 401 from the API; we want
187 /// to fail at construction time with a clear error.
188 /// What: Pass an empty string, assert `MissingConfig` error.
189 /// Test: this test.
190 #[test]
191 fn client_config_rejects_empty_key() {
192 let err = LlmClientConfig::new("").unwrap_err();
193 assert!(
194 matches!(err, LlmError::MissingConfig(_)),
195 "expected MissingConfig, got: {err:?}"
196 );
197 }
198
199 /// `LlmClientConfig::new` accepts a non-empty key.
200 ///
201 /// Why: Baseline happy-path for construction.
202 /// What: Pass a fake key, assert `Ok`.
203 /// Test: this test.
204 #[test]
205 fn client_config_direct_construction() {
206 let cfg = LlmClientConfig::new("sk-or-test-key").expect("should succeed");
207 assert_eq!(cfg.api_key, "sk-or-test-key");
208 assert!(cfg.http_referer.is_none());
209 assert!(cfg.x_title.is_none());
210 }
211
212 /// Builder methods chain correctly.
213 ///
214 /// Why: Verify the builder pattern sets optional fields.
215 /// What: Chain `with_referer` and `with_title`, assert both are set.
216 /// Test: this test.
217 #[test]
218 fn client_config_builder() {
219 let cfg = LlmClientConfig::new("sk-or-x")
220 .unwrap()
221 .with_referer("https://example.com")
222 .with_title("trusty-code");
223 assert_eq!(cfg.http_referer.as_deref(), Some("https://example.com"));
224 assert_eq!(cfg.x_title.as_deref(), Some("trusty-code"));
225 }
226
227 /// `LlmClientConfig::from_env` returns `MissingConfig` when the env var is absent.
228 ///
229 /// Why: Prevent silent failures when the key is not configured.
230 /// What: Remove the env var, call `from_env`, assert error.
231 /// Test: this test.
232 #[test]
233 fn client_config_from_env_missing() {
234 // Temporarily unset the key (may already be absent in CI).
235 let prev = std::env::var("OPENROUTER_API_KEY").ok();
236 unsafe {
237 std::env::remove_var("OPENROUTER_API_KEY");
238 }
239 let result = LlmClientConfig::from_env();
240 // Restore before asserting (so other tests are not affected even if this
241 // assertion panics).
242 if let Some(k) = prev {
243 unsafe { std::env::set_var("OPENROUTER_API_KEY", k) };
244 }
245 assert!(
246 result.is_err(),
247 "expected Err when OPENROUTER_API_KEY is unset"
248 );
249 }
250
251 /// `LlmClient::from_config` succeeds with a valid config.
252 ///
253 /// Why: Verifies the reqwest client builds without error.
254 /// What: Construct with a fake key, assert `Ok`.
255 /// Test: this test.
256 #[test]
257 fn lm_client_from_config() {
258 let cfg = LlmClientConfig::new("sk-or-test").unwrap();
259 let client = LlmClient::from_config(cfg);
260 assert!(client.is_ok(), "expected Ok, got: {client:?}");
261 }
262
263 /// Live integration test: send a trivial prompt to a cheap OpenRouter model.
264 ///
265 /// Why: End-to-end validation that `LlmClient::chat` produces a non-empty
266 /// assistant response and non-zero `TokenUsage`.
267 /// What: Read `OPENROUTER_API_KEY` from env; skip (not fail) if absent.
268 /// POST a single-turn prompt to `openai/gpt-4o-mini`; assert non-empty
269 /// `first_text()` and `usage.prompt_tokens > 0`.
270 /// Test: Run with `cargo test -p trusty-code -- --include-ignored`.
271 #[tokio::test]
272 #[ignore = "requires OPENROUTER_API_KEY; skipped in CI"]
273 async fn live_openrouter_call() {
274 // Skip gracefully when the key is not present (e.g. in a dev env that
275 // hasn't set it up yet) so the test doesn't block others.
276 let Ok(key) = std::env::var("OPENROUTER_API_KEY") else {
277 eprintln!("OPENROUTER_API_KEY not set — skipping live test");
278 return;
279 };
280 if key.is_empty() {
281 eprintln!("OPENROUTER_API_KEY is empty — skipping live test");
282 return;
283 }
284
285 let config = LlmClientConfig::new(key)
286 .unwrap()
287 .with_referer("https://github.com/bobmatnyc/trusty-tools")
288 .with_title("trusty-code-integration-test");
289
290 let client = LlmClient::from_config(config).expect("build client");
291
292 let req = ChatRequest {
293 model: "openai/gpt-4o-mini".into(),
294 messages: vec![
295 ChatMessage::system("You are a concise assistant."),
296 ChatMessage::user("Reply with exactly the word: pong"),
297 ],
298 temperature: Some(0.0),
299 max_tokens: Some(16),
300 tools: None,
301 tool_choice: None,
302 usage: None,
303 };
304
305 let resp = client.chat(&req).await.expect("chat call succeeded");
306
307 // Assert assistant text is non-empty.
308 let text = resp.first_text().expect("assistant produced text");
309 assert!(!text.is_empty(), "assistant text was empty");
310
311 // Assert usage is non-zero.
312 let usage = resp.token_usage();
313 assert!(usage.prompt_tokens > 0, "prompt_tokens should be > 0");
314 assert!(
315 usage.completion_tokens > 0,
316 "completion_tokens should be > 0"
317 );
318
319 eprintln!("live test passed — text: {text:?}, usage: {usage:?}");
320 }
321}