The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(aux): translate response_format to output_config.format for anthropic transport
Soju06f709bd844561
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex d1a513c7ec1..587b9442d3c 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -1956,6 +1956,39 @@ class AsyncCodexAuxiliaryClient:self._real_client = sync_wrapper._real_client+def _translate_anthropic_response_format(+ anthropic_kwargs: Dict[str, Any], response_format: Any,+) -> None:+ """Merge an OpenAI response format into Anthropic ``output_config``."""+ if not isinstance(response_format, dict):+ return++ format_type = response_format.get("type")+ if format_type == "json_schema":+ json_schema = response_format.get("json_schema")+ if not isinstance(json_schema, dict) or "schema" not in json_schema:+ return+ native_format = {+ "type": "json_schema",+ "schema": json_schema["schema"],+ }+ elif format_type == "json_object":+ # Anthropic SDK 0.87.0 exposes only JSONOutputFormatParam, whose+ # required type is ``json_schema``; it has no schema-less JSON mode.+ native_format = {+ "type": "json_schema",+ "schema": {"type": "object"},+ }+ else:+ return++ output_config = anthropic_kwargs.get("output_config")+ if not isinstance(output_config, dict):+ output_config = {}+ anthropic_kwargs["output_config"] = output_config+ output_config["format"] = native_format++class _AnthropicCompletionsAdapter:"""OpenAI-client-compatible adapter for Anthropic Messages API."""@@ -2056,18 +2089,25 @@ class _AnthropicCompletionsAdapter:# form is the documented Anthropic SDK passthrough for non-standard# request body keys; merge on top of whatever build_anthropic_kwargs# already produced (e.g. fast-mode ``speed``) so call-time settings- # survive. Two exclusions:+ # survive. Three exclusions:# - ``reasoning``: the OpenAI-shaped config dict is TRANSLATED into# the native ``thinking`` field above (build_anthropic_kwargs);# forwarding the raw field alongside would double-specify# reasoning and 400 on strict gateways.+ # - ``response_format``: the OpenAI structured-output shape is+ # TRANSLATED into top-level ``output_config.format`` below;+ # forwarding the raw field 400s on strict Anthropic gateways.# - ``_``-prefixed keys: private Hermes plumbing (_reasoning_config# et al.), never wire fields.caller_extra_body = kwargs.get("extra_body")if caller_extra_body and isinstance(caller_extra_body, dict):+ _translate_anthropic_response_format(+ anthropic_kwargs, caller_extra_body.get("response_format"),+ )passthrough = {k: v for k, v in caller_extra_body.items()- if k != "reasoning" and not str(k).startswith("_")+ if k not in {"reasoning", "response_format"}+ and not str(k).startswith("_")}if passthrough:existing = anthropic_kwargs.get("extra_body") or {}diff --git a/tests/agent/test_anthropic_structured_output.py b/tests/agent/test_anthropic_structured_output.pynew file mode 100644index 00000000000..eb504b6a550--- /dev/null+++ b/tests/agent/test_anthropic_structured_output.py@@ -0,0 +1,147 @@+"""Structured-output translation for Anthropic auxiliary calls."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from unittest.mock import MagicMock, patch+++def _capture_anthropic_kwargs(+ extra_body: dict, *, model: str = "claude-sonnet-4-6", async_call: bool = False,+) -> dict:+ from agent.auxiliary_client import (+ _AnthropicCompletionsAdapter,+ _AsyncAnthropicCompletionsAdapter,+ )++ captured = {}+ sync_adapter = _AnthropicCompletionsAdapter(+ MagicMock(name="anthropic_client"), model, is_oauth=False,+ )+ adapter = (+ _AsyncAnthropicCompletionsAdapter(sync_adapter)+ if async_call+ else sync_adapter+ )++ def _fake_create(_client, api_kwargs, **_kwargs):+ captured.update(api_kwargs)+ return SimpleNamespace()++ normalized = SimpleNamespace(+ content="ok",+ tool_calls=None,+ reasoning=None,+ finish_reason="stop",+ )+ with patch(+ "agent.anthropic_adapter.create_anthropic_message",+ side_effect=_fake_create,+ ), patch("agent.transports.get_transport") as mock_get_transport:+ mock_get_transport.return_value.normalize_response.return_value = normalized+ call = adapter.create(+ model=model,+ messages=[{"role": "user", "content": "hi"}],+ max_tokens=64,+ extra_body=extra_body,+ )+ if async_call:+ asyncio.run(call)++ return captured+++def _assert_no_raw_response_format(api_kwargs: dict) -> None:+ assert "response_format" not in api_kwargs+ assert "response_format" not in api_kwargs.get("extra_body", {})+++def test_json_schema_response_format_uses_native_output_config():+ schema = {+ "type": "object",+ "properties": {"title": {"type": "string"}},+ "required": ["title"],+ }+ api_kwargs = _capture_anthropic_kwargs({+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "thread_title",+ "schema": schema,+ "strict": False,+ },+ },+ })++ assert api_kwargs["output_config"]["format"] == {+ "type": "json_schema",+ "schema": schema,+ }+ _assert_no_raw_response_format(api_kwargs)+++def test_json_object_response_format_uses_permissive_object_schema():+ api_kwargs = _capture_anthropic_kwargs({+ "response_format": {"type": "json_object"},+ })++ assert api_kwargs["output_config"]["format"] == {+ "type": "json_schema",+ "schema": {"type": "object"},+ }+ _assert_no_raw_response_format(api_kwargs)+++def test_response_format_merges_with_adaptive_thinking_effort():+ schema = {"type": "object", "properties": {"ok": {"type": "boolean"}}}+ api_kwargs = _capture_anthropic_kwargs({+ "reasoning": {"enabled": True, "effort": "high"},+ "response_format": {+ "type": "json_schema",+ "json_schema": {"schema": schema},+ },+ })++ assert api_kwargs["output_config"] == {+ "effort": "high",+ "format": {"type": "json_schema", "schema": schema},+ }+ assert api_kwargs["thinking"] == {+ "type": "adaptive",+ "display": "summarized",+ }+ _assert_no_raw_response_format(api_kwargs)+++def test_unrelated_extra_body_keys_still_pass_through():+ api_kwargs = _capture_anthropic_kwargs({+ "response_format": {"type": "json_object"},+ "metadata": {"user_id": "thread-autotitle"},+ "vendor_option": True,+ })++ assert api_kwargs["extra_body"] == {+ "metadata": {"user_id": "thread-autotitle"},+ "vendor_option": True,+ }+ _assert_no_raw_response_format(api_kwargs)+++def test_async_anthropic_adapter_uses_the_same_translation():+ schema = {"type": "object"}+ api_kwargs = _capture_anthropic_kwargs(+ {+ "response_format": {+ "type": "json_schema",+ "json_schema": {"schema": schema},+ },+ },+ async_call=True,+ )++ assert api_kwargs["output_config"]["format"] == {+ "type": "json_schema",+ "schema": schema,+ }+ _assert_no_raw_response_format(api_kwargs)