trusty_code/provider/openrouter.rs
1//! OpenRouter provider — the default backend for trusty-code.
2//!
3//! Why: OpenRouter fronts dozens of model families (Qwen, DeepSeek, Gemma,
4//! OpenAI, Anthropic, Gemini, …) behind one OpenAI-compatible chat-completions
5//! schema. It is the right default for every slug that is not explicitly routed
6//! elsewhere (#1021).
7//! What: [`OpenRouterProvider`] implements [`Provider`] using OpenAI-style
8//! `tool_choice` JSON and the standard `usage` block. `supports_native_tools`
9//! is conservative: it returns `true` only for well-known native-capable model
10//! families and `false` otherwise (#1023 refines this per the strategy matrix).
11//! Test: `openrouter::tests::*`.
12
13use serde_json::{Value, json};
14
15use super::traits::{Provider, ToolChoice};
16use crate::llm::ChatResponse;
17use crate::perf::TokenUsage;
18
19/// The default OpenRouter-backed provider.
20///
21/// Why: Carries the model slug so `supports_native_tools` can decide per-model
22/// without the loop having to pass the slug on every call.
23/// What: Holds the model slug it was constructed for; the trait methods read it.
24/// Test: `openrouter::tests::*`.
25#[derive(Debug, Clone)]
26pub struct OpenRouterProvider {
27 /// The OpenRouter model slug this provider instance was built for.
28 slug: String,
29}
30
31impl OpenRouterProvider {
32 /// Construct an `OpenRouterProvider` for a given model slug.
33 ///
34 /// Why: `supports_native_tools` is slug-dependent, so the provider must
35 /// remember which model it routes for.
36 /// What: Stores the slug; all trait behaviour derives from it.
37 /// Test: `openrouter::tests::supports_native_tools_claude`.
38 pub fn new(slug: impl Into<String>) -> Self {
39 Self { slug: slug.into() }
40 }
41}
42
43/// Whether a model slug belongs to a family with native function-calling.
44///
45/// Why: Sending a `tools` array to a model that ignores it wastes tokens and
46/// produces malformed output; the loop needs a conservative yes/no per slug.
47/// What: Returns `true` when the slug names a known native-capable family
48/// (Claude, OpenAI GPT, Gemini); `false` otherwise. Matching is
49/// case-insensitive and substring-based so both bare slugs (`gpt-4o-mini`) and
50/// OpenRouter-namespaced slugs (`openai/gpt-4o-mini`) are recognised.
51/// Test: `openrouter::tests::supports_native_tools_*`.
52fn slug_supports_native_tools(slug: &str) -> bool {
53 let lower = slug.to_ascii_lowercase();
54 // Well-known native-tool-capable families. Conservative by design (#1023).
55 const NATIVE_MARKERS: [&str; 3] = ["claude-", "gpt-", "gemini-"];
56 NATIVE_MARKERS.iter().any(|m| lower.contains(m))
57}
58
59/// Whether a model slug belongs to the Anthropic family, routed via
60/// OpenRouter's OpenAI-compatible endpoint (#2156).
61///
62/// Why: OpenRouter's `cache_control` passthrough for the OpenAI-compat path
63/// is verified (via OpenRouter's prompt-caching docs and `block/goose`'s
64/// production OpenRouter provider, which gates the identical marker on this
65/// exact prefix check) to work for `anthropic/*` slugs. Other families either
66/// don't support Anthropic-style `cache_control` at all or the passthrough
67/// behaviour is unverified; conservative by design, matching
68/// `slug_supports_native_tools`'s posture.
69/// What: Returns `true` when the slug (OpenRouter-namespaced, e.g.
70/// `"anthropic/claude-sonnet-4-5"`) starts with `"anthropic/"`, case
71/// insensitively.
72/// Test: `openrouter::tests::supports_prompt_caching_anthropic_family`,
73/// `openrouter::tests::supports_prompt_caching_non_anthropic_families`.
74fn slug_supports_prompt_caching(slug: &str) -> bool {
75 slug.to_ascii_lowercase().starts_with("anthropic/")
76}
77
78impl Provider for OpenRouterProvider {
79 fn name(&self) -> &str {
80 "openrouter"
81 }
82
83 fn map_tool_choice(&self, choice: ToolChoice) -> Value {
84 match choice {
85 ToolChoice::None => json!("none"),
86 ToolChoice::Auto => json!("auto"),
87 ToolChoice::Required => json!("required"),
88 ToolChoice::Function(name) => json!({
89 "type": "function",
90 "function": { "name": name },
91 }),
92 }
93 }
94
95 fn extract_usage(&self, response: &ChatResponse) -> TokenUsage {
96 crate::llm::token_usage(response)
97 }
98
99 fn supports_native_tools(&self) -> bool {
100 slug_supports_native_tools(&self.slug)
101 }
102
103 fn supports_prompt_caching(&self) -> bool {
104 slug_supports_prompt_caching(&self.slug)
105 }
106
107 fn wants_detailed_usage(&self) -> bool {
108 // Unconditional for every OpenRouter-routed model (unlike prompt
109 // caching, which is verified only for `anthropic/*` slugs): detailed
110 // usage accounting is a wire-format directive OpenRouter honours
111 // uniformly across model families, and the response-side parsing in
112 // `UsageBlock` degrades gracefully (falls back to static pricing)
113 // when a particular upstream model/route doesn't populate `cost`.
114 true
115 }
116}
117
118// ── Tests ─────────────────────────────────────────────────────────────────────
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123
124 /// `name()` returns the stable `"openrouter"` identifier.
125 ///
126 /// Why: Telemetry keys off this string; a change would break log filters.
127 /// What: Construct a provider, assert `name() == "openrouter"`.
128 /// Test: this test.
129 #[test]
130 fn name_is_stable() {
131 let p = OpenRouterProvider::new("openai/gpt-4o-mini");
132 assert_eq!(p.name(), "openrouter");
133 }
134
135 /// `map_tool_choice` maps the three scalar policies to OpenAI strings.
136 ///
137 /// Why: The wire format requires exact `"none"`/`"auto"`/`"required"`
138 /// strings; a typo would be silently rejected by the API.
139 /// What: Map each scalar variant, assert the JSON string value.
140 /// Test: this test.
141 #[test]
142 fn map_tool_choice_scalars() {
143 let p = OpenRouterProvider::new("openai/gpt-4o-mini");
144 assert_eq!(p.map_tool_choice(ToolChoice::None), json!("none"));
145 assert_eq!(p.map_tool_choice(ToolChoice::Auto), json!("auto"));
146 assert_eq!(p.map_tool_choice(ToolChoice::Required), json!("required"));
147 }
148
149 /// `map_tool_choice(Function)` produces the OpenAI function-selector object.
150 ///
151 /// Why: Forcing a specific function requires the nested
152 /// `{type:function, function:{name}}` shape, not a bare string.
153 /// What: Map `Function("search")`, assert the object structure.
154 /// Test: this test.
155 #[test]
156 fn map_tool_choice_function() {
157 let p = OpenRouterProvider::new("openai/gpt-4o-mini");
158 let v = p.map_tool_choice(ToolChoice::Function("search_code".into()));
159 assert_eq!(v["type"], "function");
160 assert_eq!(v["function"]["name"], "search_code");
161 }
162
163 /// `extract_usage` maps the standard usage block into `TokenUsage`.
164 ///
165 /// Why: Cost accounting depends on correct field mapping; verify the
166 /// provider delegates to the canonical conversion.
167 /// What: Deserialise a response fixture with a usage block, extract usage,
168 /// assert each field.
169 /// Test: this test.
170 #[test]
171 fn extract_usage_maps_fields() {
172 let fixture = r#"{
173 "id": "gen-1",
174 "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
175 "usage": {"prompt_tokens": 12, "completion_tokens": 5, "total_tokens": 17,
176 "cache_read_input_tokens": 3, "cache_creation_input_tokens": 1}
177 }"#;
178 let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
179 let p = OpenRouterProvider::new("anthropic/claude-sonnet-4-5");
180 let usage = p.extract_usage(&resp);
181 assert_eq!(usage.prompt_tokens, 12);
182 assert_eq!(usage.completion_tokens, 5);
183 assert_eq!(usage.cache_read_tokens, 3);
184 assert_eq!(usage.cache_creation_tokens, 1);
185 }
186
187 /// Claude / GPT / Gemini slugs report native-tool support.
188 ///
189 /// Why: These families support native function-calling; the loop should send
190 /// the `tools` array directly.
191 /// What: Construct providers for representative native slugs, assert `true`.
192 /// Test: this test.
193 #[test]
194 fn supports_native_tools_native_families() {
195 for slug in [
196 "anthropic/claude-sonnet-4-5",
197 "openai/gpt-4o-mini",
198 "google/gemini-2.5-pro",
199 ] {
200 assert!(
201 OpenRouterProvider::new(slug).supports_native_tools(),
202 "expected native-tool support for {slug}"
203 );
204 }
205 }
206
207 /// Qwen / DeepSeek / Gemma slugs do NOT report native-tool support.
208 ///
209 /// Why: These are conservatively treated as non-native until #1023 refines
210 /// the matrix; the loop must use prompt-based fallback guidance for them.
211 /// What: Construct providers for these slugs, assert `false`.
212 /// Test: this test.
213 #[test]
214 fn supports_native_tools_non_native_families() {
215 for slug in [
216 "qwen/qwen-2.5-coder-32b-instruct",
217 "deepseek/deepseek-chat",
218 "google/gemma-2-27b-it",
219 ] {
220 assert!(
221 !OpenRouterProvider::new(slug).supports_native_tools(),
222 "expected NO native-tool support for {slug}"
223 );
224 }
225 }
226
227 /// `anthropic/*` slugs report prompt-caching support (#2156).
228 ///
229 /// Why: This is the gate `agent_loop::build_request` consults before
230 /// marking the tools+system prefix with a cache breakpoint; it must be
231 /// `true` for the exact family the passthrough was verified against.
232 /// What: Construct providers for Anthropic-family slugs (including a
233 /// non-default casing), assert `true`.
234 /// Test: this test.
235 #[test]
236 fn supports_prompt_caching_anthropic_family() {
237 for slug in [
238 "anthropic/claude-sonnet-4-5",
239 "anthropic/claude-haiku-4-5",
240 "Anthropic/Claude-Opus-4",
241 ] {
242 assert!(
243 OpenRouterProvider::new(slug).supports_prompt_caching(),
244 "expected prompt-caching support for {slug}"
245 );
246 }
247 }
248
249 /// Non-Anthropic slugs do NOT report prompt-caching support (#2156).
250 ///
251 /// Why: The OpenRouter passthrough shape has only been verified for
252 /// `anthropic/*`; emitting `cache_control` to other families is
253 /// unverified and must stay off by default.
254 /// What: Construct providers for OpenAI/Gemini/Qwen slugs, assert `false`.
255 /// Test: this test.
256 #[test]
257 fn supports_prompt_caching_non_anthropic_families() {
258 for slug in [
259 "openai/gpt-4o-mini",
260 "google/gemini-2.5-pro",
261 "qwen/qwen-2.5-coder-32b-instruct",
262 ] {
263 assert!(
264 !OpenRouterProvider::new(slug).supports_prompt_caching(),
265 "expected NO prompt-caching support for {slug}"
266 );
267 }
268 }
269
270 /// Every OpenRouter-routed slug requests detailed usage accounting
271 /// (response-side cache-usage fix).
272 ///
273 /// Why: Unlike prompt caching, detailed usage accounting isn't gated to
274 /// a specific model family — it must be requested for every OpenRouter
275 /// call so `usage.cost` and cache counters are available whenever the
276 /// upstream route supports them.
277 /// What: Construct providers for a representative spread of families,
278 /// assert `wants_detailed_usage() == true` for all of them.
279 /// Test: this test.
280 #[test]
281 fn wants_detailed_usage_is_true() {
282 for slug in [
283 "anthropic/claude-sonnet-4-5",
284 "openai/gpt-4o-mini",
285 "qwen/qwen-2.5-coder-32b-instruct",
286 ] {
287 assert!(
288 OpenRouterProvider::new(slug).wants_detailed_usage(),
289 "expected detailed-usage request for {slug}"
290 );
291 }
292 }
293}