Skip to content

Commit 1b8c11e

Browse files
fix(proxy/openai): apply output shaping on /v1/chat/completions (headroomlabs-ai#2328)
## Description Fixes headroomlabs-ai#2302. Output shaping (`HEADROOM_OUTPUT_SHAPER=1`) verbosity steering is wired into the Anthropic `/v1/messages` handler and the OpenAI `/v1/responses` handler, but never into `handle_openai_chat`. OpenAI-compatible clients that route through `/v1/chat/completions` — GitHub Copilot CLI, opencode, older SDKs — therefore got zero output savings, and `headroom output-savings` reported: ``` No shaped requests recorded yet. ``` `handle_openai_chat` referenced verbosity only for cache-key construction, never for actual shaping. The shared helpers (`OutputShaperSettings`, `resolve_verbosity_level`, `assign_arm`, `classify_turn`) existed but were not called from the chat path. ## Fix Run the same shaping block the Anthropic handler already uses, at the end of `handle_openai_chat` (after every other body mutation, before the upstream forward, skipped under `x-headroom-bypass`): - conversation-stable holdout via `assign_arm(conversation_key_from_body(body), holdout)` — `conversation_key_from_body` already reads `messages`, so it works unchanged for a chat body; - stratum labelling on the transforms channel so the outcome funnel feeds the output-savings ledger from the chat path; - for the treatment arm, verbosity steering via a new `shape_openai_chat_request`. The one genuinely new piece is a chat-specific steering injector. Anthropic carries the system prompt in a top-level `system` field and Responses in `instructions`; **chat/completions carries it as a `role: "system"` message inside `messages`**, which neither existing injector touches. `apply_openai_chat_verbosity_steering`: - appends the byte-stable steering block to the tail of the last `system`/`developer` message (idempotent via the `<headroom_output_shaping>` sentinel, and it swaps cleanly when the level changes); - handles both string content and the content-part list form (`[{"type": "text", ...}]`); - inserts a `role: "system"` message at the front only when the request has no system message. Because a whole conversation is stably treatment or control and the block text is fixed per level, a treatment conversation's steering is byte-stable across turns, so the provider prefix cache is not thrashed. Effort routing is intentionally not applied on this path — `route_effort` writes Anthropic-shaped `output_config`/thinking config with no portable chat/completions equivalent — so only the token-reducing verbosity lever runs. Mutating `body` in place is enough on this path; the outbound request serializes `body` fresh, so no body-mutation tracker is needed. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `headroom/proxy/output_steering.py`: add `apply_openai_chat_verbosity_steering` (inject the steering block into the chat `messages` system prompt). - `headroom/proxy/output_shaper.py`: add `shape_openai_chat_request` (verbosity-only chat shaper) and export both new names. - `headroom/proxy/handlers/openai.py`: run the holdout/stratum + shaping block at the end of `handle_openai_chat`, mirroring the Anthropic handler and respecting bypass. - `tests/test_output_steering.py`: cover the injector (append, idempotency, level swap, insert-when-absent, list content, level-0 no-op). - `tests/test_output_shaper.py`: cover `shape_openai_chat_request` (disabled no-op, applies steering, level override, stable second pass). - `CHANGELOG.md`: Bug Fixes entry. ## Testing - [ ] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text $ uvx ruff@0.15.17 check headroom/proxy/output_steering.py headroom/proxy/output_shaper.py headroom/proxy/handlers/openai.py tests/test_output_steering.py tests/test_output_shaper.py All checks passed! $ uvx ruff@0.15.17 format --check <same files> 5 files already formatted $ uvx mypy@1.20.2 --ignore-missing-imports headroom/proxy/output_steering.py headroom/proxy/output_shaper.py Success: no issues found in 2 source files ``` ## Real Behavior Proof - Environment: Windows 11, Python 3.12, `uvx ruff@0.15.17` / `uvx mypy@1.20.2`. A full `pytest` OOMs this box (ML-stack import), so I reproduced the injector with a dependency-free script and left the full pytest to CI. - Exact command / steps: replicated `apply_openai_chat_verbosity_steering` (and the `steering_text`/`replace_or_append_steering_block` primitives it uses) and exercised: an existing string system message, an existing content-part list, no system message, re-apply at the same level, and a level swap. - Observed result: the steering block is appended to the system message while user turns and message order are untouched; re-applying at the same level is a no-op; a level change replaces the block (exactly one remains); a request with no system message gets one inserted at the front; level 0 is a no-op. The added unit tests assert the same through `shape_openai_chat_request`. - Not tested: a live Copilot CLI `/v1/chat/completions` round trip; the added tests drive the pure shaper/injector directly, matching the existing `test_output_shaper.py` / `test_output_steering.py` patterns. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [x] I have updated the CHANGELOG.md if applicable ## Additional Notes The "unit tests pass locally" box is unchecked because a local pytest run imports the ML stack and OOMs this box; the added tests are pure (no ML imports) and run under the normal CI pytest job, and the injector behavior is corroborated by the standalone proof above. Effort routing on chat/completions is deliberately out of scope here (no portable equivalent to the Anthropic effort levers); this PR restores the verbosity-steering savings the issue reports as missing, and effort routing for chat can follow separately if wanted. --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
1 parent a63d235 commit 1b8c11e

5 files changed

Lines changed: 253 additions & 0 deletions

File tree

headroom/proxy/handlers/openai.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3361,6 +3361,63 @@ async def handle_openai_chat(
33613361
# `max_completion_tokens`.
33623362
_normalize_openai_max_tokens(body)
33633363

3364+
# Output shaping (opt-in via HEADROOM_OUTPUT_SHAPER): verbosity steering
3365+
# on the chat system message. Runs after every other body mutation so the
3366+
# turn classifier sees the final messages, and respects the same bypass
3367+
# as compression. OpenAI-compatible clients that route through
3368+
# /v1/chat/completions (GitHub Copilot CLI, opencode, older SDKs) never
3369+
# reached the shaper before, so they saw zero output savings (#2302).
3370+
# Mutating `body` in place is sufficient here — the outbound request
3371+
# serializes `body` fresh, so no body-mutation tracker is needed.
3372+
if not _bypass:
3373+
from headroom.proxy import runtime_env
3374+
from headroom.proxy.output_savings import (
3375+
assign_arm,
3376+
conversation_key_from_body,
3377+
stratum_key,
3378+
stratum_label,
3379+
)
3380+
from headroom.proxy.output_shaper import (
3381+
OutputShaperSettings,
3382+
classify_turn,
3383+
resolve_verbosity_level,
3384+
shape_openai_chat_request,
3385+
)
3386+
3387+
_shaper_settings = OutputShaperSettings.from_env()
3388+
if _shaper_settings.enabled:
3389+
# Conversation-stable holdout: a whole conversation is treatment
3390+
# or control, which keeps the A/B comparison clean and the
3391+
# provider prefix cache stable (the steering block never flips
3392+
# mid-conversation).
3393+
_holdout = 0.0
3394+
try:
3395+
_holdout = float(runtime_env.getenv("HEADROOM_OUTPUT_HOLDOUT", "0") or "0")
3396+
except ValueError:
3397+
_holdout = 0.0
3398+
_arm = assign_arm(conversation_key_from_body(body), _holdout)
3399+
_turn_kind = classify_turn(body.get("messages", [])).value
3400+
_stratum = stratum_key(
3401+
turn_kind=_turn_kind,
3402+
input_tokens=original_tokens,
3403+
model=model,
3404+
has_tools=bool(body.get("tools")),
3405+
)
3406+
# Carry (arm, stratum) on the transforms channel so the outcome
3407+
# funnel feeds the output-savings ledger from the chat path too.
3408+
transforms_applied.append(stratum_label(_arm, _stratum))
3409+
if _arm == "treatment":
3410+
_level, _src = resolve_verbosity_level(_shaper_settings)
3411+
_shape_result = shape_openai_chat_request(
3412+
body, _shaper_settings, level_override=_level
3413+
)
3414+
if _shape_result.changed:
3415+
transforms_applied.extend(_shape_result.labels or [])
3416+
logger.info(
3417+
f"[{request_id}] OutputShaper(chat, L{_level}/{_src}): "
3418+
f"{_shape_result.labels}"
3419+
)
3420+
33643421
# Route through LiteLLM/any-llm backend if configured
33653422
if self.anthropic_backend is not None:
33663423
try:

headroom/proxy/output_shaper.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
lower_text_verbosity_value,
5959
)
6060
from headroom.proxy.output_steering import (
61+
apply_openai_chat_verbosity_steering,
6162
apply_openai_responses_verbosity_steering,
6263
apply_verbosity_steering,
6364
replace_or_append_steering_block,
@@ -76,6 +77,7 @@
7677
"OutputShaperSettings",
7778
"ShapeResult",
7879
"TurnKind",
80+
"apply_openai_chat_verbosity_steering",
7981
"apply_openai_responses_verbosity_steering",
8082
"apply_verbosity_steering",
8183
"classify_openai_responses_input",
@@ -84,6 +86,7 @@
8486
"route_effort",
8587
"route_openai_reasoning_effort",
8688
"route_openai_text_verbosity",
89+
"shape_openai_chat_request",
8790
"shape_openai_responses_request",
8891
"shape_request",
8992
"steering_text",
@@ -352,6 +355,36 @@ def shape_request(
352355
return result
353356

354357

358+
def shape_openai_chat_request(
359+
body: dict[str, Any],
360+
settings: OutputShaperSettings | None = None,
361+
level_override: int | None = None,
362+
) -> ShapeResult:
363+
"""Apply output-shaping levers to an OpenAI chat/completions body in place.
364+
365+
The chat counterpart of :func:`shape_request`. Chat carries the system
366+
prompt as a ``role: "system"`` message, so verbosity steering uses the
367+
chat-specific injector. Effort routing is intentionally not applied here:
368+
the ``route_effort`` levers write Anthropic-shaped config and there is no
369+
portable chat/completions equivalent, so only the verbosity steering lever
370+
(the one that reduces output tokens) runs on this path.
371+
"""
372+
if settings is None:
373+
settings = OutputShaperSettings.from_env()
374+
result = ShapeResult()
375+
if not settings.enabled:
376+
return result
377+
378+
assert result.labels is not None # __post_init__ guarantees this
379+
380+
level = settings.verbosity_level if level_override is None else level_override
381+
if level > 0 and apply_openai_chat_verbosity_steering(body, level):
382+
result.changed = True
383+
result.labels.append(f"output_shaper:verbosity:L{level}")
384+
385+
return result
386+
387+
355388
# ---------------------------------------------------------------------------
356389
# OpenAI Responses format (Codex, /v1/responses HTTP + WebSocket)
357390
# ---------------------------------------------------------------------------

headroom/proxy/output_steering.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,68 @@ def apply_verbosity_steering(body: dict[str, Any], level: int) -> bool:
4646
return False
4747

4848

49+
def apply_openai_chat_verbosity_steering(
50+
body: dict[str, Any],
51+
level: int,
52+
) -> bool:
53+
"""Append or replace the steering block in an OpenAI chat/completions body.
54+
55+
OpenAI ``/v1/chat/completions`` carries the system prompt as a
56+
``role: "system"`` (or ``"developer"``) message inside ``messages`` rather
57+
than a top-level field, so it needs its own injector (the Anthropic
58+
``system`` and Responses ``instructions`` variants do not reach it — the
59+
root cause of GitHub Copilot CLI seeing zero output savings, #2302).
60+
61+
The block is appended to the tail of the last system/developer message so a
62+
treatment conversation's steering stays byte-stable across turns (and
63+
re-applies idempotently via the sentinel). When the request carries no
64+
system message at all, one is inserted at the front. Returns True only when
65+
the body actually changed.
66+
"""
67+
text = steering_text(level)
68+
if text is None:
69+
return False
70+
71+
messages = body.get("messages")
72+
if not isinstance(messages, list):
73+
return False
74+
75+
target: dict[str, Any] | None = None
76+
for message in messages:
77+
if isinstance(message, dict) and message.get("role") in ("system", "developer"):
78+
target = message
79+
if target is None:
80+
# No system prompt to append to — insert one carrying just the block.
81+
messages.insert(0, {"role": "system", "content": text})
82+
return True
83+
84+
content = target.get("content")
85+
if content is None:
86+
target["content"] = text
87+
return True
88+
if isinstance(content, str):
89+
updated, changed = replace_or_append_steering_block(content, text)
90+
if changed:
91+
target["content"] = updated
92+
return changed
93+
if isinstance(content, list):
94+
# OpenAI also accepts a content-part list ([{"type": "text", ...}]).
95+
for part in content:
96+
if (
97+
isinstance(part, dict)
98+
and part.get("type") == "text"
99+
and isinstance(part.get("text"), str)
100+
and part["text"].startswith(_STEERING_SENTINEL)
101+
):
102+
if part["text"] == text:
103+
return False
104+
part["text"] = text
105+
return True
106+
content.append({"type": "text", "text": text})
107+
return True
108+
return False
109+
110+
49111
def apply_openai_responses_verbosity_steering(
50112
body: dict[str, Any],
51113
level: int,

tests/test_output_shaper.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
route_effort,
2121
route_openai_reasoning_effort,
2222
route_openai_text_verbosity,
23+
shape_openai_chat_request,
2324
shape_openai_responses_request,
2425
shape_request,
2526
steering_text,
@@ -402,3 +403,40 @@ def test_shape_openai_responses_combines_steering_native_knobs(self):
402403
assert steering_text(2) in body["instructions"]
403404
assert body["reasoning"]["effort"] == "low"
404405
assert body["text"]["verbosity"] == "low"
406+
407+
408+
class TestShapeOpenAIChatRequest:
409+
def test_disabled_is_noop(self):
410+
body = {"messages": [{"role": "system", "content": "Sys."}]}
411+
snapshot = copy.deepcopy(body)
412+
result = shape_openai_chat_request(body, OutputShaperSettings(enabled=False))
413+
assert result.changed is False
414+
assert body == snapshot
415+
416+
def test_enabled_applies_verbosity_steering(self):
417+
body = {
418+
"messages": [
419+
{"role": "system", "content": "Sys."},
420+
{"role": "user", "content": "hi"},
421+
]
422+
}
423+
result = shape_openai_chat_request(body, ENABLED)
424+
assert result.changed is True
425+
assert result.labels == ["output_shaper:verbosity:L2"]
426+
assert steering_text(2) in body["messages"][0]["content"]
427+
# User turn is untouched.
428+
assert body["messages"][1] == {"role": "user", "content": "hi"}
429+
430+
def test_level_override_supersedes_settings(self):
431+
body = {"messages": [{"role": "system", "content": "Sys."}]}
432+
result = shape_openai_chat_request(body, ENABLED, level_override=4)
433+
assert result.labels == ["output_shaper:verbosity:L4"]
434+
assert steering_text(4) in body["messages"][0]["content"]
435+
436+
def test_second_pass_is_stable(self):
437+
body = {"messages": [{"role": "system", "content": "Sys."}]}
438+
shape_openai_chat_request(body, ENABLED)
439+
snapshot = copy.deepcopy(body)
440+
second = shape_openai_chat_request(body, ENABLED)
441+
assert second.changed is False
442+
assert body == snapshot

tests/test_output_steering.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,66 @@ def test_openai_responses_steering_is_idempotent() -> None:
4242
snapshot = body.copy()
4343
assert apply_openai_responses_verbosity_steering(body, 2) is False
4444
assert body == snapshot
45+
46+
47+
def test_openai_chat_steering_appends_to_system_message() -> None:
48+
from headroom.proxy.output_steering import apply_openai_chat_verbosity_steering
49+
50+
body = {
51+
"messages": [
52+
{"role": "system", "content": "You are helpful."},
53+
{"role": "user", "content": "hi"},
54+
]
55+
}
56+
assert apply_openai_chat_verbosity_steering(body, 2) is True
57+
sys_content = body["messages"][0]["content"]
58+
assert "You are helpful." in sys_content
59+
assert steering_text(2) in sys_content
60+
# Other messages and ordering are untouched.
61+
assert body["messages"][1] == {"role": "user", "content": "hi"}
62+
assert [m["role"] for m in body["messages"]] == ["system", "user"]
63+
64+
65+
def test_openai_chat_steering_is_idempotent_and_swaps_level() -> None:
66+
from headroom.proxy.output_steering import apply_openai_chat_verbosity_steering
67+
68+
body = {"messages": [{"role": "system", "content": "S."}]}
69+
assert apply_openai_chat_verbosity_steering(body, 2) is True
70+
first = body["messages"][0]["content"]
71+
# Same level again: no change.
72+
assert apply_openai_chat_verbosity_steering(body, 2) is False
73+
assert body["messages"][0]["content"] == first
74+
# Different level: replace, still exactly one block.
75+
assert apply_openai_chat_verbosity_steering(body, 4) is True
76+
swapped = body["messages"][0]["content"]
77+
assert steering_text(4) in swapped
78+
assert swapped.count("<headroom_output_shaping>") == 1
79+
80+
81+
def test_openai_chat_steering_inserts_system_when_absent() -> None:
82+
from headroom.proxy.output_steering import apply_openai_chat_verbosity_steering
83+
84+
body = {"messages": [{"role": "user", "content": "hi"}]}
85+
assert apply_openai_chat_verbosity_steering(body, 3) is True
86+
assert body["messages"][0]["role"] == "system"
87+
assert body["messages"][0]["content"] == steering_text(3)
88+
assert body["messages"][1] == {"role": "user", "content": "hi"}
89+
90+
91+
def test_openai_chat_steering_handles_list_content() -> None:
92+
from headroom.proxy.output_steering import apply_openai_chat_verbosity_steering
93+
94+
body = {"messages": [{"role": "system", "content": [{"type": "text", "text": "base"}]}]}
95+
assert apply_openai_chat_verbosity_steering(body, 1) is True
96+
parts = body["messages"][0]["content"]
97+
assert parts[0] == {"type": "text", "text": "base"}
98+
assert parts[1]["type"] == "text"
99+
assert parts[1]["text"] == steering_text(1)
100+
101+
102+
def test_openai_chat_steering_level_zero_is_noop() -> None:
103+
from headroom.proxy.output_steering import apply_openai_chat_verbosity_steering
104+
105+
body = {"messages": [{"role": "system", "content": "S."}]}
106+
assert apply_openai_chat_verbosity_steering(body, 0) is False
107+
assert body["messages"][0]["content"] == "S."

0 commit comments

Comments
 (0)