diff --git a/helpers.py b/helpers.py index 086ad8e6..94dcc2eb 100644 --- a/helpers.py +++ b/helpers.py @@ -1076,9 +1076,18 @@ def evaluate_branches_batch(companies_data): if not response_str: raise APIError("Keine Antwort von OpenAI erhalten.") - response_json = json.loads(response_str) + # --- NEUE, ROBUSTE JSON-EXTRAKTION --- + json_start = response_str.find('{') + json_end = response_str.rfind('}') + + if json_start == -1 or json_end == -1: + logger.error(f"Konnte kein JSON-Objekt in der Batch-API-Antwort finden. Antwort: {response_str[:300]}...") + raise json.JSONDecodeError("Kein JSON-Objekt in der Antwort gefunden.", response_str, 0) + + json_str = response_str[json_start : json_end + 1] + response_json = json.loads(json_str) + # --- ENDE DER NEUEN LOGIK --- - # NEUER, KUGELSICHERER PARSER results_list = response_json.get("results") if results_list is None or not isinstance(results_list, list): @@ -1087,6 +1096,9 @@ def evaluate_branches_batch(companies_data): return results_list + except json.JSONDecodeError as e: + logger.error(f"Endgültiger FEHLER beim Parsen der JSON-Antwort im Batch-Aufruf: {e}") + return None except Exception as e: logger.error(f"Endgültiger FEHLER beim Batch-API-Aufruf: {e}") return None