Spaces:
Paused
Paused
Refactor httpx client usage for OpenAI and DeepSeek: implement context management to prevent socket leaks and improve error logging
Browse files3 unmodified lines456789101112131415161760 unmodified lines787980758182838485868782888990919293943 unmodified lines"""import osimport sysimport warningsimport loggingfrom pathlib import Path
# Suppress asyncio event loop __del__ warnings (known Python 3.11 issue in threaded envs)warnings.filterwarnings("ignore", message=".*Invalid file descriptor.*")logging.getLogger("asyncio").setLevel(logging.CRITICAL)
# Set environment for Hugging Face Spacesos.environ['GRADIO_SERVER_NAME'] = '0.0.0.0'os.environ['GRADIO_SERVER_PORT'] = '7860'60 unmodified lines except Exception as e: print(f" ❌ {name} ({url}) -> {type(e).__name__}: {e}") # Check httpx (used by anthropic SDK) # Check httpx (used by anthropic/openai SDKs) print("\n🔧 httpx connectivity test:") try: import httpx print(f" httpx version: {httpx.__version__}") with httpx.Client(timeout=10) as client: resp = client.get("https://api.anthropic.com") print(f" ✅ httpx -> HTTP {resp.status_code}") print(f" ✅ httpx -> Anthropic HTTP {resp.status_code}") with httpx.Client(timeout=10) as client: resp = client.get("https://api.openai.com") print(f" ✅ httpx -> OpenAI HTTP {resp.status_code}") except Exception as e: print(f" ❌ httpx -> {type(e).__name__}: {e}") 681 unmodified lines68268368468568668768868969069169269369469569669769869970068568668768868969069169269369469569669769869970070170270370434 unmodified lines73974074174274374474574274674774874917 unmodified lines76776876976677077177277377477577677777877978078177277377477577677777877978078178278378478578678778278378478578678778878979079179279379479579679779879980080180250 unmodified lines853854855845856857858859860861862863864865866867868681 unmodified lines raise Exception(f"Текст судового рішення занадто короткий або відсутній (довжина: {len(court_decision_text) if court_decision_text else 0} символів). Будь ласка, перевірте вхідні дані.")
if provider == ModelProvider.OPENAI.value: # Use custom httpx client to avoid async loop issues on HF Spaces # This is critical for stable connection in threaded environments like Gradio http_client = httpx.Client( timeout=120.0, transport=httpx.HTTPTransport(retries=3) ) client = OpenAI( api_key=OPENAI_API_KEY, http_client=http_client ) # Retry logic for connection errors max_retries = 3 last_error = None response = None # Use context-managed httpx client to avoid socket/fd leaks in threaded Gradio env http_client = None response_text = None try: http_client = httpx.Client( timeout=httpx.Timeout(120.0, connect=30.0), ) client = OpenAI( api_key=OPENAI_API_KEY, http_client=http_client ) # Retry logic for connection errors max_retries = 3 last_error = None response = None print(f"[DEBUG] OpenAI Generation - Model: {model_name}") # Check for reasoning models (gpt-4.1, o1, etc.)34 unmodified lines except Exception as api_err: last_error = api_err error_type = type(api_err).__name__ error_detail = str(api_err) # Log underlying cause for connection errors if hasattr(api_err, '__cause__') and api_err.__cause__: error_detail += f" | Cause: {type(api_err.__cause__).__name__}: {api_err.__cause__}" print(f"[ERROR] OpenAI API attempt {attempt + 1} failed: {error_type}: {str(api_err)}") print(f"[ERROR] OpenAI API attempt {attempt + 1} failed: {error_type}: {error_detail}") if attempt < max_retries - 1: wait_time = 2 ** attempt # 1, 2, 4 seconds print(f"[DEBUG] Retrying in {wait_time}s...")17 unmodified lines print(f"[ERROR] OpenAI generation/parsing failed: {e}") return { "title": "Автоматично сформований заголовок (OpenAI)", "text": response_text.strip() if 'response_text' in locals() and response_text else f"Помилка при отриманні відповіді: {str(e)}", "text": response_text.strip() if response_text else f"Помилка при отриманні відповіді: {str(e)}", "proceeding": "Не визначено", "category": "Помилка парсингу" } finally: if http_client: try: http_client.close() except Exception: pass
if provider == ModelProvider.DEEPSEEK.value: # Use custom httpx client for DeepSeek on HF Spaces http_client = httpx.Client( timeout=120.0, transport=httpx.HTTPTransport(retries=3) ) client = OpenAI( api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com", http_client=http_client ) # Retry logic for DeepSeek max_retries = 3 last_error = None response = None # Use context-managed httpx client for DeepSeek to avoid socket/fd leaks http_client = None response_text = None try: http_client = httpx.Client( timeout=httpx.Timeout(120.0, connect=30.0), ) client = OpenAI( api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com", http_client=http_client ) # Retry logic for DeepSeek max_retries = 3 last_error = None response = None print(f"[DEBUG] DeepSeek Generation - Model: {model_name}") # Check for reasoning model (DeepSeek R1)50 unmodified lines print(f"[ERROR] DeepSeek generation/parsing failed: {e}") return { "title": "Автоматично сформований заголовок (DeepSeek)", "text": response_text.strip() if 'response_text' in locals() and response_text else f"Помилка при отриманні відповіді від DeepSeek: {str(e)}", "text": response_text.strip() if response_text else f"Помилка при отриманні відповіді від DeepSeek: {str(e)}", "proceeding": "Не визначено", "category": "Помилка API/Парсингу" } finally: if http_client: try: http_client.close() except Exception: pass
elif provider == ModelProvider.ANTHROPIC.value: client = Anthropic(api_key=ANTHROPIC_API_KEY)app.py+11-2
main.py+52-35