File size: 7,715 Bytes
53e0bdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import json
import os
from typing import Any, Dict

from anthropic import Anthropic
from mistralai import Mistral
from openai import OpenAI
from pydantic import BaseModel, ValidationError

# ------------------------------------------------------------------ #
# Configuration
# ------------------------------------------------------------------ #

DEFAULT_SCORES: Dict[str, Any] = {
    "vulnerability_score": 0,
    "style_score": 0,
    "quality_score": 0,
}

ANALYSIS_PROMPT_TEMPLATE = (
    "Analyze the following code for vulnerabilities, style, and quality "
    "and return **only** a JSON object with keys "
    "'vulnerability_score', 'style_score', and 'quality_score' "
    "(each 0–100):\n```python\n{code}\n```"
)

SYSTEM_MESSAGES = {
    "anthropic": "You are a secure-coding assistant. Assess code quality, style and vulnerabilities.",
    "mistral": "You are a secure-coding assistant. Assess code quality, style and vulnerabilities.",
    "openai": "You are a secure-coding assistant. Assess code quality, style and vulnerabilities.",
}

MODELS = {
    "anthropic": "claude-sonnet-4-20250514",
    "mistral": "mistral-medium-2505",
    "openai": "gpt-4.1-2025-04-14",
}

REQUIRED_KEYS = ("vulnerability_score", "style_score", "quality_score")

# ------------------------------------------------------------------ #
# Helpers
# ------------------------------------------------------------------ #


class CodeAnalysisResult(BaseModel):
    vulnerability_score: int
    style_score: int
    quality_score: int


def _safe_json_loads(raw: str) -> Dict[str, Any]:
    """
    Best-effort JSON parsing – fall back to DEFAULT_SCORES on failure.
    """
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return DEFAULT_SCORES.copy()


def _ensure_all_keys(d: dict, default: int = 0) -> dict:
    """
    Return a dict that has every REQUIRED_KEYS entry.
    Missing keys are added with `default`.
    Non-required keys are discarded.
    """
    return {key: int(d.get(key, default)) for key in REQUIRED_KEYS}


# ------------------------------------------------------------------ #
# Provider wrappers
# ------------------------------------------------------------------ #


def analyze_code_anthropic(code: str) -> dict:
    if not code:
        return _ensure_all_keys({})

    try:
        client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
        prompt = ANALYSIS_PROMPT_TEMPLATE.format(code=code)

        tools = [
            {
                "name": "code_scores",
                "description": "Return ONLY the three integer scores (0-100).",
                "input_schema": {
                    "type": "object",
                    "properties": {
                        "vulnerability_score": {
                            "type": "integer",
                            "minimum": 0,
                            "maximum": 100,
                        },
                        "style_score": {
                            "type": "integer",
                            "minimum": 0,
                            "maximum": 100,
                        },
                        "quality_score": {
                            "type": "integer",
                            "minimum": 0,
                            "maximum": 100,
                        },
                    },
                    "required": list(REQUIRED_KEYS),
                    "additionalProperties": False,
                },
            }
        ]

        resp = client.messages.create(
            model=MODELS["anthropic"],
            messages=[{"role": "user", "content": prompt}],
            system=SYSTEM_MESSAGES["anthropic"],
            tools=tools,
            tool_choice={"type": "tool", "name": "code_scores"},
            max_tokens=130,
            temperature=0,
        )

        tool_call = next(c for c in resp.content if c.type == "tool_use")
        return _ensure_all_keys(tool_call.input)

    except Exception as exc:
        out = _ensure_all_keys({})
        out["error"] = f"Anthropic API error: {exc}"
        return out


def analyze_code_mistral(code: str) -> Dict[str, Any]:
    if not code:
        return DEFAULT_SCORES.copy()

    try:
        client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
        prompt = ANALYSIS_PROMPT_TEMPLATE.format(code=code)

        resp = client.chat.complete(
            model=MODELS["mistral"],
            messages=[
                {"role": "system", "content": SYSTEM_MESSAGES["mistral"]},
                {"role": "user", "content": prompt},
            ],
            response_format={"type": "json_object"},
        )

        return _safe_json_loads(resp.choices[0].message.content)

    except Exception as exc:
        result = DEFAULT_SCORES.copy()
        result["error"] = f"Mistral API error: {exc}"
        return result


def analyze_code_openai(code: str) -> Dict[str, Any]:
    if not code:
        return DEFAULT_SCORES.copy()

    try:
        client = OpenAI()  # uses OPENAI_API_KEY from env
        prompt = ANALYSIS_PROMPT_TEMPLATE.format(code=code)

        resp = client.chat.completions.create(
            model=MODELS["openai"],
            messages=[
                {"role": "system", "content": SYSTEM_MESSAGES["openai"]},
                {"role": "user", "content": prompt},
            ],
            response_format={"type": "json_object"},
        )

        # Validate via Pydantic (optional but nice)
        parsed = _safe_json_loads(resp.choices[0].message.content)
        try:
            validated = CodeAnalysisResult(**parsed)
            return validated.model_dump()
        except ValidationError:
            # If model returns extra fields or wrong types, fall back to raw
            return parsed

    except Exception as exc:
        result = DEFAULT_SCORES.copy()
        result["error"] = f"OpenAI API error: {exc}"
        return result


# ------------------------------------------------------------------ #
# Aggregator
# ------------------------------------------------------------------ #


def code_analysis_score(code: str) -> Dict[str, Any]:
    """
    Analyzes the provided code string using multiple AI providers and returns an
    averaged score across vulnerability, style, and quality.

    Args:
        code: The code string to analyze.

    Returns:
        A dictionary containing the averaged vulnerability, style, and quality scores,
        or an error message if all providers fail.
    """
    if not code:
        return DEFAULT_SCORES.copy()

    scores_list = [
        analyze_code_anthropic(code),
        analyze_code_mistral(code),
        analyze_code_openai(code),
    ]
    valid = [s for s in scores_list if "error" not in s]

    if not valid:
        result = DEFAULT_SCORES.copy()
        result["error"] = "All API providers failed"
        return result

    # Average
    averaged = {
        "vulnerability_score": sum(s["vulnerability_score"] for s in valid)
        // len(valid),
        "style_score": sum(s["style_score"] for s in valid) // len(valid),
        "quality_score": sum(s["quality_score"] for s in valid) // len(valid),
    }
    return averaged


# ------------------------------------------------------------------ #
# Demo / quick test
# ------------------------------------------------------------------ #

if __name__ == "__main__":
    sample = """
def example_function(x):
    if x is None:
        return "Error"
    return x * 2
"""

    print("Anthropic β†’", analyze_code_anthropic(sample))
    print("Mistral   β†’", analyze_code_mistral(sample))
    print("OpenAI    β†’", analyze_code_openai(sample))
    print("AVERAGED  β†’", code_analysis_score(sample))