Spaces:
Paused
Paused
Revert httpx.Client customization: use default OpenAI SDK settings for async compatibility in HF Spaces
Browse filesFiles changed (2)
- main.py+8-27
- test_api_connection.pyAdded+151
2 unmodified lines3456789242 unmodified lines252253254255256257258259260261262263264265266267268269270271390 unmodified lines66266366466566666766866967067167267367469 unmodified lines7447457467477487497507517527537547557567572 unmodified linesimport jsonimport timeimport boto3import httpxfrom pathlib import Pathfrom typing import Dict, List, Optional, Tuple, Anyfrom anthropic import Anthropic242 unmodified linesif provider == ModelProvider.OPENAI:if not OPENAI_API_KEY:raise ValueError(f"OpenAI API key not configured. Please set OPENAI_API_KEY environment variable to use {provider.value} provider.")self.client = openai.OpenAI(api_key=OPENAI_API_KEY,timeout=120.0,http_client=httpx.Client(http2=False, timeout=120.0))elif provider == ModelProvider.DEEPSEEK:if not DEEPSEEK_API_KEY:raise ValueError(f"DeepSeek API key not configured. Please set DEEPSEEK_API_KEY environment variable to use {provider.value} provider.")self.client = openai.OpenAI(api_key=DEEPSEEK_API_KEY,base_url="https://api.deepseek.com",timeout=120.0,http_client=httpx.Client(http2=False, timeout=120.0))elif provider == ModelProvider.ANTHROPIC:if not ANTHROPIC_API_KEY:raise ValueError(f"Anthropic API key not configured. Please set ANTHROPIC_API_KEY environment variable to use {provider.value} provider.")390 unmodified linesraise Exception(f"Текст судового рішення занадто короткий або відсутній (довжина: {len(court_decision_text) if court_decision_text else 0} символів). Будь ласка, перевірте вхідні дані.")if provider == ModelProvider.OPENAI.value:# Increase timeout for complex models and HF Spaces environment# Use specific http_client with HTTP/2 disabled to resolve Connection Errors in some environmentsclient = OpenAI(api_key=OPENAI_API_KEY,timeout=120.0,http_client=httpx.Client(http2=False, timeout=120.0))# Retry logic for connection errorsmax_retries = 369 unmodified lines}if provider == ModelProvider.DEEPSEEK.value:# Increase timeout and improve reliability for DeepSeek API# Use specific http_client with HTTP/2 disabled to resolve Connection Errorsclient = OpenAI(api_key=DEEPSEEK_API_KEY,base_url="https://api.deepseek.com",timeout=120.0,http_client=httpx.Client(http2=False, timeout=120.0))# Retry logic for DeepSeekmax_retries = 32 unmodified lines345678242 unmodified lines251252253254255256257258259260261262263390 unmodified lines65465565665765865966066169 unmodified lines7317327337347357367377382 unmodified linesimport jsonimport timeimport boto3from pathlib import Pathfrom typing import Dict, List, Optional, Tuple, Anyfrom anthropic import Anthropic242 unmodified linesif provider == ModelProvider.OPENAI:if not OPENAI_API_KEY:raise ValueError(f"OpenAI API key not configured. Please set OPENAI_API_KEY environment variable to use {provider.value} provider.")# Use default httpx settings for better compatibility with async environmentsself.client = openai.OpenAI(api_key=OPENAI_API_KEY, timeout=120.0)elif provider == ModelProvider.DEEPSEEK:if not DEEPSEEK_API_KEY:raise ValueError(f"DeepSeek API key not configured. Please set DEEPSEEK_API_KEY environment variable to use {provider.value} provider.")# Use default httpx settings for better compatibility with async environmentsself.client = openai.OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com", timeout=120.0)elif provider == ModelProvider.ANTHROPIC:if not ANTHROPIC_API_KEY:raise ValueError(f"Anthropic API key not configured. Please set ANTHROPIC_API_KEY environment variable to use {provider.value} provider.")390 unmodified linesraise Exception(f"Текст судового рішення занадто короткий або відсутній (довжина: {len(court_decision_text) if court_decision_text else 0} символів). Будь ласка, перевірте вхідні дані.")if provider == ModelProvider.OPENAI.value:# Use default OpenAI client settings for async compatibility in HF Spacesclient = OpenAI(api_key=OPENAI_API_KEY, timeout=120.0)# Retry logic for connection errorsmax_retries = 369 unmodified lines}if provider == ModelProvider.DEEPSEEK.value:# Use default client settings for async compatibility in HF Spacesclient = OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com", timeout=120.0)# Retry logic for DeepSeekmax_retries = 3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151#!/usr/bin/env python3"""Test script to verify API connections for OpenAI and DeepSeek"""import osimport httpxfrom dotenv import load_dotenvfrom openai import OpenAI
# Load environment variablesload_dotenv()
def test_openai(): """Test OpenAI API connection""" print("\n" + "="*60) print("Testing OpenAI API Connection") print("="*60) api_key = os.getenv("OPENAI_API_KEY") if not api_key: print("❌ OPENAI_API_KEY not found in environment") return False print(f"✓ API Key found (length: {len(api_key)})") try: # Test with HTTP/2 enabled (default) print("\n[Test 1] Using default settings (HTTP/2 enabled)...") client = OpenAI(api_key=api_key, timeout=30.0) response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "Say 'connection test passed'"}], max_tokens=10 ) print(f"✅ Success with HTTP/2: {response.choices[0].message.content}") except Exception as e: print(f"❌ Failed with HTTP/2: {type(e).__name__}: {str(e)}") try: # Test with HTTP/2 disabled print("\n[Test 2] Using HTTP/1.1 (HTTP/2 disabled)...") client = OpenAI( api_key=api_key, timeout=30.0, http_client=httpx.Client(http2=False, timeout=30.0) ) response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "Say 'connection test passed'"}], max_tokens=10 ) print(f"✅ Success with HTTP/1.1: {response.choices[0].message.content}") return True except Exception as e: print(f"❌ Failed with HTTP/1.1: {type(e).__name__}: {str(e)}") return False
def test_deepseek(): """Test DeepSeek API connection""" print("\n" + "="*60) print("Testing DeepSeek API Connection") print("="*60) api_key = os.getenv("DEEPSEEK_API_KEY") if not api_key: print("❌ DEEPSEEK_API_KEY not found in environment") return False print(f"✓ API Key found (length: {len(api_key)})") try: # Test with HTTP/2 enabled (default) print("\n[Test 1] Using default settings (HTTP/2 enabled)...") client = OpenAI( api_key=api_key, base_url="https://api.deepseek.com", timeout=30.0 ) response = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": "Say 'connection test passed'"}], max_tokens=10 ) print(f"✅ Success with HTTP/2: {response.choices[0].message.content}") except Exception as e: print(f"❌ Failed with HTTP/2: {type(e).__name__}: {str(e)}") try: # Test with HTTP/2 disabled print("\n[Test 2] Using HTTP/1.1 (HTTP/2 disabled)...") client = OpenAI( api_key=api_key, base_url="https://api.deepseek.com", timeout=30.0, http_client=httpx.Client(http2=False, timeout=30.0) ) response = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": "Say 'connection test passed'"}], max_tokens=10 ) print(f"✅ Success with HTTP/1.1: {response.choices[0].message.content}") return True except Exception as e: print(f"❌ Failed with HTTP/1.1: {type(e).__name__}: {str(e)}") return False
def test_network_connectivity(): """Test basic network connectivity""" print("\n" + "="*60) print("Testing Network Connectivity") print("="*60) urls = [ "https://api.openai.com", "https://api.deepseek.com", "https://api.anthropic.com", "https://generativelanguage.googleapis.com" ] for url in urls: try: client = httpx.Client(timeout=10.0) response = client.get(url) print(f"✅ {url}: HTTP {response.status_code}") except Exception as e: print(f"❌ {url}: {type(e).__name__}: {str(e)}")
if __name__ == "__main__": print("\n🔍 API Connection Test Suite") print("="*60) # Test network connectivity first test_network_connectivity() # Test OpenAI openai_ok = test_openai() # Test DeepSeek deepseek_ok = test_deepseek() # Summary print("\n" + "="*60) print("Summary") print("="*60) print(f"OpenAI: {'✅ OK' if openai_ok else '❌ FAILED'}") print(f"DeepSeek: {'✅ OK' if deepseek_ok else '❌ FAILED'}") print("="*60)main.py+8-27
test_api_connection.pyAdded+151