diff --git a/tests/entrypoints/openai/responses/test_responses_utils.py b/tests/entrypoints/openai/responses/test_responses_utils.py index 87fb45072be0..108342301267 100644 --- a/tests/entrypoints/openai/responses/test_responses_utils.py +++ b/tests/entrypoints/openai/responses/test_responses_utils.py @@ -4,6 +4,7 @@ from unittest.mock import patch import pytest +from mistral_common.protocol.instruct.request import ChatCompletionRequest from openai.types.responses import CustomTool, FunctionTool, ResponseCustomToolCall from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall from openai.types.responses.response_function_tool_call_output_item import ( @@ -18,6 +19,7 @@ ) from vllm.entrypoints.generate.base.protocol import FunctionCall +from vllm.entrypoints.openai.responses.protocol import ResponsesRequest from vllm.entrypoints.openai.responses.utils import ( _construct_message_from_response_item, build_response_output_items, @@ -958,6 +960,160 @@ def test_merge_chain_breaks(self, items, num_expected_messages): assert len(messages) == num_expected_messages +class TestConstructInputMessagesContentParts: + """Renderers such as Mistral's forward messages to strict chat-only validators, + so Responses content parts must already be chat parts.""" + + IMAGE_URL = "https://example.com/cat.png" + + @staticmethod + def _convert(content): + messages = construct_input_messages( + request_input=[{"role": "user", "content": content}] + ) + assert len(messages) == 1 + assert messages[0]["role"] == "user" + return messages[0]["content"] + + @pytest.mark.parametrize("part_type", ["input_text", "output_text"]) + def test_text_parts_become_chat_text(self, part_type): + assert self._convert([{"type": part_type, "text": "hello"}]) == [ + {"type": "text", "text": "hello"} + ] + + @pytest.mark.parametrize("detail", ["auto", "low", "high"]) + def test_input_image_becomes_chat_image_url_with_detail(self, detail): + part = {"type": "input_image", "image_url": self.IMAGE_URL, "detail": detail} + assert self._convert([part]) == [ + { + "type": "image_url", + "image_url": {"url": self.IMAGE_URL, "detail": detail}, + } + ] + + def test_input_image_drops_detail_chat_parts_cannot_carry(self): + part = { + "type": "input_image", + "image_url": self.IMAGE_URL, + "detail": "original", + } + assert self._convert([part]) == [ + {"type": "image_url", "image_url": {"url": self.IMAGE_URL}} + ] + + def test_converted_parts_pass_mistral_common_validation(self): + content = self._convert( + [ + {"type": "input_text", "text": "Describe this."}, + { + "type": "input_image", + "image_url": self.IMAGE_URL, + "detail": "low", + "file_id": "file_1", + }, + ] + ) + + request = ChatCompletionRequest.from_openai( + messages=[{"role": "user", "content": content}] + ) + + text_chunk, image_chunk = request.messages[0].content + assert text_chunk.text == "Describe this." + assert image_chunk.image_url.url == self.IMAGE_URL + assert image_chunk.image_url.detail == "low" + + @pytest.mark.parametrize( + "item", + [ + pytest.param({"type": "function_call_output"}, id="function"), + pytest.param( + { + "type": "function_call_output", + "id": "fco_1", + "status": "completed", + "created_by": "resp_1", + }, + id="function_output_item", + ), + pytest.param({"type": "custom_tool_call_output"}, id="custom"), + pytest.param( + { + "type": "custom_tool_call_output", + "id": "ctco_1", + "status": "completed", + }, + id="custom_output_item", + ), + ], + ) + def test_tool_output_parts_become_chat_parts(self, item): + request = ResponsesRequest( + model="test", + input=[ + { + **item, + "call_id": "call_1", + "output": [{"type": "input_text", "text": "22C"}], + } + ], + ) + + assert construct_input_messages(request_input=request.input) == [ + { + "role": "tool", + "content": [{"type": "text", "text": "22C"}], + "tool_call_id": "call_1", + } + ] + + def test_extra_part_fields_survive_conversion(self): + cache_control = {"type": "ephemeral"} + converted = self._convert( + [ + {"type": "input_text", "text": "hi", "cache_control": cache_control}, + { + "type": "input_image", + "image_url": self.IMAGE_URL, + "detail": "auto", + "file_id": "file_1", + "uuid": "cat", + }, + ] + ) + assert converted == [ + {"type": "text", "text": "hi", "cache_control": cache_control}, + { + "type": "image_url", + "image_url": {"url": self.IMAGE_URL, "detail": "auto"}, + "file_id": "file_1", + "uuid": "cat", + }, + ] + + @pytest.mark.parametrize( + "part", + [ + pytest.param( + {"type": "input_image", "detail": "auto", "file_id": "file_1"}, + id="file_id_only_image", + ), + pytest.param( + {"type": "input_image", "detail": "auto", "image_url": None}, + id="null_image_url", + ), + pytest.param({"type": "input_file", "file_id": "file_1"}, id="input_file"), + pytest.param({"type": "text", "text": "hello"}, id="chat_text"), + pytest.param( + {"type": "image_url", "image_url": {"url": IMAGE_URL}}, + id="chat_image_url", + ), + ], + ) + def test_other_parts_are_preserved(self, part): + assert self._convert([part]) == [part] + + class TestConstructInputMessagesInstructionsLeak: """Regression tests for #37697: instructions from a prior response should NOT leak through previous_response_id.""" diff --git a/tests/entrypoints/scale_out/render/test_render.py b/tests/entrypoints/scale_out/render/test_render.py index 5392ee5728a5..71f265575d43 100644 --- a/tests/entrypoints/scale_out/render/test_render.py +++ b/tests/entrypoints/scale_out/render/test_render.py @@ -43,6 +43,7 @@ MODEL_NAME = "vllm-project/tiny-random-LlamaForCausalLM" GPT_OSS_MODEL_NAME = "openai/gpt-oss-20b" +MISTRAL_MODEL_NAME = "mistralai/Magistral-Small-2509" DEEPSEEK_V41_MODEL_NAME = "deepseek-ai/DeepSeek-V4.1-Flash" @@ -458,6 +459,33 @@ async def test_responses_render_basic(client): assert data["token_ids"] +@pytest.mark.asyncio +async def test_responses_render_input_text_matches_chat_text_part(client): + text = "Which color should I remember?" + responses_render = await client.post( + "/v1/responses/render", + json={ + "model": MODEL_NAME, + "input": [ + {"role": "user", "content": [{"type": "input_text", "text": text}]} + ], + }, + ) + # The Responses route rejects "text" parts and always adds special tokens. + chat_render = await client.post( + "/v1/chat/completions/render", + json={ + "model": MODEL_NAME, + "messages": [{"role": "user", "content": [{"type": "text", "text": text}]}], + "add_special_tokens": True, + }, + ) + + assert responses_render.status_code == 200 + assert chat_render.status_code == 200 + assert responses_render.json()["token_ids"] == chat_render.json()["token_ids"] + + @pytest.mark.asyncio async def test_responses_render_input_list_reports_only_first_invalid_item(client): invalid_item = {"type": "message", "role": "user"} @@ -1120,6 +1148,115 @@ async def test_tokenize_matches_chat_render_for_gpt_oss(gpt_oss_server): assert tokenize.json()["tokens"] == render.json()["token_ids"] +@pytest.fixture(scope="module") +def mistral_server(): + args = ["--tokenizer-mode", "mistral"] + with RemoteLaunchRenderServer(MISTRAL_MODEL_NAME, args) as remote_server: + yield remote_server + + +@pytest.mark.asyncio +async def test_responses_render_content_parts_match_strings_on_mistral(mistral_server): + """Mistral tokenizers only accept chat parts, so Responses parts must convert.""" + system = "Answer in one word." + question = "What is the capital of France?" + answer = "Paris." + follow_up = "And of Italy?" + string_input = [ + {"role": "system", "content": system}, + {"role": "user", "content": question}, + {"role": "assistant", "content": answer}, + {"role": "user", "content": follow_up}, + ] + parts_input = [ + {"role": "system", "content": [{"type": "input_text", "text": system}]}, + {"role": "user", "content": [{"type": "input_text", "text": question}]}, + { + "type": "message", + "id": "msg_1", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": answer, "annotations": []}], + }, + {"role": "user", "content": [{"type": "input_text", "text": follow_up}]}, + ] + async with httpx.AsyncClient( + base_url=mistral_server.url_for(""), timeout=30.0 + ) as client: + string_render = await client.post( + "/v1/responses/render", + json={"model": MISTRAL_MODEL_NAME, "input": string_input}, + ) + parts_render = await client.post( + "/v1/responses/render", + json={"model": MISTRAL_MODEL_NAME, "input": parts_input}, + ) + + assert string_render.status_code == 200 + assert parts_render.status_code == 200, parts_render.text + assert parts_render.json()["token_ids"] == string_render.json()["token_ids"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("call", "output_item"), + [ + pytest.param( + {"type": "function_call", "name": "get_weather", "arguments": "{}"}, + {"type": "function_call_output"}, + id="function", + ), + pytest.param( + {"type": "function_call", "name": "get_weather", "arguments": "{}"}, + { + "type": "function_call_output", + "id": "fco_1", + "status": "completed", + "created_by": "resp_1", + }, + id="function_output_item", + ), + pytest.param( + {"type": "custom_tool_call", "name": "run", "input": "date"}, + {"type": "custom_tool_call_output"}, + id="custom", + ), + pytest.param( + {"type": "custom_tool_call", "name": "run", "input": "date"}, + {"type": "custom_tool_call_output", "id": "ctco_1", "status": "completed"}, + id="custom_output_item", + ), + ], +) +async def test_responses_render_tool_output_parts_match_strings_on_mistral( + mistral_server, call, output_item +): + def render_body(output): + return { + "model": MISTRAL_MODEL_NAME, + "input": [ + {"role": "user", "content": "What is the weather in Paris?"}, + {**call, "call_id": "abcdef123"}, + {**output_item, "call_id": "abcdef123", "output": output}, + ], + } + + async with httpx.AsyncClient( + base_url=mistral_server.url_for(""), timeout=30.0 + ) as client: + string_render = await client.post( + "/v1/responses/render", json=render_body("22C") + ) + parts_render = await client.post( + "/v1/responses/render", + json=render_body([{"type": "input_text", "text": "22C"}]), + ) + + assert string_render.status_code == 200 + assert parts_render.status_code == 200, parts_render.text + assert parts_render.json()["token_ids"] == string_render.json()["token_ids"] + + @pytest.fixture(scope="module") def deepseek_v41_server(): args = [ diff --git a/vllm/entrypoints/openai/responses/utils.py b/vllm/entrypoints/openai/responses/utils.py index 62bc41f9d82c..d5a3d216910a 100644 --- a/vllm/entrypoints/openai/responses/utils.py +++ b/vllm/entrypoints/openai/responses/utils.py @@ -23,9 +23,6 @@ ResponseReasoningItem, ) from openai.types.responses.response import ToolChoice -from openai.types.responses.response_function_tool_call_output_item import ( - ResponseFunctionToolCallOutputItem, -) from openai.types.responses.response_output_text import Logprob from openai.types.responses.response_reasoning_item import ( Content as ResponseReasoningTextContent, @@ -142,7 +139,7 @@ def _item_type(item: ResponseInputOutputItem) -> str | None: def _item_dict(item: ResponseInputOutputItem) -> dict[str, Any]: - return item if isinstance(item, dict) else item.model_dump() + return item if isinstance(item, dict) else item.model_dump(exclude_none=True) def response_item_status( @@ -368,6 +365,21 @@ def construct_chat_messages_with_tool_call( return messages +def _to_chat_content_part(part: dict[str, Any]) -> dict[str, Any]: + """Convert a Responses content part to its chat completions equivalent.""" + part_type = part.get("type") + if part_type in ("input_text", "output_text"): + return {**part, "type": "text"} + if part_type == "input_image" and isinstance(url := part.get("image_url"), str): + image_url = {"url": url} + # Chat image parts reject the Responses-only "original" detail. + if (detail := part.get("detail")) in ("auto", "low", "high"): + image_url["detail"] = detail + extra_fields = {k: v for k, v in part.items() if k != "detail"} + return {**extra_fields, "type": "image_url", "image_url": image_url} + return part + + def _construct_message_from_response_item( item: ResponseInputOutputItem, prev_msg: ChatCompletionMessageParam | None = None, @@ -469,17 +481,15 @@ def _construct_message_from_response_item( "role": "assistant", "content": output_text, } - elif isinstance(item, ResponseFunctionToolCallOutputItem): - return ChatCompletionToolMessageParam( - role="tool", - content=item.output, - tool_call_id=item.call_id, - ) elif _item_type(item) in ("function_call_output", "custom_tool_call_output"): output = _item_dict(item) + content = output.get("output") + # Custom tool output is typed Iterable, so it arrives as a one-shot iterator. + if content is not None and not isinstance(content, str): + content = [_to_chat_content_part(part) for part in content] return ChatCompletionToolMessageParam( role="tool", - content=output.get("output"), + content=content, tool_call_id=output.get("call_id"), ) elif isinstance(item, dict) and item.get("type") == "reasoning": @@ -534,7 +544,10 @@ def _construct_message_from_response_item( "content": text, } if isinstance(item, dict) and "role" in item: - return item # type: ignore[return-value] + content = item.get("content") + if not isinstance(content, list): + return item + return {**item, "content": [_to_chat_content_part(part) for part in content]} item_type = item.get("type") if isinstance(item, dict) else item.type raise VLLMValidationError( f"Unsupported input item type: {item_type}",