import sys import subprocess import logging import gradio as gr import requests import os from typing import Dict, Tuple logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) required_packages = ['gradio', 'requests'] for package in required_packages: try: __import__(package) except ImportError: print(f"{package} not found. Installing...") install(package) if not os.environ.get("CODEPAL_API_KEY"): print("Error: CODEPAL_API_KEY environment variable is not set.") print("Please set it and try again.") sys.exit(1) # Constants DEFAULTS = { "SYSTEM_MESSAGE": "You are CodePal.ai, an expert AI assistant specialized in helping programmers. You generate clean, efficient, and well-documented code based on user requirements.", "MAX_TOKENS": 4000, "TEMPERATURE": 0.7, "TOP_P": 0.95, } API_URLS = { "CODE_GENERATOR": "https://api.codepal.ai/v1/code-generator/query", "CODE_FIXER": "https://api.codepal.ai/v1/code-fixer/query", "CODE_EXTENDER": "https://api.codepal.ai/v1/code-extender/query", } def check_api_endpoints(): for name, url in API_URLS.items(): try: response = requests.head(url) if response.status_code == 200: print(f"{name} API endpoint is accessible.") else: print(f"Warning: {name} API endpoint returned status code {response.status_code}") except requests.RequestException as e: print(f"Error accessing {name} API endpoint: {str(e)}") check_api_endpoints() def get_api_key() -> str: """Fetch API key from environment variables.""" return os.environ.get("CODEPAL_API_KEY", "") def is_api_key_valid() -> bool: """Validate if the API key is set and not a placeholder.""" api_key = get_api_key() return bool(api_key) and api_key != "YOUR_API_KEY" def build_request_data(language: str, instructions: str, flavor: str, max_tokens: int, temperature: float, top_p: float) -> Dict: """Construct the request data for API calls.""" return { "language": language, "instructions": instructions, "flavor": flavor, "max_tokens": max_tokens, "temperature": temperature, "top_p": top_p } def handle_api_response(response) -> Tuple[bool, str]: """Handle API response and return success status and result.""" if response.status_code != 200: error_message = "API request failed" try: error_data = response.json() error_message = error_data.get("error", error_message) except Exception: error_message = f"API request failed with status code {response.status_code}" return False, f"Error: {error_message}" result = response.json() if "error" in result: return False, f"Error: {result['error']}" return True, result["result"] def generate_code(language: str, requirements: str, code_style: str, include_tests: bool, max_tokens: int = DEFAULTS["MAX_TOKENS"], temperature: float = DEFAULTS["TEMPERATURE"], top_p: float = DEFAULTS["TOP_P"]) -> Tuple[bool, str]: """Generate code using CodePal.ai API.""" try: if not is_api_key_valid(): return False, "Error: CodePal.ai API key is not configured. Please set the CODEPAL_API_KEY environment variable." flavor = { "minimal": "minimal", "verbose": "documented" }.get(code_style, "standard") if code_style in ["minimal", "verbose"] else "tests" if include_tests else "standard" api_key = get_api_key() headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } data = build_request_data(language, requirements, flavor, max_tokens, temperature, top_p) response = requests.post(API_URLS["CODE_GENERATOR"], headers=headers, json=data) return handle_api_response(response) except Exception as e: logger.error(f"Error in generate_code: {str(e)}") return False, f"Error: {str(e)}" # Launch the app (if applicable) if __name__ == "__main__": try: app.launch(share=True) # Modify based on your application's entry point except Exception as e: print(f"Error starting the Gradio application: {str(e)}") sys.exit(1)