Datasets:
Download code/robohome/src/engine/source/packages/generative/client.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/generative/client.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/source/packages/generative/client.py
-
curl -L -o client.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/generative/client.py
12 kB
| 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 | |
| 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 | |
| def resolved_text_base_url(self) -> str: | |
| return (self.text_base_url or self.base_url).rstrip("/") | |
| def resolved_text_api_key(self) -> str: | |
| return self.text_api_key or self.api_key | |
| 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, | |
| ) | |
| 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"}, | |
| } | |
| 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" | |
| 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 | |
| def _ensure_new_output(output: Path) -> None: | |
| if output.exists(): | |
| raise FileExistsError(f"refusing to overwrite: {output}") | |
| 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}" | |