24f3001764/llm_code_deployment
0
1"""2Validate environment setup for LLM Code Deployment API3Run this before starting the server to ensure everything is configured correctly4"""5import os6import sys7from pathlib import Path8from dotenv import load_dotenv9 10# Load environment variables11load_dotenv()12 13def print_header(text):14 """Print formatted header"""15 print("\n" + "=" * 60)16 print(f" {text}")17 print("=" * 60)18 19def check_env_var(name, required=True):20 """Check if environment variable is set"""21 value = os.getenv(name)22 if value:23 # Mask sensitive values24 if any(keyword in name.lower() for keyword in ['secret', 'key', 'token', 'password']):25 masked = value[:4] + '*' * (len(value) - 8) + value[-4:] if len(value) > 8 else '*' * len(value)26 print(f" ✅ {name}: {masked}")27 else:28 print(f" ✅ {name}: {value}")29 return True30 else:31 if required:32 print(f" ❌ {name}: NOT SET (required)")33 return False34 else:35 print(f" ⚠️ {name}: NOT SET (optional)")36 return True37 38def check_python_version():39 """Check Python version"""40 version = sys.version_info41 if version.major == 3 and version.minor >= 10:42 print(f" ✅ Python {version.major}.{version.minor}.{version.micro}")43 return True44 else:45 print(f" ❌ Python {version.major}.{version.minor}.{version.micro} (requires 3.10+)")46 return False47 48def check_dependencies():49 """Check if required packages are installed"""50 required_packages = [51 'fastapi',52 'uvicorn',53 'pydantic',54 'openai',55 'httpx',56 'github',57 'aiofiles',58 'dotenv'59 ]60 61 all_installed = True62 for package in required_packages:63 try:64 __import__(package)65 print(f" ✅ {package}")66 except ImportError:67 print(f" ❌ {package} (not installed)")68 all_installed = False69 70 return all_installed71 72def check_directories():73 """Check if required directories exist"""74 dirs = ['src', 'test']75 all_exist = True76 77 for dir_name in dirs:78 dir_path = Path(dir_name)79 if dir_path.exists():80 print(f" ✅ {dir_name}/")81 else:82 print(f" ❌ {dir_name}/ (missing)")83 all_exist = False84 85 return all_exist86 87def check_api_keys():88 """Validate API keys format"""89 warnings = []90 91 # Check OpenAI API key format (warning only for non-standard keys like aipipe.org)92 openai_key = os.getenv('OPENAI_API_KEY', '')93 if openai_key:94 if not openai_key.startswith('sk-'):95 warnings.append("OpenAI API key should start with 'sk-' (unless using alternative provider like aipipe.org)")96 97 # Check GitHub token format98 github_token = os.getenv('GITHUB_TOKEN', '')99 if github_token:100 if not (github_token.startswith('ghp_') or github_token.startswith('gho_') or github_token.startswith('ghs_')):101 warnings.append("GitHub token should start with 'ghp_', 'gho_', or 'ghs_'")102 103 if warnings:104 for warning in warnings:105 print(f" ⚠️ {warning}")106 107 # Always return True since these are just warnings108 return True109 110def test_github_connection():111 """Test GitHub API connection"""112 try:113 from github import Github, Auth114 token = os.getenv('GITHUB_TOKEN')115 username = os.getenv('GITHUB_USERNAME')116 117 if not token or not username:118 print(" ⚠️ Cannot test - credentials not set")119 return False120 121 # Use new Auth method to avoid deprecation warning122 auth = Auth.Token(token)123 g = Github(auth=auth)124 user = g.get_user()125 126 if user.login.lower() == username.lower():127 print(f" ✅ Connected to GitHub as {user.login}")128 try:129 rate_limit = g.get_rate_limit()130 print(f" Remaining API calls: {rate_limit.core.remaining}")131 except:132 # Skip rate limit check if it fails133 pass134 return True135 else:136 print(f" ❌ GitHub username mismatch: {user.login} != {username}")137 return False138 139 except Exception as e:140 print(f" ❌ GitHub connection failed: {e}")141 return False142 143def test_openai_connection():144 """Test OpenAI API connection"""145 try:146 from openai import OpenAI147 api_key = os.getenv('OPENAI_API_KEY')148 base_url = os.getenv('OPENAI_BASE_URL', 'https://api.openai.com/v1') # ADD THIS LINE149 150 if not api_key:151 print(" ⚠️ Cannot test - API key not set")152 return False153 154 # Use custom base_url for alternative providers like aipipe.org155 client = OpenAI(api_key=api_key, base_url=base_url) # UPDATE THIS LINE156 157 # Try to list models to verify the key works158 models = client.models.list()159 print(f" ✅ Connected to OpenAI API")160 if base_url != 'https://api.openai.com/v1': # ADD THESE LINES161 print(f" Using custom endpoint: {base_url}")162 return True163 164 except Exception as e:165 print(f" ❌ OpenAI connection failed: {e}")166 return False167 168def main():169 """Run all validation checks"""170 print("\n🔍 LLM Code Deployment API - Setup Validation\n")171 172 all_checks_passed = True173 174 # Check Python version175 print_header("Python Version")176 if not check_python_version():177 all_checks_passed = False178 179 # Check environment variables180 print_header("Environment Variables")181 env_checks = [182 check_env_var('STUDENT_SECRET', required=True),183 check_env_var('OPENAI_API_KEY', required=True),184 check_env_var('GITHUB_TOKEN', required=True),185 check_env_var('GITHUB_USERNAME', required=True),186 check_env_var('API_HOST', required=False),187 check_env_var('PORT', required=False),188 ]189 if not all(env_checks):190 all_checks_passed = False191 print("\n 💡 Copy .env.example to .env and fill in your credentials")192 193 # Check API key formats194 print_header("API Key Validation")195 if not check_api_keys():196 all_checks_passed = False197 198 # Check dependencies199 print_header("Python Dependencies")200 if not check_dependencies():201 all_checks_passed = False202 print("\n 💡 Install dependencies with: pip install -r requirements.txt")203 204 # Check directories205 print_header("Project Structure")206 if not check_directories():207 all_checks_passed = False208 209 # Test API connections210 print_header("GitHub API Connection")211 if not test_github_connection():212 all_checks_passed = False213 214 print_header("OpenAI API Connection")215 if not test_openai_connection():216 all_checks_passed = False217 218 # Final summary219 print_header("Summary")220 if all_checks_passed:221 print("\n ✅ All checks passed! You're ready to start the server.")222 print("\n 🚀 Start the server with:")223 print(" python -m src.main")224 print("\n 🧪 Test the API with:")225 print(" python test/test_client.py")226 else:227 print("\n ❌ Some checks failed. Please fix the issues above.")228 print("\n 📚 See SETUP.md for detailed setup instructions")229 230 print("\n" + "=" * 60 + "\n")231 232 return 0 if all_checks_passed else 1233 234if __name__ == "__main__":235 sys.exit(main())236 