diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index 659c0b2299..f246bc84b3 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -1660,14 +1660,27 @@ async def process_chat_response( ) if tool_call_index is not None: - if ( - len(response_tool_calls) - <= tool_call_index - ): + # Check if the tool call already exists + current_response_tool_call = None + for ( + response_tool_call + ) in response_tool_calls: + if ( + response_tool_call.get("index") + == tool_call_index + ): + current_response_tool_call = ( + response_tool_call + ) + break + + if current_response_tool_call is None: + # Add the new tool call response_tool_calls.append( delta_tool_call ) else: + # Update the existing tool call delta_name = delta_tool_call.get( "function", {} ).get("name") @@ -1678,16 +1691,14 @@ async def process_chat_response( ) if delta_name: - response_tool_calls[ - tool_call_index - ]["function"][ - "name" - ] += delta_name + current_response_tool_call[ + "function" + ]["name"] += delta_name if delta_arguments: - response_tool_calls[ - tool_call_index - ]["function"][ + current_response_tool_call[ + "function" + ][ "arguments" ] += delta_arguments