Skip to main content

trusty_code/llm/
response_ext.rs

1//! trusty-code-local views over the SHARED [`ChatResponse`] (#4425).
2//!
3//! Why: #4425 deleted trusty-code's duplicate `ChatRequest`/`ChatResponse`/
4//! `ChatMessage`/`InferenceError` types in favour of `trusty_common::inference`'s.
5//! Three helpers that used to be inherent methods on the local response type
6//! are trusty-code-specific and therefore have no business on the shared type:
7//! they translate into `crate::perf`'s cost vocabulary or encode a
8//! trusty-code recording rule. Rust forbids inherent impls on a foreign type,
9//! so they live here as free functions rather than being pushed upstream into
10//! a crate that has no `perf` module.
11//! What: [`token_usage`] (shared wire usage → [`TokenUsage`]), [`finish_reason`]
12//! (the raw wire stop string), and [`resolved_model`] (which slug a turn is
13//! attributed to, #1475 bug 2).
14//! Test: inline `tests` — usage mapping incl. both cache shapes and the
15//! authoritative cost, and both `resolved_model` branches.
16
17use trusty_common::inference::ChatResponse;
18
19use crate::perf::TokenUsage;
20
21/// Convert a response's wire usage block into trusty-code's [`TokenUsage`].
22///
23/// Why: `PerfCollector::record_phase` accepts `&TokenUsage`; keeping the
24/// conversion in ONE place stops each call site from re-deciding how the two
25/// cache-token shapes (flat Anthropic-native fields vs. OpenRouter's nested
26/// `prompt_tokens_details`) merge.
27/// What: delegates the merge to the shared `UsageBlock::into_usage` — which is
28/// the same field-for-field logic the deleted `UsageBlock::into_token_usage`
29/// performed — then copies the five fields across. `cost_usd` carries the
30/// provider's authoritative, already-cache-discounted price so callers prefer
31/// it over a static per-token recompute.
32/// Test: `token_usage_maps_flat_cache_fields`,
33/// `token_usage_maps_openrouter_details`, `token_usage_carries_cost`.
34pub fn token_usage(response: &ChatResponse) -> TokenUsage {
35    let usage = response.usage();
36    let mut out = TokenUsage::new(
37        usage.prompt_tokens,
38        usage.completion_tokens,
39        usage.cache_read_tokens,
40        usage.cache_creation_tokens,
41    );
42    out.cost_usd = usage.cost_usd;
43    out
44}
45
46/// The first choice's raw wire stop condition.
47///
48/// Why: trusty-code's loop and its tests compare the stop reason as the wire
49/// string (`"stop"`, `"tool_calls"`); the shared type exposes it only as the
50/// typed `StopReason`, and re-deriving the string at each site would risk two
51/// spellings drifting apart.
52/// What: `choices[0].finish_reason.as_deref()`, or `None`.
53/// Test: `finish_reason_reads_first_choice`.
54pub fn finish_reason(response: &ChatResponse) -> Option<&str> {
55    response.choices.first()?.finish_reason.as_deref()
56}
57
58/// The model slug this turn should be attributed to (#1475 bug 2).
59///
60/// Why: `run_task::recorder::RecordingLlmClient` must record what the provider
61/// actually ran, not merely what was asked for — a routing/fallback slug
62/// (`:auto`, a multi-model alias) can resolve to a different concrete model,
63/// and pricing the turn against the requested slug would then be wrong.
64/// What: the response's `model` when non-empty, else `requested`.
65/// Test: `resolved_model_prefers_response_model`,
66/// `resolved_model_falls_back_to_requested`.
67pub fn resolved_model<'a>(response: &'a ChatResponse, requested: &'a str) -> &'a str {
68    if response.model.is_empty() {
69        requested
70    } else {
71        &response.model
72    }
73}
74
75// ── Tests ─────────────────────────────────────────────────────────────────────
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    /// Build a response carrying only the given usage JSON.
82    ///
83    /// Why: every usage test differs only in the usage block; one builder keeps
84    /// the assertions readable.
85    /// What: deserialises a minimal fixture with the supplied usage object.
86    fn with_usage(usage_json: &str) -> ChatResponse {
87        let fixture = format!(
88            r#"{{"id":"gen-1","model":"anthropic/claude-sonnet-4-5",
89                 "choices":[{{"message":{{"role":"assistant","content":"ok"}},
90                              "finish_reason":"stop"}}],
91                 "usage":{usage_json}}}"#
92        );
93        serde_json::from_str(&fixture).expect("deserialise fixture")
94    }
95
96    /// The flat Anthropic-native cache fields map onto `TokenUsage`.
97    ///
98    /// Why: this is the Bedrock / direct-Anthropic wire shape; dropping it
99    /// would silently zero cache effectiveness on those routes.
100    /// What: assert all four token buckets.
101    /// Test: this test.
102    #[test]
103    fn token_usage_maps_flat_cache_fields() {
104        let resp = with_usage(
105            r#"{"prompt_tokens":12,"completion_tokens":5,"total_tokens":17,
106                "cache_read_input_tokens":3,"cache_creation_input_tokens":1}"#,
107        );
108        let usage = token_usage(&resp);
109        assert_eq!(usage.prompt_tokens, 12);
110        assert_eq!(usage.completion_tokens, 5);
111        assert_eq!(usage.cache_read_tokens, 3);
112        assert_eq!(usage.cache_creation_tokens, 1);
113    }
114
115    /// OpenRouter's nested `prompt_tokens_details` maps onto the same buckets.
116    ///
117    /// Why: OpenRouter reports cache counters nested rather than flat; the
118    /// caller must not have to know which shape arrived.
119    /// What: assert the nested counters surface as cache read/creation.
120    /// Test: this test.
121    #[test]
122    fn token_usage_maps_openrouter_details() {
123        let resp = with_usage(
124            r#"{"prompt_tokens":100,"completion_tokens":20,"total_tokens":120,
125                "prompt_tokens_details":{"cached_tokens":80,"cache_write_tokens":5}}"#,
126        );
127        let usage = token_usage(&resp);
128        assert_eq!(usage.cache_read_tokens, 80);
129        assert_eq!(usage.cache_creation_tokens, 5);
130    }
131
132    /// The provider's authoritative cost survives the conversion.
133    ///
134    /// Why: without it, cost reporting falls back to a static per-token
135    /// estimate that ignores the cache discount and overstates spend.
136    /// What: assert `cost_usd`.
137    /// Test: this test.
138    #[test]
139    fn token_usage_carries_cost() {
140        let resp = with_usage(
141            r#"{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2,"cost":0.00123}"#,
142        );
143        assert_eq!(token_usage(&resp).cost_usd, Some(0.00123));
144    }
145
146    /// `finish_reason` reads the first choice's raw wire string.
147    ///
148    /// Why: the loop's stop/continue decision keys off this exact spelling.
149    /// What: assert `"stop"` from the fixture.
150    /// Test: this test.
151    #[test]
152    fn finish_reason_reads_first_choice() {
153        let resp = with_usage(r#"{}"#);
154        assert_eq!(finish_reason(&resp), Some("stop"));
155    }
156
157    /// A response that names a model wins over the requested slug.
158    ///
159    /// Why: the recorder must attribute the turn to what actually ran.
160    /// What: assert the response's own model is returned.
161    /// Test: this test.
162    #[test]
163    fn resolved_model_prefers_response_model() {
164        let resp = with_usage(r#"{}"#);
165        assert_eq!(
166            resolved_model(&resp, "asked/for"),
167            "anthropic/claude-sonnet-4-5"
168        );
169    }
170
171    /// An empty response model falls back to the requested slug.
172    ///
173    /// Why: mocks and older fixtures omit `model`; attributing those turns to
174    /// an empty string would break pricing lookups.
175    /// What: blank the model, assert the fallback.
176    /// Test: this test.
177    #[test]
178    fn resolved_model_falls_back_to_requested() {
179        let mut resp = with_usage(r#"{}"#);
180        resp.model = String::new();
181        assert_eq!(resolved_model(&resp, "asked/for"), "asked/for");
182    }
183}