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 remote-tracking branch 'origin/litellm_internal_staging' into litellm_headroom_ccr_streaming_responses
mateo-berri4a5d0b81638f
diff --cc litellm/llms/openai/responses/guardrail_translation/handler.pyindex b70b5539eca,1530c154e93..fb8fac02108--- a/litellm/llms/openai/responses/guardrail_translation/handler.py+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py@@@ -28,10 -28,12 +28,13 @@@ Output: response.output is List[Generic- text: str"""+ import time+ import uuidfrom collections.abc import Mapping, Sequence+ from 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 ResponseFunctionToolCallfrom openai.types.responses.tool_param import FunctionToolParam@@@ -54,8 -63,15 +65,16 @@@ from litellm.types.llms.openai importErrorEvent,ErrorEventError,OpenAIMcpServerTool,+ OutputItemAddedEvent,+ OutputItemDoneEvent,+ OutputTextDeltaEvent,+ OutputTextDoneEvent,+ ResponseAPIUsage,+ ResponseCompletedEvent,+ ResponsesAPIOptionalRequestParams,+ ResponsesAPIResponse,ResponsesAPIStreamEvents,+ ResponsesAPIStreamingResponse,)from litellm.types.responses.main import (GenericResponseOutputItem,@@@ -86,201 -104,12 +107,205 @@@ class ResponsesStreamChunk(TypedDict, ttype: ReadOnly[str]text: ReadOnly[str]+ delta: ReadOnly[str]+ item_id: ReadOnly[str]+ output_index: ReadOnly[int]+ content_index: ReadOnly[int]+_PATCHABLE_ITEM_FIELDS: Final[Mapping[str, str]] = MappingProxyType(+ {"function_call_output": "output", "message": "content"}+)++_EMPTY_RESPONSES_REQUEST: Final[ResponsesAPIOptionalRequestParams] = {}+++def _item_rewrite_field(item: Mapping[str, object]) -> str | None:+ item_type: Final = item.get("type")+ if item_type is None:+ return "content" if "content" in item else None+ if not isinstance(item_type, str):+ return None+ return _PATCHABLE_ITEM_FIELDS.get(item_type)+++def _rewritten_input_item(item: Mapping[str, object], rewritten: object) -> Mapping[str, object] | None:+ field: Final = _item_rewrite_field(item)+ if field is None or not isinstance(rewritten, Mapping):+ return None+ rewritten_content: Final = rewritten.get("content")+ if isinstance(item.get(field), str) and isinstance(rewritten_content, str):+ return {**item, field: rewritten_content} # mutable-ok: request input items must stay JSON-plain dicts+ rewritten_row: Final = cast("AllMessageValues", rewritten) # cast-ok: guardrails hand back chat-shaped rows+ converted_items, _ = LiteLLMResponsesTransformationHandler().convert_chat_completion_messages_to_responses_api(+ [rewritten_row] # mutable-ok: converter signature takes a list+ )+ if len(converted_items) != 1 or not isinstance(converted_items[0], Mapping):+ return None+ first_converted: Final = cast("Mapping[str, object]", converted_items[0]) # cast-ok: isinstance-checked above+ converted_value: Final = first_converted.get(field)+ if converted_value is None:+ return None+ return {**item, field: converted_value} # mutable-ok: request input items must stay JSON-plain dicts+++def _is_function_call_item(item: object) -> bool:+ return isinstance(item, Mapping) and item.get("type") in ("function_call", "custom_tool_call")+++def _last_message_role(messages: Sequence[object]) -> str | None:+ if not messages:+ return None+ last: Final = messages[-1]+ role: Final = last.get("role") if isinstance(last, Mapping) else getattr(last, "role", None)+ return role if isinstance(role, str) else None+++def _provenance_unit_bounds(+ raw_input: Sequence[object],+ solo_conversions: Sequence[Sequence[object]],+) -> tuple[tuple[int, int], ...]:+ trailing_roles: Final = tuple(+ accumulate(+ (_last_message_role(messages) for messages in solo_conversions),+ lambda previous, current: current if current is not None else previous,+ )+ )+ start_indexes: Final = tuple(+ index+ for index in range(len(raw_input))+ if index == 0 or not (_is_function_call_item(raw_input[index]) and trailing_roles[index - 1] == "assistant")+ )+ return tuple(zip(start_indexes, (*start_indexes[1:], len(raw_input))))+++def _input_item_provenance(+ raw_input: Sequence[object],+ expected_messages: Sequence[object],+) -> tuple[Mapping[int, int], frozenset[int]] | None:+ if not all(isinstance(item, Mapping) for item in raw_input):+ return None+ solo_conversions: Final = tuple(+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast("ResponseInputParam", [item]), # cast-ok: items checked as Mappings above+ responses_api_request=_EMPTY_RESPONSES_REQUEST,+ )+ for item in raw_input+ )+ full_conversion: Final = tuple(+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast("ResponseInputParam", list(raw_input)), # cast-ok: items checked as Mappings above+ responses_api_request=_EMPTY_RESPONSES_REQUEST,+ )+ )+ if full_conversion != tuple(expected_messages):+ return None+ units: Final = _provenance_unit_bounds(raw_input, solo_conversions)+ unit_messages: Final = tuple(+ tuple(solo_conversions[start])+ if end - start == 1+ else tuple(+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast("ResponseInputParam", list(raw_input[start:end])), # cast-ok: checked as Mappings above+ responses_api_request=_EMPTY_RESPONSES_REQUEST,+ )+ )+ for start, end in units+ )+ if tuple(message for messages in unit_messages for message in messages) != full_conversion:+ return None+ boundaries: Final = tuple(accumulate((len(messages) for messages in unit_messages), initial=0))+ item_for_message: Final = MappingProxyType(+ {+ message_index: start+ for unit_index, (start, end) in enumerate(units)+ if end - start == 1+ for message_index in range(boundaries[unit_index], boundaries[unit_index + 1])+ }+ )+ tainted: Final = frozenset(+ message_index+ for unit_index, (start, end) in enumerate(units)+ if end - start > 1+ for message_index in range(boundaries[unit_index], boundaries[unit_index + 1])+ )+ return item_for_message, tainted+++class _RequestFields(NamedTuple):+ input: tuple[object, ...]+ instructions: str | None+++class _ExtractedInputs(NamedTuple):+ inputs: GenericGuardrailAPIInputs+ task_mappings: tuple[tuple[int, int | None], ...]+++def _patched_request_fields(+ raw_input: object,+ instructions: object,+ original_messages: Sequence[object],+ structured_messages: Sequence[object],+) -> _RequestFields | None:+ if not isinstance(raw_input, list) or len(original_messages) != len(structured_messages):+ return None+ offset: Final = 1 if instructions else 0+ provenance: Final = _input_item_provenance(raw_input, tuple(original_messages)[offset:])+ if provenance is None:+ return None+ item_for_message, tainted = provenance+ changed: Final = tuple(+ (index, rewritten)+ for index, (original, rewritten) in enumerate(zip(original_messages, structured_messages))+ if original != rewritten+ )+ instruction_rewrites: Final = tuple(rewritten for index, rewritten in changed if index < offset)+ rewritten_instructions: Final = (+ instruction_rewrites[0].get("content")+ if instruction_rewrites and isinstance(instruction_rewrites[0], Mapping)+ else instructions+ )+ instructions_value: Final = rewritten_instructions if isinstance(rewritten_instructions, str) else None+ if rewritten_instructions is not None and instructions_value is None:+ return None+ body_changes: Final = tuple((index - offset, rewritten) for index, rewritten in changed if index >= offset)+ if any(message_index in tainted or message_index not in item_for_message for message_index, _ in body_changes):+ return None+ replacements: Final = MappingProxyType(+ {+ item_for_message[message_index]: _rewritten_input_item(+ cast("Mapping[str, object]", raw_input[item_for_message[message_index]]), # cast-ok: checked Mappings+ rewritten,+ )+ for message_index, rewritten in body_changes+ }+ )+ if len(replacements) != len(body_changes) or any(item is None for item in replacements.values()):+ return None+ return _RequestFields(+ input=tuple(replacements.get(index, item) for index, item in enumerate(raw_input)),+ instructions=instructions_value,+ )+++def _patch_or_convert_request_fields(+ raw_input: object,+ instructions: object,+ original_messages: Sequence[object],+ structured_messages: Sequence[AllMessageValues],+) -> _RequestFields | None:+ if not isinstance(structured_messages, list):+ return None+ patched: Final = _patched_request_fields(raw_input, instructions, original_messages, structured_messages)+ if patched is not None:+ return patched+ input_items, converted_instructions = (+ LiteLLMResponsesTransformationHandler().convert_chat_completion_messages_to_responses_api(structured_messages)+ )+ return _RequestFields(input=tuple(input_items), instructions=converted_instructions)++def _next_stream_sequence_number(responses_so_far: Sequence[Any] | None) -> int:sequence_numbers: Final = (item.get("sequence_number") if isinstance(item, dict) else getattr(item, "sequence_number", None)diff --cc tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.pyindex 86c023dd7a4,315b6948bd8..450b3538944--- 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@@@ -1231,518 -1323,217 +1323,734 @@@ 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 TestBuildBlockSseChunks:+ """build_block_sse_chunks turns a streaming ModifyResponseException into 200 SSE events"""++ def _exc(self, original_response=None):+ from litellm.exceptions import ModifyResponseException++ return ModifyResponseException(+ message="Blocked by policy.",+ model="gpt-5.4-mini",+ request_data={},+ guardrail_name="test",+ original_response=original_response,+ )++ def _payloads(self, chunks):+ import json++ return [json.loads(chunk.decode().removeprefix("data: ").strip()) for chunk in chunks]++ def test_standalone_block_emits_complete_synthetic_stream(self):+ handler = OpenAIResponsesHandler()+ payloads = self._payloads(handler.build_block_sse_chunks(self._exc(), stream_started=False))+ types = [payload["type"] for payload in payloads]+ assert types[0] == "response.created"+ assert types[-1] == "response.completed"+ completed = payloads[-1]["response"]+ assert completed["id"].startswith("resp_")+ assert completed["model"] == "gpt-5.4-mini"+ assert completed["output"][0]["content"][0]["text"] == "Blocked by policy."++ def test_continuation_appends_item_at_next_output_index_with_real_usage(self):+ handler = OpenAIResponsesHandler()+ yielded = [+ {"type": "response.created", "response": {"id": "resp_live", "model": "gpt-5.4-mini-2026-01-01"}},+ {"type": "response.output_item.added", "output_index": 2, "item": {"id": "msg_orig"}},+ ]+ original = yielded + [+ {+ "type": "response.completed",+ "response": {+ "id": "resp_live",+ "model": "gpt-5.4-mini-2026-01-01",+ "output": [],+ "usage": {"input_tokens": 7, "output_tokens": 21, "total_tokens": 28},+ },+ }+ ]+ payloads = self._payloads(+ handler.build_block_sse_chunks(+ self._exc(original_response=original), stream_started=True, responses_so_far=yielded+ )+ )+ types = [payload["type"] for payload in payloads]+ assert "response.created" not in types+ assert types[0] == "response.output_item.done"+ assert payloads[0]["output_index"] == 2+ assert payloads[0]["item"]["id"] == "msg_orig"+ assert payloads[0]["item"]["status"] == "completed"+ assert types[1] == "response.output_item.added"+ assert payloads[1]["output_index"] == 3+ completed = payloads[-1]["response"]+ assert completed["id"] == "resp_live"+ assert completed["model"] == "gpt-5.4-mini-2026-01-01"+ assert completed["output"][0]["content"][0]["text"] == "Blocked by policy."+ assert completed["usage"] == {"input_tokens": 7, "output_tokens": 21, "total_tokens": 28}++ def test_continuation_reads_usage_from_typed_completed_event(self):+ from litellm.types.llms.openai import (+ ResponseCompletedEvent,+ ResponsesAPIResponse,+ ResponsesAPIStreamEvents,+ )++ handler = OpenAIResponsesHandler()+ original = [+ ResponseCompletedEvent(+ type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED,+ response=ResponsesAPIResponse.model_validate(+ {+ "id": "resp_live",+ "created_at": 1,+ "model": "gpt-5.4-mini",+ "output": [],+ "usage": {"input_tokens": 7, "output_tokens": 21, "total_tokens": 28},+ }+ ),+ )+ ]+ payloads = self._payloads(+ handler.build_block_sse_chunks(+ self._exc(original_response=original), stream_started=True, responses_so_far=[]+ )+ )+ completed = payloads[-1]["response"]+ assert completed["usage"]["input_tokens"] == 7+ assert completed["usage"]["output_tokens"] == 21+ assert completed["usage"]["total_tokens"] == 28++ def test_continuation_closes_open_item_given_pydantic_events_with_enum_types(self):+ from litellm.types.llms.openai import (+ BaseLiteLLMOpenAIResponseObject,+ ContentPartAddedEvent,+ OutputItemAddedEvent,+ OutputTextDeltaEvent,+ ResponsesAPIStreamEvents,+ )++ handler = OpenAIResponsesHandler()+ open_item = GenericResponseOutputItem.model_validate(+ {"type": "message", "id": "msg_live", "status": "in_progress", "role": "assistant", "content": []}+ )+ yielded = [+ OutputItemAddedEvent(+ type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED, output_index=0, item=open_item+ ),+ ContentPartAddedEvent(+ type=ResponsesAPIStreamEvents.CONTENT_PART_ADDED,+ item_id="msg_live",+ output_index=0,+ content_index=0,+ part=BaseLiteLLMOpenAIResponseObject.model_validate(+ {"type": "output_text", "text": "", "annotations": []}+ ),+ ),+ OutputTextDeltaEvent(+ type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,+ item_id="msg_live",+ output_index=0,+ content_index=0,+ delta="partial ",+ ),+ OutputTextDeltaEvent(+ type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,+ item_id="msg_live",+ output_index=0,+ content_index=0,+ delta="text",+ ),+ ]+ payloads = self._payloads(+ handler.build_block_sse_chunks(+ self._exc(original_response=yielded), stream_started=True, responses_so_far=yielded+ )+ )+ types = [payload["type"] for payload in payloads]+ assert types[:3] == [+ "response.output_text.done",+ "response.content_part.done",+ "response.output_item.done",+ ]+ assert payloads[0]["text"] == "partial text"+ assert payloads[2]["item"]["id"] == "msg_live"+ assert payloads[2]["item"]["status"] == "completed"+ assert payloads[2]["item"]["content"][0]["text"] == "partial text"+ assert types[3] == "response.output_item.added"+ assert payloads[3]["output_index"] == 1++ def test_continuation_closes_open_function_call_as_incomplete(self):+ handler = OpenAIResponsesHandler()+ yielded = [+ {"type": "response.created", "response": {"id": "resp_live", "model": "gpt-5.4-mini"}},+ {+ "type": "response.output_item.added",+ "output_index": 0,+ "item": {+ "id": "fc_live",+ "type": "function_call",+ "status": "in_progress",+ "call_id": "call_1",+ "name": "run_payment",+ "arguments": "",+ },+ },+ {+ "type": "response.function_call_arguments.delta",+ "item_id": "fc_live",+ "output_index": 0,+ "delta": '{"amount": 100}',+ },+ ]+ payloads = self._payloads(+ handler.build_block_sse_chunks(+ self._exc(original_response=yielded), stream_started=True, responses_so_far=yielded+ )+ )+ types = [payload["type"] for payload in payloads]+ assert types[0] == "response.output_item.done"+ closed = payloads[0]["item"]+ assert closed["id"] == "fc_live"+ assert closed["type"] == "function_call"+ assert closed["status"] == "incomplete"+ assert closed["name"] == "run_payment"+ assert "content" not in closed+ assert types[1] == "response.output_item.added"+ assert payloads[1]["output_index"] == 1+ assert types[-1] == "response.completed"++ def test_continuation_without_open_item_emits_no_closing_events(self):+ handler = OpenAIResponsesHandler()+ yielded = [+ {"type": "response.created", "response": {"id": "resp_live", "model": "gpt-5.4-mini"}},+ {"type": "response.in_progress", "response": {"id": "resp_live"}},+ ]+ payloads = self._payloads(+ handler.build_block_sse_chunks(+ self._exc(original_response=yielded), stream_started=True, responses_so_far=yielded+ )+ )+ types = [payload["type"] for payload in payloads]+ assert types[0] == "response.output_item.added"+ assert types[-1] == "response.completed"+ dones = [payload for payload in payloads if payload["type"] == "response.output_item.done"]+ assert len(dones) == 1+ assert dones[0]["item"]["content"][0]["text"] == "Blocked by policy."