diff --git a/modules/services/serviceAi/mainServiceAi.py b/modules/services/serviceAi/mainServiceAi.py index a284bc99..67a47163 100644 --- a/modules/services/serviceAi/mainServiceAi.py +++ b/modules/services/serviceAi/mainServiceAi.py @@ -338,6 +338,11 @@ Respond with ONLY a JSON object in this exact format: result, iteration, debugPrefix, allSections, accumulationState ) + # CRITICAL: Merge sections BEFORE KPI validation + # This ensures sections are preserved even if KPI validation fails + if extractedSections: + allSections = JsonResponseHandler.mergeSectionsIntelligently(allSections, extractedSections, iteration) + # Define KPIs if we just entered accumulation mode (iteration 1, incomplete JSON) if accumulationState and accumulationState.isAccumulationMode and iteration == 1 and not accumulationState.kpis: logger.info(f"Iteration {iteration}: Defining KPIs for accumulation tracking") @@ -478,10 +483,8 @@ Respond with ONLY a JSON object in this exact format: logger.warning(f"Iteration {iteration}: No sections extracted from complete JSON, stopping") break - # Merge new sections with existing sections intelligently - # This handles the STANDARD CASE: broken JSON iterations must be merged together - # The break can occur anywhere - in any section, at any depth - allSections = JsonResponseHandler.mergeSectionsIntelligently(allSections, extractedSections, iteration) + # NOTE: Section merging now happens BEFORE KPI validation (see above) + # This ensures sections are preserved even if KPI validation fails # Calculate total bytes in merged content for progress display merged_json_str = json.dumps(allSections, indent=2, ensure_ascii=False)