DocUA commited on
Commit
98f5eca
·
1 Parent(s): 381cd06

Add diagnostic logging and raw httpx connectivity test for OpenAI API

Browse files
Files changed (1) hide show
  1. main.py +27 -5
main.py CHANGED
@@ -684,11 +684,26 @@ def generate_legal_position(
684
  raise Exception(f"Текст судового рішення занадто короткий або відсутній (довжина: {len(court_decision_text) if court_decision_text else 0} символів). Будь ласка, перевірте вхідні дані.")
685
 
686
  if provider == ModelProvider.OPENAI.value:
687
- # Use custom httpx client with HTTP/2 disabled to avoid 421 Misdirected Request
688
- # errors on HF Spaces (Cloudflare HTTP/2 connection coalescing issue)
689
  http_client = None
690
  response_text = None
691
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692
  http_client = httpx.Client(
693
  timeout=httpx.Timeout(120.0, connect=30.0),
694
  http2=False,
@@ -697,6 +712,7 @@ def generate_legal_position(
697
  api_key=OPENAI_API_KEY,
698
  http_client=http_client
699
  )
 
700
 
701
  # Retry logic for connection errors
702
  max_retries = 3
@@ -741,13 +757,19 @@ def generate_legal_position(
741
  response = client.chat.completions.create(**completion_params)
742
  break
743
  except Exception as api_err:
 
744
  last_error = api_err
745
  error_type = type(api_err).__name__
746
  error_detail = str(api_err)
747
- # Log underlying cause for connection errors
748
- if hasattr(api_err, '__cause__') and api_err.__cause__:
749
- error_detail += f" | Cause: {type(api_err.__cause__).__name__}: {api_err.__cause__}"
 
 
 
 
750
  print(f"[ERROR] OpenAI API attempt {attempt + 1} failed: {error_type}: {error_detail}")
 
751
  if attempt < max_retries - 1:
752
  wait_time = 2 ** attempt # 1, 2, 4 seconds
753
  print(f"[DEBUG] Retrying in {wait_time}s...")
 
684
  raise Exception(f"Текст судового рішення занадто короткий або відсутній (довжина: {len(court_decision_text) if court_decision_text else 0} символів). Будь ласка, перевірте вхідні дані.")
685
 
686
  if provider == ModelProvider.OPENAI.value:
687
+ # Diagnostic: test raw httpx connection before using OpenAI SDK
 
688
  http_client = None
689
  response_text = None
690
  try:
691
+ print(f"[DEBUG] OpenAI pre-flight check...")
692
+ print(f"[DEBUG] openai SDK version: {openai.__version__}")
693
+ print(f"[DEBUG] httpx version: {httpx.__version__}")
694
+ print(f"[DEBUG] OPENAI_API_KEY length: {len(OPENAI_API_KEY) if OPENAI_API_KEY else 0}")
695
+
696
+ # Quick raw httpx connectivity test to api.openai.com
697
+ try:
698
+ with httpx.Client(timeout=10.0, http2=False) as test_client:
699
+ test_resp = test_client.get("https://api.openai.com/v1/models",
700
+ headers={"Authorization": f"Bearer {OPENAI_API_KEY[:20]}...truncated"})
701
+ print(f"[DEBUG] Raw httpx test -> HTTP {test_resp.status_code}")
702
+ except Exception as pre_err:
703
+ import traceback
704
+ print(f"[WARNING] Raw httpx pre-flight failed: {type(pre_err).__name__}: {pre_err}")
705
+ print(f"[WARNING] Pre-flight traceback: {traceback.format_exc()}")
706
+
707
  http_client = httpx.Client(
708
  timeout=httpx.Timeout(120.0, connect=30.0),
709
  http2=False,
 
712
  api_key=OPENAI_API_KEY,
713
  http_client=http_client
714
  )
715
+ print(f"[DEBUG] OpenAI client base_url: {client.base_url}")
716
 
717
  # Retry logic for connection errors
718
  max_retries = 3
 
757
  response = client.chat.completions.create(**completion_params)
758
  break
759
  except Exception as api_err:
760
+ import traceback
761
  last_error = api_err
762
  error_type = type(api_err).__name__
763
  error_detail = str(api_err)
764
+ # Walk the full exception chain
765
+ cause = api_err.__cause__
766
+ depth = 0
767
+ while cause and depth < 5:
768
+ error_detail += f"\n -> Caused by [{depth}]: {type(cause).__name__}: {cause}"
769
+ cause = getattr(cause, '__cause__', None) or getattr(cause, '__context__', None)
770
+ depth += 1
771
  print(f"[ERROR] OpenAI API attempt {attempt + 1} failed: {error_type}: {error_detail}")
772
+ print(f"[ERROR] Full traceback:\n{traceback.format_exc()}")
773
  if attempt < max_retries - 1:
774
  wait_time = 2 ** attempt # 1, 2, 4 seconds
775
  print(f"[DEBUG] Retrying in {wait_time}s...")