Abstract In the era of artificial intelligence, the importance of environmental rule of law for ecological governance is becoming increasingly important. This study explores how artificial intelligence can contribute to environmental management, especially the prediction and analysis of ambient air quality through the random forest algorithm. The study aims to assess and predict the changes of ambient air quality in Chinese cities and provide a scientific basis for environmental governance. Methodologically, a random forest model was used to analyze the relationship between ambient air quality and multiple factors. The results showed that the random forest model was effective in predicting air quality, in which the level of urban economic development showed a significant correlation with air quality, and the PM2.5 concentration in cities with a high level of economic development was significantly higher than that in the towns with a low to medium level of economic growth, as the PM2.5 concentration decreased from 43.854 μg/m3 to 33.941 μg/m3. In addition, seasonal variations had a significant effect on air quality. It is concluded that the random forest model is an effective tool to provide accurate data support for environmental rule of law and governance, which helps to formulate more accurate ecological protection policies.