Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(guardrails): write structured_messages rewrites back into /v1/responses input

mateo-berri429ad06972b7
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index 85fb0bc8dc6..63c66a4c2c5 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -931,7 +931,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
return OpenAiResponsesToChatCompletionStreamIterator(streaming_response, sync_stream, json_mode)
def _convert_content_str_to_input_text(self, content: str, role: str) -> dict[str, object]:
- if role == "user" or role == "system" or role == "tool":
+ if role in ("user", "system", "developer", "tool"):
return {"type": "input_text", "text": content}
else:
return {"type": "output_text", "text": content}
diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py
index 7c5d8ac99ad..4320edb8414 100644
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@ -38,6 +38,7 @@ from typing_extensions import ReadOnly, TypedDict
from litellm._logging import verbose_proxy_logger
from litellm.completion_extras.litellm_responses_transformation.transformation import (
+ LiteLLMResponsesTransformationHandler,
OpenAiResponsesToChatCompletionStreamIterator,
)
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
@@ -149,8 +150,15 @@ class OpenAIResponsesHandler(BaseTranslation):
input_type="request",
logging_obj=litellm_logging_obj,
)
- guardrailed_texts = guardrailed_inputs.get("texts", [])
- data["input"] = guardrailed_texts[0] if guardrailed_texts else input_data
+ guardrailed_structured_messages = guardrailed_inputs.get("structured_messages")
+ if (
+ guardrailed_structured_messages is not None
+ and guardrailed_structured_messages is not structured_messages
+ ):
+ self._write_back_structured_messages(data, guardrailed_structured_messages)
+ else:
+ guardrailed_texts = guardrailed_inputs.get("texts", [])
+ data["input"] = guardrailed_texts[0] if guardrailed_texts else input_data
self._apply_guardrailed_tools_to_data(data, original_tools, guardrailed_inputs.get("tools"))
verbose_proxy_logger.debug("OpenAI Responses API: Processed string input")
return data
@@ -198,24 +206,43 @@ class OpenAIResponsesHandler(BaseTranslation):
logging_obj=litellm_logging_obj,
)
- guardrailed_texts = guardrailed_inputs.get("texts", [])
self._apply_guardrailed_tools_to_data(
data,
original_tools_list,
guardrailed_inputs.get("tools"),
)
- # Step 3: Map guardrail responses back to original input structure
- await self._apply_guardrail_responses_to_input(
- messages=input_data,
- responses=guardrailed_texts,
- task_mappings=task_mappings,
- )
+ guardrailed_structured_messages = guardrailed_inputs.get("structured_messages")
+ if (
+ guardrailed_structured_messages is not None
+ and guardrailed_structured_messages is not structured_messages
+ ):
+ self._write_back_structured_messages(data, guardrailed_structured_messages)
+ else:
+ # Step 3: Map guardrail responses back to original input structure
+ await self._apply_guardrail_responses_to_input(
+ messages=input_data,
+ responses=guardrailed_inputs.get("texts", []),
+ task_mappings=task_mappings,
+ )
- verbose_proxy_logger.debug("OpenAI Responses API: Processed input messages: %s", input_data)
+ verbose_proxy_logger.debug("OpenAI Responses API: Processed input messages: %s", data.get("input"))
return data
+ @staticmethod
+ def _write_back_structured_messages(data: dict, structured_messages: Sequence[AllMessageValues]) -> None:
+ input_items, instructions = (
+ LiteLLMResponsesTransformationHandler().convert_chat_completion_messages_to_responses_api(
+ list(structured_messages)
+ )
+ )
+ data["input"] = input_items
+ if instructions is None:
+ data.pop("instructions", None)
+ return
+ data["instructions"] = instructions
+
def extract_request_tool_names(self, data: dict) -> list[str]:
"""Extract tool names from Responses API request (tools[].name for function
and custom, tools[].server_label for mcp)."""
diff --git a/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py b/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
index 21b60d7a216..6590718878d 100644
--- a/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
+++ b/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
@@ -1295,6 +1295,19 @@ def test_text_plus_tool_calls_sequence():
# =============================================================================
+def test_developer_message_content_uses_input_text():
+ handler = LiteLLMResponsesTransformationHandler()
+
+ input_items, instructions = handler.convert_chat_completion_messages_to_responses_api(
+ [{"role": "developer", "content": "Always answer in French."}]
+ )
+
+ assert instructions is None
+ assert input_items == [
+ {"type": "message", "role": "developer", "content": [{"type": "input_text", "text": "Always answer in French."}]}
+ ]
+
+
def test_tool_message_output_uses_input_text_not_output_text():
"""
Test that tool message content uses input_text type, not output_text.
diff --git a/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py b/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
index 447175b09a6..63f8babf760 100644
--- a/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
@@ -1229,3 +1229,99 @@ class TestOpenAIResponsesHandlerToolInjection:
names = [t.get("name") for t in result["tools"]]
assert "get_weather" in names
assert "injected_tool" in names
+
+
+COMPRESSED_MARKER = "[compressed document; retrieve the full text with hash=b573993006976af767214fac]"
+
+
+class StructuredRewriteGuardrail(CustomGuardrail):
+ """Guardrail that rewrites whole messages via structured_messages and leaves
+ texts untouched, the way message-compressing guardrails do."""
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ messages = list(inputs.get("structured_messages") or [])
+ first_user = next(i for i, m in enumerate(messages) if m.get("role") == "user")
+ rewritten = [
+ {**m, "content": COMPRESSED_MARKER} if i == first_user else m for i, m in enumerate(messages)
+ ]
+ return {**inputs, "structured_messages": rewritten}
+
+
+def _texts(item: dict) -> list[str]:
+ content = item.get("content")
+ if isinstance(content, str):
+ return [content]
+ return [part["text"] for part in content]
+
+
+class TestStructuredMessagesWriteBack:
+ """A guardrail's structured_messages rewrite must land in the Responses request,
+ not only the per-text mapping the chat handler shares with it."""
+
+ @pytest.mark.asyncio
+ async def test_list_input_gets_rewritten_messages_and_keeps_instructions(self):
+ handler = OpenAIResponsesHandler()
+ data = {
+ "model": "gpt-5.6",
+ "instructions": "Answer from the memo only.",
+ "input": [
+ {"role": "user", "content": "memo " * 400},
+ {"role": "assistant", "content": "Understood."},
+ {"role": "user", "content": "What is the codename?"},
+ ],
+ }
+
+ result = await handler.process_input_messages(data, StructuredRewriteGuardrail())
+
+ assert result["instructions"] == "Answer from the memo only."
+ user_items = [item for item in result["input"] if item.get("role") == "user"]
+ assert [_texts(item) for item in user_items] == [[COMPRESSED_MARKER], ["What is the codename?"]]
+ assert not any(item.get("role") == "system" for item in result["input"])
+ assert _texts(next(item for item in result["input"] if item.get("role") == "assistant")) == ["Understood."]
+
+ @pytest.mark.asyncio
+ async def test_string_input_becomes_rewritten_message_list(self):
+ handler = OpenAIResponsesHandler()
+ data = {"model": "gpt-5.6", "input": "memo " * 400}
+
+ result = await handler.process_input_messages(data, StructuredRewriteGuardrail())
+
+ assert [_texts(item) for item in result["input"]] == [[COMPRESSED_MARKER]]
+ assert "instructions" not in result
+
+ @pytest.mark.asyncio
+ async def test_developer_item_survives_write_back_as_input_text(self):
+ handler = OpenAIResponsesHandler()
+ data = {
+ "model": "gpt-5.6",
+ "input": [
+ {"role": "developer", "content": "Always answer in French."},
+ {"role": "user", "content": "memo " * 400},
+ {"role": "user", "content": "What is the codename?"},
+ ],
+ }
+
+ result = await handler.process_input_messages(data, StructuredRewriteGuardrail())
+
+ developer = next(item for item in result["input"] if item.get("role") == "developer")
+ assert developer["content"] == [{"type": "input_text", "text": "Always answer in French."}]
+
+ @pytest.mark.asyncio
+ async def test_same_inputs_object_back_keeps_the_text_mapping(self):
+ handler = OpenAIResponsesHandler()
+ original_input = [
+ {"role": "user", "content": "Hello"},
+ {"role": "user", "content": [{"type": "input_text", "text": "Again"}]},
+ ]
+ data = {"model": "gpt-5.6", "input": original_input}
+
+ result = await handler.process_input_messages(data, MockGuardrail())
+
+ assert result["input"] is original_input
+ assert [_texts(item) for item in result["input"]] == [["Hello [GUARDRAILED]"], ["Again [GUARDRAILED]"]]
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
index 1fbc975e40a..37b9852d3e1 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
@@ -954,6 +954,40 @@ async def test_passthrough_handler_does_not_log_headroom_as_run(
assert "headroom" not in _applied_guardrails(data)
+async def test_responses_request_sends_compressed_input_and_retrieve_tool_upstream(
+ guardrail: HeadroomGuardrail,
+):
+ """Regression for LIT-6494: on /v1/responses the compressed messages must be
+ written back into `input`, not only the retrieve tool into `tools`, or the
+ model keeps reading the full document and never calls headroom_retrieve."""
+ from litellm.llms.openai.responses.guardrail_translation.handler import OpenAIResponsesHandler
+
+ data = {
+ "model": "gpt-5.6",
+ "instructions": ORIGINAL_MESSAGES[0]["content"],
+ "input": [{"role": m["role"], "content": m["content"]} for m in ORIGINAL_MESSAGES[1:]],
+ "tools": [{"type": "function", "name": "get_weather", "parameters": {"type": "object", "properties": {}}}],
+ }
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=_make_compress_response(COMPRESSED_MESSAGES_WITH_HASH),
+ ):
+ result = await OpenAIResponsesHandler().process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert result["instructions"] == ORIGINAL_MESSAGES[0]["content"]
+ assert [item["content"][0]["text"] for item in result["input"]] == [
+ COMPRESSED_MESSAGES_WITH_HASH[0]["content"],
+ ORIGINAL_MESSAGES[2]["content"],
+ ORIGINAL_MESSAGES[3]["content"],
+ ]
+ assert "A" * 5000 not in json.dumps(result["input"])
+ assert [tool["name"] for tool in result["tools"]] == ["get_weather", HEADROOM_RETRIEVE_TOOL_NAME]
+
+
@pytest.mark.asyncio
async def test_apply_guardrail_http_error_raises():
guardrail = _make_guardrail()