File size: 6,899 Bytes
165ed2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
from __future__ import annotations

import hashlib
import json
import os
import random
import re
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from typing import Any


RETRY_CODES = {429, 500, 502, 503, 504}


def canonical_json(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))


def sha256_json(value: Any) -> str:
    return hashlib.sha256(canonical_json(value).encode()).hexdigest()


def extract_json(text: str) -> Any:
    text = text.strip()
    if text.startswith("```"):
        text = re.sub(r"^```(?:json)?\s*", "", text)
        text = re.sub(r"\s*```$", "", text)
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        starts = [i for i in (text.find("["), text.find("{")) if i >= 0]
        if not starts:
            raise
        start = min(starts)
        for end in range(len(text), start, -1):
            try:
                return json.loads(text[start:end])
            except json.JSONDecodeError:
                continue
        raise


@dataclass
class ReviewResponse:
    raw_body: dict
    text: str
    parsed: Any
    usage: dict
    model_version: str
    latency_seconds: float
    request_hash: str
    response_hash: str
    status_code: int


class ReviewClient:
    def __init__(
        self,
        api_type: str,
        base_url: str,
        api_key: str,
        model: str,
        timeout: int = 180,
        retries: int = 5,
        extra_body: dict | None = None,
    ):
        self.api_type = api_type
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key
        self.model = model
        self.timeout = timeout
        self.retries = retries
        self.extra_body = extra_body or {}
        if api_type not in {
            "openai_compatible", "anthropic_compatible", "generic_http_json",
            "local_openai_compatible", "custom_adapter",
        }:
            raise ValueError(f"unsupported REVIEW_API_TYPE: {api_type}")

    def _request_spec(self, system: str, user: str, max_tokens: int) -> tuple[str, dict, dict]:
        if self.api_type == "anthropic_compatible":
            url = self.base_url + "/messages"
            body = {
                "model": self.model,
                "max_tokens": max_tokens,
                "system": system,
                "messages": [{"role": "user", "content": user}],
            }
            body.update(self.extra_body)
            headers = {
                "content-type": "application/json",
                "x-api-key": self.api_key,
                "anthropic-version": "2023-06-01",
            }
            return url, body, headers
        if self.api_type in {"openai_compatible", "local_openai_compatible"}:
            url = self.base_url + "/chat/completions"
            body = {
                "model": self.model,
                "temperature": 0,
                "max_tokens": max_tokens,
                "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
            }
            body.update(self.extra_body)
            return url, body, {"content-type": "application/json", "authorization": f"Bearer {self.api_key}"}
        url = self.base_url
        body = {"model": self.model, "system": system, "input": user, "max_tokens": max_tokens}
        body.update(self.extra_body)
        return url, body, {"content-type": "application/json", "authorization": f"Bearer {self.api_key}"}

    def _parse_text(self, payload: dict) -> tuple[str, dict, str]:
        if self.api_type == "anthropic_compatible":
            text = "\n".join(
                block.get("text", "") for block in payload.get("content", [])
                if isinstance(block, dict) and block.get("type") == "text"
            )
            usage = payload.get("usage", {})
            model_version = str(payload.get("model", self.model))
            return text, usage, model_version
        if self.api_type in {"openai_compatible", "local_openai_compatible"}:
            text = payload["choices"][0]["message"]["content"]
            return text, payload.get("usage", {}), str(payload.get("model", self.model))
        text = payload.get("output") or payload.get("text") or payload.get("response") or ""
        return str(text), payload.get("usage", {}), str(payload.get("model", self.model))

    def complete_json(self, system: str, user: str, max_tokens: int = 4096) -> ReviewResponse:
        url, body, headers = self._request_spec(system, user, max_tokens)
        public_request = {"url_host": urllib.parse.urlparse(url).netloc, "body": body}
        request_hash = sha256_json(public_request)
        encoded = canonical_json(body).encode()
        last_error: Exception | None = None
        for attempt in range(self.retries + 1):
            started = time.monotonic()
            try:
                request = urllib.request.Request(url, data=encoded, headers=headers, method="POST")
                with urllib.request.urlopen(request, timeout=self.timeout) as response:
                    raw = response.read().decode("utf-8", errors="replace")
                    payload = json.loads(raw)
                    text, usage, model_version = self._parse_text(payload)
                    parsed = extract_json(text)
                    return ReviewResponse(
                        raw_body=payload, text=text, parsed=parsed, usage=usage,
                        model_version=model_version, latency_seconds=time.monotonic() - started,
                        request_hash=request_hash, response_hash=hashlib.sha256(raw.encode()).hexdigest(),
                        status_code=response.status,
                    )
            except urllib.error.HTTPError as exc:
                last_error = exc
                if exc.code not in RETRY_CODES or attempt >= self.retries:
                    raise
            except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
                last_error = exc
                if attempt >= self.retries:
                    raise
            delay = min(60.0, (2 ** attempt) + random.random())
            time.sleep(delay)
        raise RuntimeError(f"request failed: {type(last_error).__name__}")


def client_from_env(api_key: str) -> ReviewClient:
    extra = {}
    if os.environ.get("REVIEW_EXTRA_BODY_JSON"):
        extra = json.loads(os.environ["REVIEW_EXTRA_BODY_JSON"])
    return ReviewClient(
        api_type=os.environ.get("REVIEW_API_TYPE", "anthropic_compatible"),
        base_url=os.environ["REVIEW_API_BASE_URL"],
        api_key=api_key,
        model=os.environ["REVIEW_MODEL_PRIMARY"],
        timeout=int(os.environ.get("REVIEW_TIMEOUT_SECONDS", "180")),
        retries=int(os.environ.get("REVIEW_MAX_RETRIES", "5")),
        extra_body=extra,
    )