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 lines456789101160 unmodified lines72737475767778798081828384853 unmodified lines"""import osimport sysfrom pathlib import Path# Set environment for Hugging Face Spacesos.environ['GRADIO_SERVER_NAME'] = '0.0.0.0'os.environ['GRADIO_SERVER_PORT'] = '7860'60 unmodified linesexcept Exception as e:print(f" ❌ {name} ({url}) -> {type(e).__name__}: {e}")# Check httpx (used by anthropic SDK)print("\n🔧 httpx connectivity test:")try:import httpxprint(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}")except Exception as e:print(f" ❌ httpx -> {type(e).__name__}: {e}")3 unmodified lines456789101112131415161760 unmodified lines78798081828384858687888990919293943 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 linesexcept Exception as e:print(f" ❌ {name} ({url}) -> {type(e).__name__}: {e}")# Check httpx (used by anthropic/openai SDKs)print("\n🔧 httpx connectivity test:")try:import httpxprint(f" httpx version: {httpx.__version__}")with httpx.Client(timeout=10) as client:resp = client.get("https://api.anthropic.com")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 lines68268368468568668768868969069169269369469569669769869970070170270370434 unmodified lines73974074174274374474517 unmodified lines76376476576676776876977077177277377477577677777877978078178278378478578678778878979079150 unmodified lines842843844845846847848849850851681 unmodified linesraise 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 Gradiohttp_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 errorsmax_retries = 3last_error = Noneresponse = Nonetry:print(f"[DEBUG] OpenAI Generation - Model: {model_name}")# Check for reasoning models (gpt-4.1, o1, etc.)34 unmodified linesexcept Exception as api_err:last_error = api_errerror_type = type(api_err).__name__print(f"[ERROR] OpenAI API attempt {attempt + 1} failed: {error_type}: {str(api_err)}")if attempt < max_retries - 1:wait_time = 2 ** attempt # 1, 2, 4 secondsprint(f"[DEBUG] Retrying in {wait_time}s...")17 unmodified linesprint(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)}","proceeding": "Не визначено","category": "Помилка парсингу"}if provider == ModelProvider.DEEPSEEK.value:# Use custom httpx client for DeepSeek on HF Spaceshttp_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 DeepSeekmax_retries = 3last_error = Noneresponse = Nonetry:print(f"[DEBUG] DeepSeek Generation - Model: {model_name}")# Check for reasoning model (DeepSeek R1)50 unmodified linesprint(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)}","proceeding": "Не визначено","category": "Помилка API/Парсингу"}elif provider == ModelProvider.ANTHROPIC.value:client = Anthropic(api_key=ANTHROPIC_API_KEY)681 unmodified lines68268368468568668768868969069169269369469569669769869970070170270370434 unmodified lines73974074174274374474574674774874917 unmodified lines76776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180250 unmodified lines853854855856857858859860861862863864865866867868681 unmodified linesraise Exception(f"Текст судового рішення занадто короткий або відсутній (довжина: {len(court_decision_text) if court_decision_text else 0} символів). Будь ласка, перевірте вхідні дані.")if provider == ModelProvider.OPENAI.value:# Use context-managed httpx client to avoid socket/fd leaks in threaded Gradio envhttp_client = Noneresponse_text = Nonetry: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 errorsmax_retries = 3last_error = Noneresponse = Noneprint(f"[DEBUG] OpenAI Generation - Model: {model_name}")# Check for reasoning models (gpt-4.1, o1, etc.)34 unmodified linesexcept Exception as api_err:last_error = api_errerror_type = type(api_err).__name__error_detail = str(api_err)# Log underlying cause for connection errorsif 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}: {error_detail}")if attempt < max_retries - 1:wait_time = 2 ** attempt # 1, 2, 4 secondsprint(f"[DEBUG] Retrying in {wait_time}s...")17 unmodified linesprint(f"[ERROR] OpenAI generation/parsing failed: {e}")return {"title": "Автоматично сформований заголовок (OpenAI)","text": response_text.strip() if response_text else f"Помилка при отриманні відповіді: {str(e)}","proceeding": "Не визначено","category": "Помилка парсингу"}finally:if http_client:try:http_client.close()except Exception:passif provider == ModelProvider.DEEPSEEK.value:# Use context-managed httpx client for DeepSeek to avoid socket/fd leakshttp_client = Noneresponse_text = Nonetry: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 DeepSeekmax_retries = 3last_error = Noneresponse = Noneprint(f"[DEBUG] DeepSeek Generation - Model: {model_name}")# Check for reasoning model (DeepSeek R1)50 unmodified linesprint(f"[ERROR] DeepSeek generation/parsing failed: {e}")return {"title": "Автоматично сформований заголовок (DeepSeek)","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:passelif provider == ModelProvider.ANTHROPIC.value:client = Anthropic(api_key=ANTHROPIC_API_KEY)
app.py+11-2
main.py+52-35