mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-08-10 14:27:00 -04:00
## Description Wire output shaping for OpenAI Responses traffic across HTTP `/v1/responses` and Codex WebSocket `response.create` frames. The change adds provider-specific shaping for `instructions`, `reasoning.effort`, and `text.verbosity` while keeping Anthropic request mutation separate. Review follow-up: merged byte-faithful `/v1/responses` forwarding from #1557 and marks shaped HTTP Responses payloads as `body_mutated=True`, so retry forwarding sends the shaped body instead of the original raw bytes. ## Type of Change - [ ] Bug fix (non-breaking change fixes an issue) - [x] New feature (non-breaking change adds functionality) - [ ] Breaking change (fix or feature would cause existing functionality change) - [x] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Added OpenAI Responses output shaping for `instructions`, `reasoning.effort`, and `text.verbosity`. - Wired shaping into `/v1/responses` HTTP and Codex WebSocket `response.create` paths. - Preserved `x-headroom-bypass` and `HEADROOM_OUTPUT_HOLDOUT` behavior. - Added output-shaper transform labels for verbosity, text verbosity, reasoning effort, holdout control, and strata. - Updated output-savings conversation keys for Responses payloads and WS `response.create` envelopes. - Counted WS frame payload tokens when assigning output-savings strata. - Merged byte-faithful `/v1/responses` forwarding from #1557 and kept shaped HTTP bodies on the mutated-forwarding path. - Added tests for classification, shaping, holdout, bypass, labels, WS strata, and byte-faithful forwarding compatibility. - Updated `CHANGELOG.md` for OpenAI Responses output-shaping support. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ uv run --extra dev python -m pytest tests/test_openai_codex_ws_lifecycle.py tests/test_openai_responses_output_shaper.py tests/test_codex_responses_passthrough_bytes.py tests/test_output_shaper.py tests/test_output_savings.py -q 110 passed, 1 warning in 1.49s $ uv run --extra dev ruff check headroom/proxy/handlers/openai.py tests/test_openai_responses_output_shaper.py tests/test_codex_responses_passthrough_bytes.py tests/test_openai_codex_ws_lifecycle.py tests/test_output_shaper.py tests/test_output_savings.py All checks passed! $ git diff --check No whitespace errors. ``` ## Real Behavior Proof - Environment: local macOS checkout, branch `output-shaper-openai-responses`. - Exact command / steps: ran targeted pytest, ruff, and diff checks listed above. - Observed result: targeted tests passed with an existing FastAPI TestClient deprecation warning; ruff passed; diff check passed. - Not tested: full repository test suite, live OpenAI traffic, browser dashboard rendering, full `mypy headroom`. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows project's style guidelines - [x] I performed self-review of my code - [x] I commented my code, particularly in hard-to-understand areas - [x] I made corresponding changes to documentation - [x] My changes generate no new warnings - [x] I added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I updated `CHANGELOG.md` if applicable ## Screenshots N/A ## Additional Notes - Non-applicable Type Change items are left unchecked. - The pytest warning comes from `fastapi.testclient` importing Starlette TestClient and was not introduced by this change. - `CHANGELOG.md` includes entries for OpenAI Responses output-shaping support and byte-faithful `/v1/responses` forwarding compatibility. --------- Co-authored-by: obchain <riteshnikhoriya94@gmail.com>
117 lines
3.8 KiB
Python
117 lines
3.8 KiB
Python
"""Byte-faithful passthrough for Codex Desktop /v1/responses posts (issue #1542).
|
|
|
|
Codex Desktop sends ``POST /v1/responses`` with ``content-encoding: zstd``. The
|
|
handler decodes the body to parse it, but when nothing mutates the request it
|
|
must forward the *original decoded bytes* verbatim and must not re-advertise the
|
|
stale ``content-encoding`` header. Otherwise the upstream ChatGPT Codex endpoint
|
|
either re-canonicalizes a body it rejects, or tries to zstd-decode already-decoded
|
|
JSON — both surface to the client as ``400 {"detail":"Bad Request"}``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("fastapi")
|
|
pytest.importorskip("httpx")
|
|
|
|
import httpx
|
|
from fastapi.testclient import TestClient
|
|
|
|
from headroom.proxy.loopback_guard import require_loopback
|
|
from headroom.proxy.server import ProxyConfig, create_app
|
|
|
|
|
|
def _make_client(optimize: bool = False):
|
|
config = ProxyConfig(
|
|
optimize=optimize,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
)
|
|
app = create_app(config)
|
|
app.dependency_overrides[require_loopback] = lambda: None
|
|
return app
|
|
|
|
|
|
def _fake_upstream_response(url: str) -> httpx.Response:
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"id": "resp_test",
|
|
"object": "response",
|
|
"output": [],
|
|
"usage": {"input_tokens": 12, "output_tokens": 3},
|
|
},
|
|
request=httpx.Request("POST", url),
|
|
)
|
|
|
|
|
|
def _patch_capture(app):
|
|
"""Replace the server's upstream forwarder with a capturing stub."""
|
|
captured: dict = {}
|
|
server = app.state.proxy
|
|
|
|
async def fake_retry(method, url, headers, body, stream=False, **kwargs):
|
|
captured["method"] = method
|
|
captured["url"] = url
|
|
captured["headers"] = dict(headers)
|
|
captured["body"] = body
|
|
captured["kwargs"] = kwargs
|
|
return _fake_upstream_response(url)
|
|
|
|
server._retry_request = fake_retry
|
|
return captured
|
|
|
|
|
|
def test_unmutated_zstd_post_forwards_decoded_bytes_and_strips_content_encoding():
|
|
zstandard = pytest.importorskip("zstandard")
|
|
app = _make_client(optimize=False)
|
|
|
|
payload = {
|
|
"model": "gpt-5-codex",
|
|
"input": "list the files in this repo",
|
|
"instructions": "be terse",
|
|
}
|
|
raw = json.dumps(payload).encode("utf-8")
|
|
compressed = zstandard.ZstdCompressor().compress(raw)
|
|
|
|
with TestClient(app) as client:
|
|
captured = _patch_capture(app)
|
|
resp = client.post(
|
|
"/v1/responses",
|
|
headers={
|
|
"Authorization": "Bearer sk-test",
|
|
"Content-Type": "application/json",
|
|
"Content-Encoding": "zstd",
|
|
"originator": "codex_desktop",
|
|
},
|
|
content=compressed,
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
# Nothing mutated the request -> byte-faithful passthrough engages.
|
|
assert captured["kwargs"].get("body_mutated") is False
|
|
assert captured["kwargs"].get("original_body_bytes") == raw
|
|
# The stale content-encoding must not ride along with already-decoded bytes.
|
|
fwd_headers = {k.lower(): v for k, v in captured["headers"].items()}
|
|
assert "content-encoding" not in fwd_headers
|
|
|
|
|
|
def test_unmutated_plain_post_passes_original_bytes_through():
|
|
app = _make_client(optimize=False)
|
|
raw = json.dumps({"model": "gpt-5-codex", "input": "hi"}).encode("utf-8")
|
|
|
|
with TestClient(app) as client:
|
|
captured = _patch_capture(app)
|
|
resp = client.post(
|
|
"/v1/responses",
|
|
headers={"Authorization": "Bearer sk-test", "Content-Type": "application/json"},
|
|
content=raw,
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
assert captured["kwargs"].get("body_mutated") is False
|
|
assert captured["kwargs"].get("original_body_bytes") == raw
|