From fe09e8d6275f0ccc047bec0b769ec9ceeba754a3 Mon Sep 17 00:00:00 2001 From: WatchTree-19 <119982314+WatchTree-19@users.noreply.github.com> Date: Fri, 25 Sep 2026 20:58:48 +0000 Subject: [PATCH] FIX: run every parallel function call in OpenAIResponseTarget The agentic loop only executed the last function_call in a response. When the model requested several calls at once, the others got no function_call_output, so the next request carried unanswered calls, which the Responses API rejects with "No tool output found for function call". Execute each call in reply order and send one output per call. --- .../openai/openai_response_target.py | 43 +++++++++--------- ...penai_response_target_function_chaining.py | 45 +++++++++++++++++++ 2 files changed, 68 insertions(+), 20 deletions(-) diff --git a/pyrit/prompt_target/openai/openai_response_target.py b/pyrit/prompt_target/openai/openai_response_target.py index 6fb7199b3a..2a125c00c4 100644 --- a/pyrit/prompt_target/openai/openai_response_target.py +++ b/pyrit/prompt_target/openai/openai_response_target.py @@ -546,8 +546,6 @@ async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Me responses_to_return: list[Message] = [] # Main agentic loop - each back-and-forth creates a new message - tool_call_section: dict[str, Any] | None = None - while True: logger.info(f"Sending conversation with {len(working_conversation)} messages to the prompt target") @@ -563,23 +561,26 @@ async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Me working_conversation.append(result) responses_to_return.append(result) - # Extract tool call if present - tool_call_section = self._find_last_pending_tool_call(result) + # Extract every tool call in the reply; parallel calls each need an output + tool_call_sections = self._find_pending_tool_calls(result) # If no tool call, we're done - if not tool_call_section: + if not tool_call_sections: break - # Execute the tool/function - tool_output = await self._execute_call_section_async(tool_call_section) + for tool_call_section in tool_call_sections: + # Execute the tool/function + tool_output = await self._execute_call_section_async(tool_call_section) - # Create a new message with the tool output - tool_piece = self._make_tool_piece(tool_output, tool_call_section["call_id"], reference_piece=message_piece) - tool_message = Message(message_pieces=[tool_piece]) + # Create a new message with the tool output + tool_piece = self._make_tool_piece( + tool_output, tool_call_section["call_id"], reference_piece=message_piece + ) + tool_message = Message(message_pieces=[tool_piece]) - # Add tool output message to conversation and responses list - working_conversation.append(tool_message) - responses_to_return.append(tool_message) + # Add tool output message to conversation and responses list + working_conversation.append(tool_message) + responses_to_return.append(tool_message) # Continue loop to send tool result and get next response @@ -776,18 +777,20 @@ def _parse_response_output_section( # Agentic helpers (module scope) - def _find_last_pending_tool_call(self, reply: Message) -> dict[str, Any] | None: + def _find_pending_tool_calls(self, reply: Message) -> list[dict[str, Any]]: """ - Return the last tool-call section in assistant messages, or None. - Looks for a piece whose value parses as JSON with a 'type' key matching function_call. + Return every tool-call section in assistant messages, in reply order. + Looks for pieces whose value parses as JSON with a 'type' key matching function_call. + The model can request several calls at once, and each one needs its own output. Args: reply: The message to search for tool calls. Returns: - The tool-call section dict, or None if not found. + The tool-call section dicts, or an empty list if there are none. """ - for piece in reversed(reply.message_pieces): + sections: list[dict[str, Any]] = [] + for piece in reply.message_pieces: # Filter on data_type to skip reasoning/message pieces that also have api_role "assistant". if piece.api_role == "assistant" and piece.original_value_data_type == "function_call": try: @@ -796,8 +799,8 @@ def _find_last_pending_tool_call(self, reply: Message) -> dict[str, Any] | None: continue if isinstance(section, dict) and section.get("type") == "function_call": # Do NOT skip function_call even if status == "completed" — we still need to emit the output. - return cast("dict[str, Any]", section) - return None + sections.append(cast("dict[str, Any]", section)) + return sections async def _execute_call_section_async(self, tool_call_section: dict[str, Any]) -> dict[str, Any]: """ diff --git a/tests/unit/prompt_target/target/test_openai_response_target_function_chaining.py b/tests/unit/prompt_target/target/test_openai_response_target_function_chaining.py index e380002b39..7995f1c348 100644 --- a/tests/unit/prompt_target/target/test_openai_response_target_function_chaining.py +++ b/tests/unit/prompt_target/target/test_openai_response_target_function_chaining.py @@ -365,3 +365,48 @@ async def mock_create(**kwargs): # If we got here, no duplicates were detected assert len(call_history) == 2 + + +async def test_parallel_function_calls_each_get_an_output(response_target, patch_central_database): + """Every function_call in one response must be executed and answered before the next request.""" + executed = [] + + async def func_a(args: dict) -> dict: + executed.append("func_a") + return {"value": "a"} + + async def func_b(args: dict) -> dict: + executed.append("func_b") + return {"value": "b"} + + response_target._custom_functions["func_a"] = func_a + response_target._custom_functions["func_b"] = func_b + + user_message = Message( + message_pieces=[MessagePiece(role="user", original_value="Run both", conversation_id=str(uuid.uuid4()))] + ) + + parallel = create_mock_function_call_response("call_alpha", "func_a", {}) + parallel.output.append(create_mock_function_call_response("call_beta", "func_b", {}).output[0]) + responses = [parallel, create_mock_text_response("Done")] + call_history = [] + + async def mock_create(**kwargs): + call_history.append(kwargs["input"]) + return responses[len(call_history) - 1] + + with patch.object(response_target._async_client.responses, "create", new_callable=AsyncMock) as mock_create_call: + mock_create_call.side_effect = mock_create + result = await response_target.send_prompt_async(message=user_message) + + assert executed == ["func_a", "func_b"] + assert len(call_history) == 2 + second_call = call_history[1] + calls = [item["call_id"] for item in second_call if item.get("type") == "function_call"] + outputs = [item["call_id"] for item in second_call if item.get("type") == "function_call_output"] + assert calls == ["call_alpha", "call_beta"] + assert outputs == ["call_alpha", "call_beta"] + last_call = max(i for i, item in enumerate(second_call) if item.get("type") == "function_call") + first_output = min(i for i, item in enumerate(second_call) if item.get("type") == "function_call_output") + assert last_call < first_output + assert result[-1].message_pieces[0].original_value == "Done"