Skip to main content

lean_ctx/proxy/
openai.rs

1use axum::{
2    body::Body,
3    extract::State,
4    http::{Request, StatusCode},
5    response::Response,
6};
7use serde_json::Value;
8
9use super::ProxyState;
10use super::forward;
11use super::tool_kind::{self, ToolResultKind};
12use super::{cache_safety, prose};
13use crate::core::config::{HistoryMode, ProseRole};
14
15pub async fn handler(
16    State(state): State<ProxyState>,
17    req: Request<Body>,
18) -> Result<Response, StatusCode> {
19    let upstream = state.openai_upstream();
20    forward::forward_request(
21        State(state),
22        req,
23        &upstream,
24        "/v1/chat/completions",
25        compress_request_body,
26        "OpenAI",
27        &[],
28    )
29    .await
30}
31
32fn compress_request_body(parsed: Value, original_size: usize) -> (Vec<u8>, usize, usize) {
33    let mut doc = parsed;
34    let mut modified = false;
35
36    // Opt-in per-role prose aggressiveness (#710); both default `None` → no-op.
37    let cfg = crate::core::config::Config::load();
38    let system_aggr = cfg.proxy.resolved_role_aggressiveness(ProseRole::System);
39    let user_aggr = cfg.proxy.resolved_role_aggressiveness(ProseRole::User);
40    let live_compress = cfg.proxy.live_compresses();
41    let mode = cfg.proxy.resolved_history_mode();
42    // #895 Track B: output-savings holdout arm, from the pristine body (before any
43    // mutation below) so it matches the arm the response meter records. Control
44    // conversations skip output-shaping but are still metered. Default 0 → Treatment.
45    let arm = super::holdout::assign(
46        &super::holdout::openai_chat_key(&doc),
47        cfg.proxy.output_holdout_fraction(),
48    );
49    // #493: in-band CCR expansion (opt-in). Splice any <lc_expand:HASH> the model
50    // echoed back into the verbatim original from the local tee store. A strict
51    // no-op when no marker is present (byte-identical body → cache-safe). Runs
52    // before the meter-only short-circuit so an explicit expand request is
53    // honored even when the proxy is otherwise byte-passthrough.
54    if cfg.proxy.ccr_inband_enabled() {
55        modified |= super::ccr::splice_inband_in_place(&mut doc);
56    }
57    // #834: cache-safe cross-provider effort control. Default off → no-op. The
58    // value is a constant, so it never perturbs the prompt-cache prefix; it sets
59    // `reasoning_effort` only on reasoning models and never overrides a
60    // client-set value.
61    if arm == super::holdout::Arm::Treatment {
62        if let Some(effort) = cfg.proxy.resolved_effort() {
63            modified |= super::effort::apply_openai_chat(&mut doc, effort);
64        }
65        // #895: cache-safe wire verbosity steer; control arm skips it (measured).
66        if cfg.proxy.verbosity_steer_enabled() {
67            modified |= super::verbosity::apply_openai_chat(&mut doc);
68        }
69    }
70    // Meter-only (#481): nothing rewrites the body, so skip all work and let
71    // forward + usage metering run against the byte-unchanged request. A pending
72    // in-band splice (`modified`) opts out: the body did change this turn.
73    if !live_compress
74        && mode == HistoryMode::Off
75        && system_aggr.is_none()
76        && user_aggr.is_none()
77        && !modified
78    {
79        let out = serde_json::to_vec(&doc).unwrap_or_default();
80        return (out, original_size, original_size);
81    }
82    let mut prose_segments: u64 = 0;
83
84    if let Some(messages) = doc.get_mut("messages").and_then(|m| m.as_array_mut()) {
85        let tool_names = tool_kind::openai_tool_names(messages);
86
87        // OpenAI's automatic prompt caching is prefix-based like Anthropic's,
88        // so history is pruned at the same frozen, cache-aware boundary. `mode`
89        // resolved above.
90        let boundary = super::history_prune::prune_boundary(mode, messages.len());
91        // Mirror the Anthropic guard: never rewrite content behind a client
92        // `cache_control` breakpoint (#448). OpenAI requests carry none, so this
93        // resolves to 0 and pruning is byte-for-byte unchanged — but the code
94        // path stays uniform across providers.
95        let cached = super::history_prune::cached_prefix_len(messages);
96        modified |=
97            super::history_prune::prune_history_range(messages, cached, boundary, &tool_names);
98
99        for msg in messages.iter_mut() {
100            let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
101            if role != "tool" {
102                continue;
103            }
104
105            let name = msg
106                .get("tool_call_id")
107                .and_then(|v| v.as_str())
108                .and_then(|id| tool_names.get(id))
109                .map(String::as_str);
110            let kind = name.map_or(ToolResultKind::Other, tool_kind::classify_tool_name);
111
112            // #481: skip live compression when globally off or tool excluded.
113            if !live_compress || name.is_some_and(|n| cfg.proxy.is_tool_live_compress_excluded(n)) {
114                continue;
115            }
116            if let Some(mut content) = msg
117                .get_mut("content")
118                .and_then(|c| c.as_str().map(String::from))
119                && super::tool_output::compress_text(&mut content, name, kind)
120            {
121                msg["content"] = Value::String(content);
122                modified = true;
123            }
124        }
125
126        // Frozen-region prose: system anchors (deterministic rewrite keeps the
127        // auto-cached prefix byte-stable, so safe at any position outside the
128        // client-cached prefix) and user turns in `[cached, boundary)`. The
129        // `assistant` and `tool` roles are never touched (passthrough). Both
130        // knobs default off, so this is inert unless an operator opts in.
131        if system_aggr.is_some() || user_aggr.is_some() {
132            for (i, msg) in messages.iter_mut().enumerate() {
133                if i < cached {
134                    continue;
135                }
136                let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
137                let aggr = match role {
138                    "system" | "developer" => system_aggr,
139                    "user" if i < boundary => user_aggr,
140                    _ => None,
141                };
142                if let Some(a) = aggr {
143                    prose_segments += u64::from(prose::compress_message_content(msg, a));
144                }
145            }
146        }
147    }
148
149    if prose_segments > 0 {
150        modified = true;
151    }
152    cache_safety::record(prose_segments, true);
153
154    // Ask OpenAI to append a final usage chunk so the proxy can meter real
155    // spend. Not counted as compression (it slightly grows the body), so it
156    // never inflates the savings figure.
157    maybe_inject_usage_reporting(&mut doc);
158
159    let out = serde_json::to_vec(&doc).unwrap_or_default();
160    let compressed_size = if modified { out.len() } else { original_size };
161    (out, original_size, compressed_size)
162}
163
164/// Config-gated wrapper around [`inject_usage_reporting`].
165fn maybe_inject_usage_reporting(doc: &mut Value) {
166    if crate::core::config::Config::load()
167        .proxy
168        .meters_openai_usage()
169    {
170        inject_usage_reporting(doc);
171    }
172}
173
174/// Injects `stream_options.include_usage = true` into a streamed Chat
175/// Completions request so the final SSE chunk carries `usage` (OpenAI omits it
176/// otherwise). No-op for non-streamed requests or when the client already
177/// configured `stream_options.include_usage`.
178fn inject_usage_reporting(doc: &mut Value) {
179    if doc.get("stream").and_then(Value::as_bool) != Some(true) {
180        return;
181    }
182    let Some(obj) = doc.as_object_mut() else {
183        return;
184    };
185    let opts = obj
186        .entry("stream_options")
187        .or_insert_with(|| Value::Object(serde_json::Map::new()));
188    if let Some(opts_obj) = opts.as_object_mut() {
189        opts_obj.entry("include_usage").or_insert(Value::Bool(true));
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::super::compress::compress_tool_result;
196    use super::*;
197
198    #[test]
199    fn read_file_tool_result_protected() {
200        let code = (0..60)
201            .map(|i| format!("    const value{i} = computeValue{i}(ctx, opts);"))
202            .collect::<Vec<_>>()
203            .join("\n");
204        let body = serde_json::json!({
205            "model": "gpt-5",
206            "messages": [
207                {"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "read_file"}}]},
208                {"role": "tool", "tool_call_id": "call_1", "content": code}
209            ]
210        });
211        let bytes = serde_json::to_vec(&body).unwrap();
212        let (out, _orig, _comp) = compress_request_body(body, bytes.len());
213        let parsed: Value = serde_json::from_slice(&out).unwrap();
214        assert!(
215            parsed["messages"][1]["content"]
216                .as_str()
217                .unwrap()
218                .contains("value59")
219        );
220    }
221
222    #[test]
223    fn json_envelope_tool_output_is_compressed() {
224        let _iso = crate::core::data_dir::isolated_data_dir();
225        let raw = long_git_status();
226        let expected = compress_tool_result(&raw, Some("Bash"));
227        let envelope = serde_json::to_string(&serde_json::json!({
228            "content": [{"type": "text", "text": raw}],
229            "isError": false,
230        }))
231        .unwrap();
232        let body = serde_json::json!({
233            "model": "gpt-5",
234            "messages": [
235                {"role": "assistant", "tool_calls": [{
236                    "id": "call_1",
237                    "type": "function",
238                    "function": {"name": "Bash"}
239                }]},
240                {"role": "tool", "tool_call_id": "call_1", "content": envelope}
241            ]
242        });
243        let bytes = serde_json::to_vec(&body).unwrap();
244        let (out, orig, comp) = compress_request_body(body, bytes.len());
245
246        assert!(comp < orig, "JSON envelope tool output should shrink");
247        let parsed: Value = serde_json::from_slice(&out).unwrap();
248        let content = parsed["messages"][1]["content"].as_str().unwrap();
249        let envelope: Value = serde_json::from_str(content).unwrap();
250        assert_eq!(envelope["content"][0]["text"].as_str().unwrap(), expected);
251    }
252
253    #[test]
254    fn injects_include_usage_for_streaming() {
255        let mut doc = serde_json::json!({"model": "gpt-5.4", "stream": true, "messages": []});
256        inject_usage_reporting(&mut doc);
257        assert_eq!(doc["stream_options"]["include_usage"], Value::Bool(true));
258    }
259
260    fn long_git_status() -> String {
261        let mut s = String::from(
262            "$ git status\nOn branch main\nYour branch is up to date with 'origin/main'.\n\nChanges not staged for commit:\n  (use \"git add <file>...\" to update what will be committed)\n",
263        );
264        for i in 0..80 {
265            s.push_str(&format!("\tmodified:   src/module_{i}/file_{i}.rs\n"));
266        }
267        s.push_str("\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n");
268        s
269    }
270
271    #[test]
272    fn no_injection_for_non_streaming() {
273        let mut doc = serde_json::json!({"model": "gpt-5.4", "messages": []});
274        inject_usage_reporting(&mut doc);
275        assert!(
276            doc.get("stream_options").is_none(),
277            "non-streamed requests get usage in the body, no injection needed"
278        );
279    }
280
281    #[test]
282    fn respects_client_set_include_usage() {
283        let mut doc = serde_json::json!({
284            "model": "gpt-5.4",
285            "stream": true,
286            "stream_options": {"include_usage": false},
287            "messages": []
288        });
289        inject_usage_reporting(&mut doc);
290        assert_eq!(
291            doc["stream_options"]["include_usage"],
292            Value::Bool(false),
293            "an explicit client value must be preserved"
294        );
295    }
296
297    fn big_prose() -> String {
298        let p = "You are a careful, senior software engineer. You always explain your \
299                 reasoning before making changes, you prefer small reviewable diffs, and \
300                 you never introduce mock data or placeholders into production code. ";
301        [p; 6].join("\n")
302    }
303
304    #[test]
305    fn system_message_compressed_and_assistant_untouched() {
306        let _iso = crate::core::data_dir::isolated_data_dir();
307        crate::core::config::Config::update_global(|c| {
308            c.proxy.role_aggressiveness.system = Some(0.6);
309        })
310        .unwrap();
311
312        let prose = big_prose();
313        let body = serde_json::json!({
314            "model": "gpt-5",
315            "messages": [
316                {"role": "system", "content": prose},
317                {"role": "user", "content": "hi"},
318                {"role": "assistant", "content": prose},
319            ]
320        });
321        let bytes = serde_json::to_vec(&body).unwrap();
322        let (out, _o, _c) = compress_request_body(body, bytes.len());
323        let parsed: Value = serde_json::from_slice(&out).unwrap();
324
325        assert!(
326            parsed["messages"][0]["content"].as_str().unwrap().len() < prose.len(),
327            "system message prose must be compressed when enabled"
328        );
329        assert_eq!(
330            parsed["messages"][2]["content"].as_str().unwrap(),
331            prose,
332            "assistant turns must pass through verbatim (#710)"
333        );
334    }
335
336    #[test]
337    fn openai_prose_compression_is_deterministic() {
338        let _iso = crate::core::data_dir::isolated_data_dir();
339        crate::core::config::Config::update_global(|c| {
340            c.proxy.role_aggressiveness.system = Some(0.6);
341        })
342        .unwrap();
343        let prose = big_prose();
344        let mk = || {
345            serde_json::json!({
346                "model": "gpt-5",
347                "messages": [{"role": "system", "content": prose}, {"role": "user", "content": "hi"}]
348            })
349        };
350        let (a, b) = (mk(), mk());
351        let la = serde_json::to_vec(&a).unwrap().len();
352        let lb = serde_json::to_vec(&b).unwrap().len();
353        assert_eq!(
354            compress_request_body(a, la).0,
355            compress_request_body(b, lb).0,
356            "identical input must yield byte-identical output (#498)"
357        );
358    }
359
360    #[test]
361    fn effort_control_sets_reasoning_effort_and_off_is_noop() {
362        // #834 end-to-end through the Chat Completions request path.
363        let _iso = crate::core::data_dir::isolated_data_dir();
364        crate::test_env::remove_var("LEAN_CTX_PROXY_EFFORT");
365        let body = serde_json::json!({
366            "model": "gpt-5.5", "messages": [{"role": "user", "content": "hi"}]
367        });
368        let bytes = serde_json::to_vec(&body).unwrap();
369
370        // Off by default: a cache-safe no-op (size unchanged, no param added).
371        let (off, o, c) = compress_request_body(body.clone(), bytes.len());
372        assert_eq!(c, o, "effort off must be a passthrough");
373        assert!(
374            serde_json::from_slice::<Value>(&off)
375                .unwrap()
376                .get("reasoning_effort")
377                .is_none()
378        );
379
380        // Enabled: reasoning_effort is filled on the reasoning model.
381        crate::core::config::Config::update_global(|cfg| {
382            cfg.proxy.effort = Some("low".into());
383        })
384        .unwrap();
385        let (on, _o, _c) = compress_request_body(body, bytes.len());
386        assert_eq!(
387            serde_json::from_slice::<Value>(&on).unwrap()["reasoning_effort"],
388            "low"
389        );
390    }
391}