File size: 3,262 Bytes
0109502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import json, os, random, time, httpx
from dotenv import load_dotenv

load_dotenv()

SYSTEM = (
    "Return ONLY JSON with keys valid,scores,overall_score,dominant_topic,"
    "secondary_topics,summary,issues. scores must contain correctness,"
    "instruction_alignment,quality,training_value,scope_fit, all integers 0-100. "
    "Be strict, concise, and do not reward unnecessary complexity."
)


class NIMReviewer:
    def __init__(self, topics, retries=3, base_delay=1):
        self.topics = topics
        self.retries = retries
        self.base_delay = base_delay
        self.base = os.getenv("NIM_BASE_URL", "https://integrate.api.nvidia.com/v1").rstrip("/")
        self.model = os.getenv("NIM_MODEL")
        self.key = os.getenv("NIM_API_KEY")
        if not self.model or not self.key:
            raise RuntimeError("Set NIM_MODEL and NIM_API_KEY")

    def review(self, instruction, user_input, code):
        allowed = "\n".join(f"- {k}: {v}" for k, v in self.topics.items())
        prompt = (
            f"Allowed topics:\n{allowed}\n\nInstruction:\n{instruction}\n\n"
            f"Input:\n{user_input}\n\nCode:\n```python\n{code}\n```"
        )
        payload = {
            "model": self.model,
            "messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}],
            "temperature": 0,
            "max_tokens": 800,
            "response_format": {"type": "json_object"},
        }

        for attempt in range(1, self.retries + 1):
            try:
                with httpx.Client(timeout=60) as c:
                    r = c.post(
                        self.base + "/chat/completions",
                        headers={"Authorization": f"Bearer {self.key}"},
                        json=payload,
                    )
            except (httpx.TimeoutException, httpx.TransportError) as e:
                # Network-level failures: retryable.
                if attempt == self.retries:
                    raise RuntimeError(f"nim_retry_exhausted: {type(e).__name__}: {e}") from e
                time.sleep(self.base_delay * 2 ** (attempt - 1) + random.uniform(0, 0.5))
                continue

            if r.status_code == 429 or 500 <= r.status_code < 600:
                # Rate limit / server error: retryable.
                if attempt == self.retries:
                    raise RuntimeError(
                        f"nim_retry_exhausted: HTTPStatusError: {r.status_code} {r.reason_phrase}"
                    )
                time.sleep(self.base_delay * 2 ** (attempt - 1) + random.uniform(0, 0.5))
                continue

            if r.status_code >= 400:
                # Any other 4xx (400 bad request, 401 bad key, 403 forbidden, 404, ...)
                # will fail identically on every attempt. Fail immediately instead of
                # burning retries and obscuring the real error.
                raise RuntimeError(
                    f"nim_request_failed_non_retryable: HTTP {r.status_code} {r.reason_phrase}: "
                    f"{r.text[:500]}"
                )

            r.raise_for_status()
            raw = r.json()
            return json.loads(raw["choices"][0]["message"]["content"]), raw, attempt