File size: 4,505 Bytes
a90a47c
 
 
9997dfd
b637fc4
 
 
9997dfd
a90a47c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b637fc4
 
 
 
 
 
 
9997dfd
b637fc4
 
 
 
 
 
a90a47c
 
 
 
 
 
 
 
 
 
 
 
 
b637fc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a90a47c
 
 
b637fc4
 
 
a90a47c
 
b637fc4
a90a47c
 
 
 
b637fc4
a90a47c
 
 
 
 
b637fc4
a90a47c
 
b637fc4
 
a90a47c
b637fc4
 
a90a47c
9997dfd
b637fc4
a90a47c
b637fc4
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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)