api_client.py 9.53 KB
Newer Older
raojy's avatar
first  
raojy committed
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
from __future__ import annotations

import json
import time
from dataclasses import dataclass
from typing import Any

import httpx

try:
    from .config import SenseNovaConfig, load_config
    from .image_utils import MAX_IMAGE_BYTES, is_http_url, is_supported_vision_image_url
except ImportError:  # pragma: no cover - supports direct test imports
    from config import SenseNovaConfig, load_config
    from image_utils import MAX_IMAGE_BYTES, is_http_url, is_supported_vision_image_url

CHAT_MODELS = ("sensenova-6.7-flash-lite", "deepseek-v4")
VISION_MODELS = ("sensenova-6.7-flash-lite",)
IMAGE_MODELS = ("sensenova-u1-fast",)
IMAGE_SIZES = (
    "2752x1536",
    "1536x2752",
    "2048x2048",
    "2496x1664",
    "1664x2496",
    "2368x1760",
    "1760x2368",
    "2272x1824",
    "1824x2272",
    "3072x1376",
    "1344x3136",
)
IMAGE_SIZE_OPTIONS = (
    "2752x1536|16:9",
    "1536x2752|9:16",
    "2048x2048|1:1",
    "2496x1664|3:2",
    "1664x2496|2:3",
    "2368x1760|4:3",
    "1760x2368|3:4",
    "2272x1824|5:4",
    "1824x2272|4:5",
    "3072x1376|21:9",
    "1344x3136|9:21",
)


@dataclass(frozen=True)
class ChatResult:
    text: str
    usage: dict[str, Any]
    raw: dict[str, Any]


@dataclass(frozen=True)
class ImageGenerationResult:
    image_base64: str
    image_url: str
    image_bytes: bytes
    raw: dict[str, Any]


class SenseNovaClient:
    def __init__(self, config: SenseNovaConfig):
        self.config = config

    @classmethod
    def from_env(cls) -> SenseNovaClient:
        return cls(load_config())

    def chat(
        self,
        *,
        text: str,
        system_prompt: str,
        model: str,
        temperature: float,
        top_p: float,
        max_tokens: int,
        timeout: int,
    ) -> ChatResult:
        if model not in CHAT_MODELS:
            raise RuntimeError(f"Unsupported chat model: {model}")
        if not text.strip():
            raise RuntimeError("Chat text cannot be empty.")

        payload: dict[str, Any] = {
            "model": model,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": text},
            ],
            "stream": False,
            "temperature": temperature,
            "top_p": top_p,
            "max_tokens": max_tokens,
        }
        raw = self._post_json("/chat/completions", payload, timeout=timeout)
        return ChatResult(text=_extract_chat_text(raw), usage=raw.get("usage", {}), raw=raw)

    def vision_chat(
        self,
        *,
        image_url: str,
        prompt: str,
        system_prompt: str,
        model: str,
        temperature: float,
        top_p: float,
        max_tokens: int,
        timeout: int,
    ) -> ChatResult:
        if model not in VISION_MODELS:
            raise RuntimeError(f"Unsupported vision model: {model}")
        if not prompt.strip():
            raise RuntimeError("Vision prompt cannot be empty.")
        if not is_supported_vision_image_url(image_url):
            raise RuntimeError("Vision image URL must be http(s) or a base64 image data URL.")

        payload: dict[str, Any] = {
            "model": model,
            "messages": [
                {"role": "system", "content": system_prompt},
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": prompt},
                        {"type": "image_url", "image_url": {"url": image_url}},
                    ],
                },
            ],
            "stream": False,
            "temperature": temperature,
            "top_p": top_p,
            "max_tokens": max_tokens,
        }
        raw = self._post_json("/chat/completions", payload, timeout=timeout)
        return ChatResult(text=_extract_chat_text(raw), usage=raw.get("usage", {}), raw=raw)

    def generate_image(
        self,
        *,
        prompt: str,
        model: str,
        size: str,
        timeout: int,
    ) -> ImageGenerationResult:
        if model not in IMAGE_MODELS:
            raise RuntimeError(f"Unsupported image model: {model}")
        normalized_size = normalize_image_size(size)
        if normalized_size not in IMAGE_SIZES:
            raise RuntimeError(f"Unsupported image size: {size}")
        if not prompt.strip():
            raise RuntimeError("Image prompt cannot be empty.")

        payload: dict[str, Any] = {
            "model": model,
            "prompt": prompt,
            "size": normalized_size,
            "n": 1,
        }
        raw = self._post_json("/images/generations", payload, timeout=timeout)
        image_base64, image_url = _extract_image_payload(raw)

        image_bytes = b""
        if image_base64:
            import base64

            try:
                from .image_utils import strip_data_url
            except ImportError:  # pragma: no cover - supports direct test imports
                from image_utils import strip_data_url

            image_bytes = base64.b64decode(strip_data_url(image_base64), validate=True)
        elif image_url:
            image_bytes = self.download_image(image_url, timeout=timeout)
        else:
            raise RuntimeError("Image response did not contain b64_json, base64, or url.")

        return ImageGenerationResult(
            image_base64=image_base64,
            image_url=image_url,
            image_bytes=image_bytes,
            raw=raw,
        )

    def download_image(self, url: str, *, timeout: int) -> bytes:
        if not is_http_url(url):
            raise RuntimeError("Image URL must use http or https.")

        try:
            with (
                httpx.Client(timeout=timeout, follow_redirects=True) as client,
                client.stream("GET", url) as response,
            ):
                response.raise_for_status()
                chunks: list[bytes] = []
                total = 0
                for chunk in response.iter_bytes():
                    total += len(chunk)
                    if total > MAX_IMAGE_BYTES:
                        raise RuntimeError("Downloaded image is larger than 50MB.")
                    chunks.append(chunk)
                return b"".join(chunks)
        except httpx.HTTPStatusError as exc:
            status_code = exc.response.status_code
            raise RuntimeError(f"Image download failed with HTTP {status_code}.") from exc
        except httpx.HTTPError as exc:
            raise RuntimeError(f"Image download failed: {exc.__class__.__name__}.") from exc

    def _post_json(self, path: str, payload: dict[str, Any], *, timeout: int) -> dict[str, Any]:
        url = f"{self.config.base_url}{path}"
        headers = {
            "Authorization": f"Bearer {self.config.api_key}",
            "Content-Type": "application/json",
        }

        last_error: Exception | None = None
        for attempt in range(3):
            try:
                with httpx.Client(timeout=timeout) as client:
                    response = client.post(url, headers=headers, json=payload)
                if response.status_code in {429, 500, 502, 503, 504} and attempt < 2:
                    time.sleep(2**attempt)
                    continue
                response.raise_for_status()
                return response.json()
            except httpx.HTTPStatusError as exc:
                status_code = exc.response.status_code
                if status_code in {429, 500, 502, 503, 504} and attempt < 2:
                    time.sleep(2**attempt)
                    last_error = exc
                    continue
                raise RuntimeError(_format_api_error(exc.response, self.config.api_key)) from exc
            except httpx.HTTPError as exc:
                if attempt < 2:
                    time.sleep(2**attempt)
                    last_error = exc
                    continue
                raise RuntimeError(f"SenseNova request failed: {exc.__class__.__name__}.") from exc
            except json.JSONDecodeError as exc:
                raise RuntimeError("SenseNova response was not valid JSON.") from exc

        raise RuntimeError(f"SenseNova request failed: {last_error.__class__.__name__}.")


def _extract_chat_text(raw: dict[str, Any]) -> str:
    try:
        return raw["choices"][0]["message"]["content"]
    except (KeyError, IndexError, TypeError) as exc:
        raise RuntimeError("Chat response did not contain choices[0].message.content.") from exc


def normalize_image_size(size: str) -> str:
    return size.split("|", 1)[0].strip()


def _extract_image_payload(raw: dict[str, Any]) -> tuple[str, str]:
    try:
        first = raw["data"][0]
    except (KeyError, IndexError, TypeError) as exc:
        raise RuntimeError("Image response did not contain data[0].") from exc

    if not isinstance(first, dict):
        raise RuntimeError("Image response data[0] was not an object.")

    image_base64 = first.get("b64_json") or first.get("base64") or first.get("image_base64") or ""
    image_url = first.get("url") or ""
    return str(image_base64), str(image_url)


def _format_api_error(response: httpx.Response, api_key: str = "") -> str:
    message = ""
    try:
        body = response.json()
        message = body.get("error", {}).get("message") or body.get("message") or ""
    except Exception:
        message = response.text[:500]

    if message:
        return f"SenseNova API error HTTP {response.status_code}: {_redact(message, api_key)}"
    return f"SenseNova API error HTTP {response.status_code}."


def _redact(value: str, api_key: str = "") -> str:
    redacted = value.replace("Bearer ", "Bearer [REDACTED] ")
    if api_key:
        redacted = redacted.replace(api_key, "[REDACTED]")
    return redacted