File size: 12,012 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
290
291
292
293
294
295
296
297
298
299
300
301
302
from __future__ import annotations

import base64
import mimetypes
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal, cast

from openai import OpenAI


@dataclass(frozen=True)
class RelaySettings:
    base_url: str
    api_key: str
    image_model: str = "gpt-image-2"
    multimodal_model: str = "gpt-6-astra"
    multimodal_api: Literal["auto", "responses", "chat"] = "auto"
    text_base_url: str | None = None
    text_api_key: str | None = None
    reasoning_effort: Literal["low", "medium", "high", "xhigh"] | None = None
    disable_response_storage: bool = True

    @property
    def resolved_text_base_url(self) -> str:
        return (self.text_base_url or self.base_url).rstrip("/")

    @property
    def resolved_text_api_key(self) -> str:
        return self.text_api_key or self.api_key

    @classmethod
    def from_env(cls) -> RelaySettings:
        api_key, _ = cls._credential_from_env()
        if not api_key:
            raise RuntimeError(
                "IMAGE2_API_KEY is not set and no readable IMAGE2_API_KEY_FILE was found"
            )
        raw_api_mode = os.environ.get("MULTIMODAL_API", "auto").strip().casefold()
        if raw_api_mode not in {"auto", "responses", "chat"}:
            raise ValueError("MULTIMODAL_API must be auto, responses, or chat")
        api_mode = cast(Literal["auto", "responses", "chat"], raw_api_mode)
        image_base_url = os.environ.get(
            "IMAGE2_BASE_URL", "https://54-169-24-77.sslip.io/v1"
        ).rstrip("/")
        text_api_key, _ = cls._text_credential_from_env()
        raw_reasoning_effort = os.environ.get(
            "MULTIMODAL_REASONING_EFFORT",
            os.environ.get("RHG_PLANNER_REASONING_EFFORT", ""),
        ).strip().casefold()
        if raw_reasoning_effort and raw_reasoning_effort not in {
            "low",
            "medium",
            "high",
            "xhigh",
        }:
            raise ValueError("MULTIMODAL_REASONING_EFFORT must be low, medium, high, or xhigh")
        disable_storage = os.environ.get(
            "OPENAI_DISABLE_RESPONSE_STORAGE",
            os.environ.get("RHG_PLANNER_DISABLE_RESPONSE_STORAGE", "1"),
        ).casefold() in {"1", "true", "yes"}
        return cls(
            base_url=image_base_url,
            api_key=api_key,
            image_model=os.environ.get("IMAGE2_MODEL", "gpt-image-2"),
            multimodal_model=os.environ.get("MULTIMODAL_MODEL", "gpt-6-astra"),
            multimodal_api=api_mode,
            text_base_url=os.environ.get("OPENAI_BASE_URL", image_base_url).rstrip("/"),
            text_api_key=text_api_key or api_key,
            reasoning_effort=(
                cast(Literal["low", "medium", "high", "xhigh"], raw_reasoning_effort)
                if raw_reasoning_effort
                else None
            ),
            disable_response_storage=disable_storage,
        )

    @classmethod
    def status_from_env(cls) -> dict[str, object]:
        api_key, credential_source = cls._credential_from_env()
        text_api_key, text_credential_source = cls._text_credential_from_env()
        return {
            "configured": bool(api_key),
            "credential_source": credential_source,
            "base_url": os.environ.get(
                "IMAGE2_BASE_URL", "https://54-169-24-77.sslip.io/v1"
            ).rstrip("/"),
            "image_model": os.environ.get("IMAGE2_MODEL", "gpt-image-2"),
            "multimodal_model": os.environ.get("MULTIMODAL_MODEL", "gpt-6-astra"),
            "multimodal_api": os.environ.get("MULTIMODAL_API", "auto"),
            "text_base_url": os.environ.get(
                "OPENAI_BASE_URL",
                os.environ.get("IMAGE2_BASE_URL", "https://54-169-24-77.sslip.io/v1"),
            ).rstrip("/"),
            "text_configured": bool(text_api_key or api_key),
            "text_credential_source": text_credential_source or credential_source,
            "reasoning_effort": os.environ.get(
                "MULTIMODAL_REASONING_EFFORT",
                os.environ.get("RHG_PLANNER_REASONING_EFFORT"),
            ),
            "response_storage_disabled": os.environ.get(
                "OPENAI_DISABLE_RESPONSE_STORAGE",
                os.environ.get("RHG_PLANNER_DISABLE_RESPONSE_STORAGE", "1"),
            ).casefold()
            in {"1", "true", "yes"},
        }

    @staticmethod
    def _credential_from_env() -> tuple[str, str | None]:
        api_key = os.environ.get("IMAGE2_API_KEY", "").strip()
        if api_key:
            return api_key, "environment"
        key_path = Path(
            os.environ.get("IMAGE2_API_KEY_FILE", str(Path.home() / ".config/codeximage2/api_key"))
        ).expanduser()
        if not key_path.is_file():
            return "", None
        if key_path.stat().st_mode & 0o077:
            raise RuntimeError(f"IMAGE2_API_KEY_FILE must have mode 600: {key_path}")
        return key_path.read_text(encoding="utf-8").strip(), "file"

    @staticmethod
    def _text_credential_from_env() -> tuple[str, str | None]:
        api_key = os.environ.get("OPENAI_API_KEY", "").strip()
        if api_key:
            return api_key, "environment"
        key_value = os.environ.get("OPENAI_API_KEY_FILE", "").strip()
        if not key_value:
            return "", None
        key_path = Path(key_value).expanduser()
        if not key_path.is_file():
            return "", None
        if key_path.stat().st_mode & 0o077:
            raise RuntimeError(f"OPENAI_API_KEY_FILE must have mode 600: {key_path}")
        return key_path.read_text(encoding="utf-8").strip(), "file"


class GenerativeClient:
    """Small relay client that never returns or logs credentials or encoded inputs."""

    def __init__(
        self,
        settings: RelaySettings,
        client: OpenAI | None = None,
        text_client: OpenAI | None = None,
    ) -> None:
        self.settings = settings
        # Relay-specific model names are intentionally broader than the SDK's literals.
        self.client: Any = client or OpenAI(api_key=settings.api_key, base_url=settings.base_url)
        if text_client is not None:
            self.text_client: Any = text_client
        elif client is not None:
            self.text_client = client
        else:
            text_base_url = getattr(
                settings, "resolved_text_base_url", settings.base_url.rstrip("/")
            )
            text_api_key = getattr(settings, "resolved_text_api_key", settings.api_key)
            if text_base_url == settings.base_url.rstrip("/") and text_api_key == settings.api_key:
                self.text_client = self.client
            else:
                self.text_client = OpenAI(
                    api_key=text_api_key,
                    base_url=text_base_url,
                )

    def list_models(self) -> list[str]:
        return sorted(model.id for model in self.text_client.models.list().data)

    def _response_options(self) -> dict[str, Any]:
        options: dict[str, Any] = {"store": not self.settings.disable_response_storage}
        if self.settings.reasoning_effort:
            options["reasoning"] = {"effort": self.settings.reasoning_effort}
        return options

    def generate_image(
        self,
        prompt: str,
        output: Path,
        *,
        size: str = "1024x1024",
        quality: str = "high",
    ) -> Path:
        self._ensure_new_output(output)
        result = self.client.images.generate(
            model=self.settings.image_model,
            prompt=prompt,
            size=size,
            quality=quality,
        )
        encoded = result.data[0].b64_json if result.data else None
        if not encoded:
            raise RuntimeError("image relay returned no base64 image")
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_bytes(base64.b64decode(encoded, validate=True))
        return output

    def edit_image(
        self,
        source: Path,
        prompt: str,
        output: Path,
        *,
        size: str = "1024x1024",
        quality: str = "medium",
    ) -> Path:
        if not source.is_file():
            raise FileNotFoundError(source)
        self._ensure_new_output(output)
        with source.open("rb") as image:
            result = self.client.images.edit(
                model=self.settings.image_model,
                image=image,
                prompt=prompt,
                size=size,
                quality=quality,
            )
        encoded = result.data[0].b64_json if result.data else None
        if not encoded:
            raise RuntimeError("image relay returned no base64 image")
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_bytes(base64.b64decode(encoded, validate=True))
        return output

    def analyze_image(self, source: Path, prompt: str) -> str:
        image_url = self._data_url(source)
        if self.settings.multimodal_api in {"auto", "responses"}:
            try:
                response = self.text_client.responses.create(
                    model=self.settings.multimodal_model,
                    input=[
                        {
                            "role": "user",
                            "content": [
                                {"type": "input_text", "text": prompt},
                                {"type": "input_image", "image_url": image_url},
                            ],
                        }
                    ],
                    **self._response_options(),
                )
                return str(response.output_text)
            except Exception:
                if self.settings.multimodal_api == "responses":
                    raise
        response = self.text_client.chat.completions.create(
            model=self.settings.multimodal_model,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": prompt},
                        {"type": "image_url", "image_url": {"url": image_url}},
                    ],
                }
            ],
        )
        content = response.choices[0].message.content
        if not isinstance(content, str):
            raise RuntimeError("multimodal relay returned no text")
        return content

    def generate_text(self, prompt: str) -> str:
        if not prompt.strip():
            raise ValueError("text prompt cannot be empty")
        if self.settings.multimodal_api in {"auto", "responses"}:
            try:
                response = self.text_client.responses.create(
                    model=self.settings.multimodal_model,
                    input=prompt,
                    **self._response_options(),
                )
                output = str(response.output_text)
                if not output.strip():
                    raise RuntimeError("text relay returned no output")
                return output
            except Exception:
                if self.settings.multimodal_api == "responses":
                    raise
        response = self.text_client.chat.completions.create(
            model=self.settings.multimodal_model,
            messages=[{"role": "user", "content": prompt}],
        )
        content = response.choices[0].message.content
        if not isinstance(content, str) or not content.strip():
            raise RuntimeError("text relay returned no text")
        return content

    @staticmethod
    def _ensure_new_output(output: Path) -> None:
        if output.exists():
            raise FileExistsError(f"refusing to overwrite: {output}")

    @staticmethod
    def _data_url(source: Path) -> str:
        if not source.is_file():
            raise FileNotFoundError(source)
        mime_type = mimetypes.guess_type(source.name)[0] or "application/octet-stream"
        encoded = base64.b64encode(source.read_bytes()).decode("ascii")
        return f"data:{mime_type};base64,{encoded}"