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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
merge: litellm_internal_staging into litellm_headroom_ccr_streaming_responses
yassin6d5a3ab42c18
diff --cc litellm/llms/openai/responses/guardrail_translation/handler.pyindex fb8fac02108,5a5970fb867..0c19ecf909e--- a/litellm/llms/openai/responses/guardrail_translation/handler.py+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py@@@ -32,12 -33,10 +33,11 @@@ import timimport uuidfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclass+from itertools import accumulatefrom types import MappingProxyType-from typing import TYPE_CHECKING, Any, Final, Union, cast+from typing import TYPE_CHECKING, Any, Final, NamedTuple, Union, castfrom openai.types.responses.response_function_tool_call import ResponseFunctionToolCall- from openai.types.responses.tool_param import FunctionToolParamfrom pydantic import BaseModel, TypeAdapterfrom typing_extensions import ReadOnly, TypedDict@@@ -353,92 -157,105 +353,101 @@@ class OpenAIResponsesHandler(BaseTranslHandles both string input and list of message objects."""input_data: Final[str | ResponseInputParam | None] = data.get("input")- if input_data is None:+ if not isinstance(input_data, (str, list)):return data-structured_messages: Final = self.get_structured_messages(data)- extracted: Final = self._extract_guardrail_inputs(data, input_data)+ raw_tools: Final = data.get("tools")+ original_tools: Final[tuple[Mapping[str, object], ...]] = (+ tuple(raw_tools) if isinstance(raw_tools, list) else ()+ )+ flattened_tool_groups: Final = tuple(+ form.chat_tools for form in LiteLLMCompletionResponsesConfig.responses_tools_to_chat_forms(original_tools)+ )- flattened_tools: Final = tuple(- cast(ChatCompletionToolParam, tool) # cast-ok: mcp tools ride along in the guardrail's tool list- for group in flattened_tool_groups- for tool in group- )- tools_to_check: Final[list[ChatCompletionToolParam]] = list( # mutable-ok: guardrail inputs want a list- copy.deepcopy(flattened_tools)++ extracted: Final = self._extract_guardrail_inputs(data, input_data, flattened_tool_groups)+ if not extracted.inputs.get("texts"):+ return data+ if structured_messages:+ extracted.inputs["structured_messages"] = structured_messages- original_tools: Final[list[dict[str, object]]] = list(data.get("tools") or [])+ guardrailed_inputs: Final = await guardrail_to_apply.apply_guardrail(+ inputs=extracted.inputs,+ request_data=data,+ input_type="request",+ logging_obj=litellm_logging_obj,)- self._apply_guardrailed_tools_to_data(data, original_tools, guardrailed_inputs.get("tools"))-- # Handle simple string input- if isinstance(input_data, str):- inputs = GenericGuardrailAPIInputs(texts=[input_data])- if tools_to_check:- inputs["tools"] = tools_to_check- if structured_messages:- inputs["structured_messages"] = structured_messages- # Include model information if available- model = data.get("model")- if model:- inputs["model"] = model-- guardrailed_inputs = await guardrail_to_apply.apply_guardrail(- inputs=inputs,- request_data=data,- 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- self._apply_guardrailed_tools_to_data(- data, original_tools, flattened_tool_groups, guardrailed_inputs.get("tools")++ self._apply_guardrailed_tools_to_data(data, original_tools, flattened_tool_groups, guardrailed_inputs.get("tools"))+ written_back: Final = self._written_back_request_fields(data, structured_messages, guardrailed_inputs)+ if written_back is not None:+ data["input"] = list(written_back.input) # mutable-ok: JSON body+ if written_back.instructions is None:+ data.pop("instructions", None)+ else:+ data["instructions"] = written_back.instructions # rebind-ok: data is an out-param+ elif isinstance(input_data, str):+ guardrailed_texts: Final = guardrailed_inputs.get("texts") or ()+ data["input"] = guardrailed_texts[0] if guardrailed_texts else input_data # rebind-ok: data is an out-param+ else:+ await self._apply_guardrail_responses_to_input(+ messages=input_data,+ responses=guardrailed_inputs.get("texts") or (),+ task_mappings=extracted.task_mappings,)- verbose_proxy_logger.debug("OpenAI Responses API: Processed string input")- return data-- # Handle list input (ResponseInputParam)- if not isinstance(input_data, list):- return data+ verbose_proxy_logger.debug("OpenAI Responses API: Processed input messages: %s", data.get("input"))+ return data+ def _extract_guardrail_inputs(+ self,+ data: Mapping[str, object],+ input_data: "str | ResponseInputParam",++ flattened_tool_groups: Sequence[Sequence[Mapping[str, object]]],+ ) -> _ExtractedInputs:texts_to_check: Final[list[str]] = []images_to_check: Final[list[str]] = []task_mappings: Final[list[tuple[int, int | None]]] = []- tools_to_check: Final[list[ChatCompletionToolParam]] = []-- # Step 1: Extract all text content, images, and tools- for msg_idx, message in enumerate(input_data):- self._extract_input_text_and_images(- message=message,- msg_idx=msg_idx,- texts_to_check=texts_to_check,- images_to_check=images_to_check,- task_mappings=task_mappings,- )-- # Step 2: Apply guardrail to all texts in batch- if texts_to_check:- inputs = GenericGuardrailAPIInputs(texts=texts_to_check)- if images_to_check:- inputs["images"] = images_to_check- if tools_to_check:- inputs["tools"] = tools_to_check- if structured_messages:- inputs["structured_messages"] = structured_messages- # Include model information if available- model = data.get("model")- if model:- inputs["model"] = model- guardrailed_inputs = await guardrail_to_apply.apply_guardrail(- inputs=inputs,- request_data=data,- input_type="request",- logging_obj=litellm_logging_obj,- )-- guardrailed_texts = guardrailed_inputs.get("texts", [])- self._apply_guardrailed_tools_to_data(- data, original_tools, flattened_tool_groups, 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,++ tools_to_check: Final[list[ChatCompletionToolParam]] = list( # mutable-ok: guardrail inputs want a list++ copy.deepcopy(++ tuple(++ cast(ChatCompletionToolParam, tool) # cast-ok: mcp tools ride along in the guardrail's tool list++ for group in flattened_tool_groups++ for tool in group++ )+ )-- verbose_proxy_logger.debug("OpenAI Responses API: Processed input messages: %s", input_data)-- return data++ )+ if isinstance(input_data, str):+ texts_to_check.append(input_data)+ else:+ for msg_idx, message in enumerate(input_data):+ self._extract_input_text_and_images(+ message=message,+ msg_idx=msg_idx,+ texts_to_check=texts_to_check,+ images_to_check=images_to_check,+ task_mappings=task_mappings,+ )- tools: Final = data.get("tools")- if tools:- self._extract_and_transform_tools(- cast("list[FunctionToolParam | OpenAIMcpServerTool]", tools), # cast-ok: request body tools- tools_to_check,- )+ inputs: Final = GenericGuardrailAPIInputs(texts=texts_to_check)+ if images_to_check:+ inputs["images"] = images_to_check+ if tools_to_check:+ inputs["tools"] = tools_to_check+ model: Final = data.get("model")+ if isinstance(model, str):+ inputs["model"] = model+ return _ExtractedInputs(inputs=inputs, task_mappings=tuple(task_mappings))++ @staticmethod+ def _written_back_request_fields(+ data: Mapping[str, object],+ structured_messages: Sequence[AllMessageValues] | None,+ guardrailed_inputs: GenericGuardrailAPIInputs,+ ) -> _RequestFields | None:+ guardrailed: Final = guardrailed_inputs.get("structured_messages")+ if guardrailed is None or guardrailed is structured_messages:+ return None+ return _patch_or_convert_request_fields(+ data.get("input"),+ data.get("instructions"),+ structured_messages or (),+ guardrailed,+ )def extract_request_tool_names(self, data: dict) -> list[str]:"""Extract tool names from Responses API request (tools[].name for functiondiff --cc tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.pyindex 450b3538944,d071ef78c2d..568effe580e--- 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@@@ -1323,523 -1329,194 +1329,711 @@@ class TestOpenAIResponsesHandlerToolInjassert "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}+++class ToolOutputRewriteGuardrail(CustomGuardrail):+ """Guardrail that compresses the first tool-result row, the way Headroom does."""++ 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_tool = next(i for i, m in enumerate(messages) if isinstance(m, dict) and m.get("role") == "tool")+ rewritten = [+ {**m, "content": COMPRESSED_MARKER} if i == first_tool else m for i, m in enumerate(messages)+ ]+ return {**inputs, "structured_messages": rewritten}+++class DroppingRewriteGuardrail(CustomGuardrail):+ """Guardrail that rewrites the first user row and drops the last row, so the+ rewrite can only land through the full-conversion fallback."""++ 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 isinstance(m, dict) and 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[:-1]}+++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_preserved_verbatim_by_row_patch(self):+ handler = OpenAIResponsesHandler()+ developer_item = {"role": "developer", "content": "Always answer in French."}+ data = {+ "model": "gpt-5.6",+ "input": [+ developer_item,+ {"role": "user", "content": "memo " * 400},+ {"role": "user", "content": "What is the codename?"},+ ],+ }++ result = await handler.process_input_messages(data, StructuredRewriteGuardrail())++ assert result["input"][0] is developer_item+ assert developer_item["content"] == "Always answer in French."+ assert _texts(result["input"][1]) == [COMPRESSED_MARKER]+ assert _texts(result["input"][2]) == ["What is the codename?"]++ @pytest.mark.asyncio+ async def test_reasoning_and_function_call_items_survive_tool_output_compression(self):+ handler = OpenAIResponsesHandler()+ reasoning_item = {+ "id": "rs_123",+ "type": "reasoning",+ "summary": [],+ "encrypted_content": "gAAAAA-signed-reasoning",+ }+ function_call_item = {+ "id": "fc_123",+ "type": "function_call",+ "call_id": "call_abc",+ "name": "read_document",+ "arguments": '{"path": "memo.txt"}',+ "status": "completed",+ }+ data = {+ "model": "gpt-5.6",+ "instructions": "Answer from the memo only.",+ "input": [+ reasoning_item,+ function_call_item,+ {"type": "function_call_output", "call_id": "call_abc", "output": "memo " * 400},+ {"role": "user", "content": "What is the codename?"},+ ],+ }++ result = await handler.process_input_messages(data, ToolOutputRewriteGuardrail())++ assert result["instructions"] == "Answer from the memo only."+ assert result["input"][0] is reasoning_item+ assert reasoning_item["encrypted_content"] == "gAAAAA-signed-reasoning"+ assert result["input"][1] is function_call_item+ assert function_call_item["id"] == "fc_123"+ assert result["input"][2] == {+ "type": "function_call_output",+ "call_id": "call_abc",+ "output": COMPRESSED_MARKER,+ }+ assert result["input"][3] == {"role": "user", "content": "What is the codename?"}++ @pytest.mark.asyncio+ async def test_web_search_call_item_preserved_verbatim(self):+ handler = OpenAIResponsesHandler()+ web_search_item = {+ "id": "ws_123",+ "type": "web_search_call",+ "status": "completed",+ "action": {"type": "search", "query": "codename memo"},+ }+ data = {+ "model": "gpt-5.6",+ "input": [+ web_search_item,+ {"role": "user", "content": "memo " * 400},+ {"role": "user", "content": "What is the codename?"},+ ],+ }++ result = await handler.process_input_messages(data, StructuredRewriteGuardrail())++ assert result["input"][0] is web_search_item+ assert _texts(result["input"][1]) == [COMPRESSED_MARKER]+ assert _texts(result["input"][2]) == ["What is the codename?"]++ @pytest.mark.asyncio+ async def test_row_count_change_falls_back_to_full_conversion(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, DroppingRewriteGuardrail())++ assert len(result["input"]) == 2+ developer = next(item for item in result["input"] if item.get("role") == "developer")+ assert developer["content"] == [{"type": "input_text", "text": "Always answer in French."}]+ assert _texts(next(item for item in result["input"] if item.get("role") == "user")) == [COMPRESSED_MARKER]++ @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]"]]+++class AllToolOutputsRewriteGuardrail(CustomGuardrail):+ """Guardrail that compresses every tool-result row."""++ 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 [])+ rewritten = [+ {**m, "content": COMPRESSED_MARKER} if isinstance(m, dict) and m.get("role") == "tool" else m+ for m in messages+ ]+ return {**inputs, "structured_messages": rewritten}+++class AssistantRewriteGuardrail(CustomGuardrail):+ """Guardrail that rewrites the first assistant row's content."""++ 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 = next(i for i, m in enumerate(messages) if isinstance(m, dict) and m.get("role") == "assistant")+ rewritten = [{**m, "content": COMPRESSED_MARKER} if i == first else m for i, m in enumerate(messages)]+ return {**inputs, "structured_messages": rewritten}+++class DictStructuredMessagesGuardrail(CustomGuardrail):+ """Guardrail that hands back a raw evaluation dict instead of a message list,+ the way HiddenLayer v2 does."""++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+ input_type: Literal["request", "response"],+ logging_obj: Optional[Any] = None,+ ) -> GenericGuardrailAPIInputs:+ return {**inputs, "structured_messages": {"evaluation": "allowed", "messages": []}}+++def _parallel_tool_call_input() -> list:+ return [+ {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "read_a", "arguments": "{}"},+ {"id": "fc_2", "type": "function_call", "call_id": "call_2", "name": "read_b", "arguments": "{}"},+ {"type": "function_call_output", "call_id": "call_1", "output": "memo " * 400},+ {"type": "function_call_output", "call_id": "call_2", "output": "note " * 400},+ {"role": "user", "content": "What is the codename?"},+ ]+++class TestProvenancePatching:+ """The O(n) provenance pass must keep patching rewritten rows in place for the+ shapes real agent loops produce, and fall back safely everywhere else."""++ @pytest.mark.asyncio+ async def test_parallel_tool_call_outputs_both_patched(self):+ handler = OpenAIResponsesHandler()+ raw_input = _parallel_tool_call_input()+ fc_1, fc_2 = raw_input[0], raw_input[1]+ data = {"model": "gpt-5.6", "input": raw_input}++ result = await handler.process_input_messages(data, AllToolOutputsRewriteGuardrail())++ assert result["input"][0] is fc_1+ assert result["input"][1] is fc_2+ assert result["input"][2] == {"type": "function_call_output", "call_id": "call_1", "output": COMPRESSED_MARKER}+ assert result["input"][3] == {"type": "function_call_output", "call_id": "call_2", "output": COMPRESSED_MARKER}+ assert result["input"][4] == {"role": "user", "content": "What is the codename?"}++ @pytest.mark.asyncio+ async def test_assistant_turn_with_tool_call_keeps_items_verbatim(self):+ handler = OpenAIResponsesHandler()+ assistant_item = {"role": "assistant", "content": "Let me read the memo."}+ function_call_item = {+ "id": "fc_9",+ "type": "function_call",+ "call_id": "call_9",+ "name": "read_document",+ "arguments": '{"path": "memo.txt"}',+ }+ data = {+ "model": "gpt-5.6",+ "input": [+ assistant_item,+ function_call_item,+ {"type": "function_call_output", "call_id": "call_9", "output": "memo " * 400},+ {"role": "user", "content": "What is the codename?"},+ ],+ }++ result = await handler.process_input_messages(data, ToolOutputRewriteGuardrail())++ assert result["input"][0] is assistant_item+ assert result["input"][1] is function_call_item+ assert result["input"][2] == {"type": "function_call_output", "call_id": "call_9", "output": COMPRESSED_MARKER}++ @pytest.mark.asyncio+ async def test_rewrite_of_merged_tool_call_message_falls_back(self):+ handler = OpenAIResponsesHandler()+ raw_input = _parallel_tool_call_input()+ data = {"model": "gpt-5.6", "input": raw_input}++ result = await handler.process_input_messages(data, AssistantRewriteGuardrail())++ assert not any(item is original for item in result["input"] for original in raw_input)+ assistant_items = [item for item in result["input"] if item.get("role") == "assistant"]+ assert [_texts(item) for item in assistant_items] == [[COMPRESSED_MARKER]]++ @pytest.mark.asyncio+ async def test_rewrite_of_lone_function_call_message_falls_back(self):+ handler = OpenAIResponsesHandler()+ data = {+ "model": "gpt-5.6",+ "input": [+ {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "read_a", "arguments": "{}"},+ {"type": "function_call_output", "call_id": "call_1", "output": "memo memo"},+ {"role": "user", "content": "What is the codename?"},+ ],+ }++ raw_input = data["input"]+ result = await handler.process_input_messages(data, AssistantRewriteGuardrail())++ assert not any(item is original for item in result["input"] for original in raw_input)+ assistant_items = [item for item in result["input"] if item.get("role") == "assistant"]+ assert [_texts(item) for item in assistant_items] == [[COMPRESSED_MARKER]]++ def test_provenance_bails_on_non_mapping_item(self):+ from litellm.llms.openai.responses.guardrail_translation.handler import _input_item_provenance++ assert _input_item_provenance(["not a mapping"], []) is None++ def test_provenance_bails_when_expected_messages_disagree(self):+ from litellm.llms.openai.responses.guardrail_translation.handler import _input_item_provenance++ assert _input_item_provenance([{"role": "user", "content": "hi"}], [{"role": "user", "content": "bye"}]) is None++ def test_provenance_bails_on_unpredicted_merge(self):+ from litellm.llms.openai.responses.guardrail_translation.handler import _input_item_provenance+ from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+ )++ raw_input = [+ {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "read_a", "arguments": "{}"},+ {"role": "assistant", "content": "Reading the memo now."},+ ]+ expected = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=raw_input, responses_api_request={}+ )+ assert len(expected) == 1+ assert _input_item_provenance(raw_input, expected) is None++ def test_provenance_maps_and_taints_parallel_tool_calls(self):+ from litellm.llms.openai.responses.guardrail_translation.handler import _input_item_provenance+ from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+ )++ raw_input = _parallel_tool_call_input()+ expected = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=raw_input, responses_api_request={}+ )+ provenance = _input_item_provenance(raw_input, expected)+ assert provenance is not None+ item_for_message, tainted = provenance+ assert tainted == {0}+ assert dict(item_for_message) == {1: 2, 2: 3, 3: 4}+++class TestDictStructuredMessagesGuard:+ """A guardrail handing back a non-list structured_messages payload must not+ blow up the request; the write-back is skipped instead."""++ @pytest.mark.asyncio+ async def test_list_input_survives_dict_structured_messages(self):+ handler = OpenAIResponsesHandler()+ original_input = [{"role": "user", "content": "Hello"}]+ data = {"model": "gpt-5.6", "input": original_input}++ result = await handler.process_input_messages(data, DictStructuredMessagesGuardrail())++ assert result["input"] is original_input+ assert result["input"] == [{"role": "user", "content": "Hello"}]++ @pytest.mark.asyncio+ async def test_string_input_survives_dict_structured_messages(self):+ handler = OpenAIResponsesHandler()+ data = {"model": "gpt-5.6", "input": "Hello there"}++ result = await handler.process_input_messages(data, DictStructuredMessagesGuardrail())++ assert result["input"] == "Hello there"+++class SystemRewriteGuardrail(CustomGuardrail):+ """Guardrail that rewrites the system row, the way prompt-hardening guardrails do."""++ def __init__(self, rewritten_content: Any = COMPRESSED_MARKER):+ super().__init__()+ self.rewritten_content = rewritten_content++ 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 = next(i for i, m in enumerate(messages) if isinstance(m, dict) and m.get("role") == "system")+ rewritten = [+ {**m, "content": self.rewritten_content} if i == first else m for i, m in enumerate(messages)+ ]+ return {**inputs, "structured_messages": rewritten}+++class TestPatchEdgeBranches:+ @pytest.mark.asyncio+ async def test_multimodal_user_item_rewritten_through_conversion(self):+ handler = OpenAIResponsesHandler()+ data = {+ "model": "gpt-5.6",+ "input": [+ {"role": "user", "content": [{"type": "input_text", "text": "memo " * 400}]},+ {"role": "user", "content": "What is the codename?"},+ ],+ }++ result = await handler.process_input_messages(data, StructuredRewriteGuardrail())++ assert _texts(result["input"][0]) == [COMPRESSED_MARKER]+ assert result["input"][1] == {"role": "user", "content": "What is the codename?"}++ @pytest.mark.asyncio+ async def test_instructions_rewrite_lands_in_instructions_field(self):+ handler = OpenAIResponsesHandler()+ user_item = {"role": "user", "content": "What is the codename?"}+ data = {+ "model": "gpt-5.6",+ "instructions": "Answer from the memo only.",+ "input": [user_item],+ }++ result = await handler.process_input_messages(data, SystemRewriteGuardrail())++ assert result["instructions"] == COMPRESSED_MARKER+ assert result["input"][0] is user_item++ @pytest.mark.asyncio+ async def test_non_string_instructions_rewrite_falls_back(self):+ handler = OpenAIResponsesHandler()+ user_item = {"role": "user", "content": "What is the codename?"}+ data = {+ "model": "gpt-5.6",+ "instructions": "Answer from the memo only.",+ "input": [user_item],+ }++ result = await handler.process_input_messages(+ data, SystemRewriteGuardrail(rewritten_content=[{"type": "text", "text": COMPRESSED_MARKER}])+ )++ assert result["input"][0] is not user_item++ @pytest.mark.asyncio+ async def test_unpredicted_merge_falls_back_through_patch(self):+ handler = OpenAIResponsesHandler()+ raw_input = [+ {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "read_a", "arguments": "{}"},+ {"role": "assistant", "content": "Reading the memo now."},+ {"type": "function_call_output", "call_id": "call_1", "output": "memo memo"},+ {"role": "user", "content": "memo " * 400},+ ]+ data = {"model": "gpt-5.6", "input": raw_input}++ result = await handler.process_input_messages(data, StructuredRewriteGuardrail())++ assert not any(item is original for item in result["input"] for original in raw_input)+ user_items = [item for item in result["input"] if item.get("role") == "user"]+ assert _texts(user_items[0]) == [COMPRESSED_MARKER]++ def test_item_rewrite_field_ignores_non_string_type(self):+ from litellm.llms.openai.responses.guardrail_translation.handler import _item_rewrite_field++ assert _item_rewrite_field({"type": 123, "content": "hello"}) is None+++ class ToolEditingGuardrail(CustomGuardrail):+ """Guardrail that rewrites the flattened chat tools it was handed through ``edit``"""++ def __init__(self, edit: Callable[[list[dict]], list[dict]], **kwargs):+ super().__init__(**kwargs)+ self.edit = edit++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+ input_type: Literal["request", "response"],+ logging_obj: Any | None = None,+ ) -> GenericGuardrailAPIInputs:+ inputs["tools"] = self.edit(list(inputs.get("tools") or []))+ return inputs+++ def _codex_request(input_value):+ """A Responses API request shaped like what the Codex CLI sends when an MCP server is configured"""+ return {+ "model": "gpt-5.3-codex",+ "input": input_value,+ "tools": [+ {+ "type": "function",+ "name": "get_weather",+ "description": "Weather lookup",+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}},+ "strict": False,+ },+ {+ "type": "namespace",+ "name": "mcp__confluence",+ "description": "Confluence tools",+ "tools": [+ {+ "type": "function",+ "name": "confluence_get_page",+ "description": "Get a page",+ "parameters": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},+ "strict": False,+ },+ {+ "type": "function",+ "name": "confluence_search",+ "description": "Search pages",+ "parameters": {"type": "object", "properties": {"q": {"type": "string"}}},+ "strict": False,+ },+ ],+ },+ {+ "type": "custom",+ "name": "apply_patch",+ "description": "Apply a patch",+ "format": {"type": "grammar", "syntax": "lark", "definition": 'start: "x"'},+ },+ {"type": "web_search"},+ ],+ }+++ def _tool_named(tools, name):+ return next(tool for tool in tools if tool.get("name") == name)+++ class TestOpenAIResponsesHandlerNamespaceTools:+ """Codex sends MCP tools as ``namespace`` tools; a guardrail must never flatten them (GH #39183)"""++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "input_value",+ ["hi", [{"role": "user", "content": "hi", "type": "message"}]],+ ids=["string_input", "list_input"],+ )+ async def test_pass_through_guardrail_leaves_tools_untouched(self, input_value):+ data = _codex_request(input_value)+ expected_tools = copy.deepcopy(data["tools"])++ result = await OpenAIResponsesHandler().process_input_messages(+ data, MockPassThroughGuardrail(guardrail_name="test")+ )++ assert result["tools"] == expected_tools++ @pytest.mark.asyncio+ async def test_appending_guardrail_keeps_namespace_and_adds_tool(self):+ data = _codex_request("hi")+ expected_tools = copy.deepcopy(data["tools"])++ result = await OpenAIResponsesHandler().process_input_messages(+ data, ToolAppendingGuardrail(guardrail_name="test")+ )++ assert result["tools"][:-1] == expected_tools+ assert result["tools"][-1]["type"] == "function"+ assert result["tools"][-1]["name"] == "injected_tool"++ @pytest.mark.asyncio+ async def test_dropping_one_member_prunes_only_that_member(self):+ data = _codex_request("hi")+ expected_tools = copy.deepcopy(data["tools"])+ guardrail = ToolEditingGuardrail(+ edit=lambda tools: [t for t in tools if t["function"]["name"] != "mcp__confluence__confluence_search"],+ guardrail_name="test",+ )++ result = await OpenAIResponsesHandler().process_input_messages(data, guardrail)++ namespace = _tool_named(result["tools"], "mcp__confluence")+ assert [member["name"] for member in namespace["tools"]] == ["confluence_get_page"]+ assert namespace["tools"][0] == expected_tools[1]["tools"][0]+ assert [t for t in result["tools"] if t is not namespace] == [expected_tools[0], *expected_tools[2:]]++ @pytest.mark.asyncio+ async def test_editing_a_member_lands_on_that_member_without_the_namespace_prefix(self):+ data = _codex_request("hi")+ expected_tools = copy.deepcopy(data["tools"])++ def redact_search(tools):+ for tool in tools:+ if tool["function"]["name"] == "mcp__confluence__confluence_search":+ tool["function"]["description"] = "Confluence tools\n\nREDACTED"+ return tools++ result = await OpenAIResponsesHandler().process_input_messages(+ data, ToolEditingGuardrail(edit=redact_search, guardrail_name="test")+ )++ namespace = _tool_named(result["tools"], "mcp__confluence")+ assert namespace["tools"][0] == expected_tools[1]["tools"][0]+ assert namespace["tools"][1] == {**expected_tools[1]["tools"][1], "description": "REDACTED"}+ assert {k: v for k, v in namespace.items() if k != "tools"} == {+ k: v for k, v in expected_tools[1].items() if k != "tools"+ }++ @pytest.mark.asyncio+ async def test_dropping_every_member_drops_the_namespace(self):+ data = _codex_request("hi")+ expected_tools = copy.deepcopy(data["tools"])+ guardrail = ToolEditingGuardrail(+ edit=lambda tools: [t for t in tools if not t["function"]["name"].startswith("mcp__confluence__")],+ guardrail_name="test",+ )++ result = await OpenAIResponsesHandler().process_input_messages(data, guardrail)++ assert result["tools"] == [expected_tools[0], *expected_tools[2:]]++ @pytest.mark.asyncio+ async def test_edited_top_level_function_is_rewritten_in_place(self):+ data = _codex_request("hi")+ expected_tools = copy.deepcopy(data["tools"])++ def rename_weather(tools):+ for tool in tools:+ if tool["function"]["name"] == "get_weather":+ tool["function"]["description"] = "Weather lookup (guarded)"+ return tools++ result = await OpenAIResponsesHandler().process_input_messages(+ data, ToolEditingGuardrail(edit=rename_weather, guardrail_name="test")+ )++ assert result["tools"][0] == {**expected_tools[0], "description": "Weather lookup (guarded)"}+ assert result["tools"][1:] == expected_tools[1:]+++ class TestOpenAIResponsesHandlerMalformedTools:+ @pytest.mark.asyncio+ async def test_request_tools_that_are_not_a_list_never_reach_the_guardrail(self):+ handler = OpenAIResponsesHandler()+ seen: list[list[dict]] = []++ def record(tools):+ seen.append(tools)+ return tools++ guardrail = ToolEditingGuardrail(edit=record, guardrail_name="test")+ data = {"input": "hi", "tools": {"type": "function", "name": "get_weather"}}++ result = await handler.process_input_messages(data, guardrail)++ assert seen == [[]]+ assert result["input"] == "hi"++class TestBuildBlockSseChunks:"""build_block_sse_chunks turns a streaming ModifyResponseException into 200 SSE events"""