Spaces:
Running on Zero
Running on Zero
Switch GPT client to GLM-5.3-Flash
Browse filesFiles changed (2)
28 unmodified lines293031323334353637383910 unmodified lines5051525354555657585917 unmodified lines7778798081828384858687888990919293949548 unmodified lines14414514614714814915015115223 unmodified lines1761771781791801811821831841853 unmodified lines1891901911921931941952 unmodified lines19819920020120220320420520620720820921021121221348 unmodified lines26226326426526626777 unmodified lines34534634734834935035135235335454 unmodified lines40941041141241341441541641741841942042142242342442542642742842943043143243310 unmodified lines44444544644744844945045145245345445545645745845946046146217 unmodified lines48048148248348448548648748848949058 unmodified lines54955055155255355428 unmodified linesimport openaiimport yamlfrom openai import AzureOpenAI, OpenAI # pip install openaifrom PIL import Imagefrom tenacity import (retry,retry_if_not_exception_type,stop_after_attempt,stop_after_delay,wait_random_exponential,10 unmodified linesCONFIG_FILE = str(Path(__file__).with_name("gpt_config.yaml"))DEFAULT_GPT_TIMEOUT = float(os.environ.get("GPT_TIMEOUT", 90))# GPT-5.x counts reasoning tokens against this cap, so it must be high# enough to leave room for both reasoning and the visible reply.GPT5_DEFAULT_MAX_COMPLETION_TOKENS = 8192_CODEX_DEFAULT_REASONING_EFFORT = "medium"_CODEX_ENV_KEYS = {"ALL_PROXY","CODEX_HOME",17 unmodified linesif provider_override is not None:agent_config = {}return {"endpoint": environ.get("ENDPOINT", agent_config.get("endpoint")),"api_key": environ.get("API_KEY", agent_config.get("api_key")),"api_version": environ.get("API_VERSION", agent_config.get("api_version")),"model_name": environ.get("MODEL_NAME", agent_config.get("model_name")),"provider": provider_override or agent_config.get("provider"),}def _codex_subprocess_environment() -> dict[str, str]:"""Return the minimal host environment required by Codex CLI."""return {48 unmodified linescheck_connection (bool, optional): Whether to check API connection.verbose (bool, optional): Enable verbose logging.timeout (float, optional): Max seconds for a single GPT request.provider (str, optional): Backend provider. Use ``codex`` to reuse alocal Codex CLI login; otherwise the existing Azure/OpenAI-compatible API selection is preserved.Example:```sh23 unmodified linesverbose: bool = False,timeout: float = DEFAULT_GPT_TIMEOUT,provider: Optional[str] = None,):self.provider = (provider or ("azure" if api_version else "openai")).lower()self.codex_executable = Noneif self.provider == "codex":self.codex_executable = shutil.which("codex")3 unmodified lines"`codex login` before using the Codex provider.")self.client = Noneelif self.provider == "azure" or api_version is not None:self.client = AzureOpenAI(azure_endpoint=endpoint,api_key=api_key,2 unmodified linesmax_retries=0,)else:self.client = OpenAI(base_url=endpoint,api_key=api_key,timeout=timeout,max_retries=0,)self.endpoint = endpointself.model_name = model_nameself.timeout = timeoutself.image_formats = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}self.verbose = verboseif check_connection:48 unmodified lines) from excreturn targetdef _query_codex(self,text_prompt: str,77 unmodified linesname = (model_name or "").lower()return "gpt-5" in name or "gpt5" in name@retry(retry=retry_if_not_exception_type(openai.BadRequestError),wait=wait_random_exponential(min=1, max=10),stop=stop_after_attempt(5) | stop_after_delay(DEFAULT_GPT_TIMEOUT),)def completion_with_backoff(self, **kwargs):"""Performs a chat completion request with retry/backoff."""54 unmodified linesif "openrouter" in self.endpoint:image_base64 = combine_images_to_grid(image_base64)for img in image_base64:if isinstance(img, Image.Image):buffer = BytesIO()img.save(buffer, format=img.format or "PNG")buffer.seek(0)image_binary = buffer.read()img = base64.b64encode(image_binary).decode("utf-8")elif (len(os.path.splitext(img)) > 1and os.path.splitext(img)[-1].lower() in self.image_formats):if not os.path.exists(img):raise FileNotFoundError(f"Image file not found: {img}")with open(img, "rb") as f:img = base64.b64encode(f.read()).decode("utf-8")content_user.append({"type": "image_url","image_url": {"url": f"data:image/png;base64,{img}"},})10 unmodified lines"model": self.model_name,}else:payload = {"messages": [{"role": "system", "content": system_role},{"role": "user", "content": content_user},],"temperature": 0.1,"max_tokens": 500,"top_p": 0.1,"frequency_penalty": 0,"presence_penalty": 0,"stop": None,"model": self.model_name,}if params:params = dict(params)17 unmodified linespayload.update(params)response = Nonetry:response = self.completion_with_backoff(**payload)response = response.choices[0].message.contentexcept Exception as e:logger.error(f"Error GPTclint {self.endpoint} API call: {e}")response = Noneif self.verbose:58 unmodified linescheck_connection=False,timeout=DEFAULT_GPT_TIMEOUT,provider=settings["provider"],)28 unmodified lines29303132333435363738394010 unmodified lines515253545556575859606162636465666768697071727374757677787917 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514648 unmodified lines19519619719819920020120220320420520623 unmodified lines2302312322332342352362372382392402412423 unmodified lines2462472482492502512522532542552 unmodified lines25825926026126226326426526626726826927027127227327427527627727827928048 unmodified lines32933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344477 unmodified lines52252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155254 unmodified lines60760860961061161261361461561661761861962062162262362462562662762810 unmodified lines63964064164264364464564664764864965065165265365465565665765865966066166266366466517 unmodified lines68368468568668768868969069169269369469569669769869970070158 unmodified lines76076176276376476576628 unmodified linesimport openaiimport yamlfrom huggingface_hub import get_tokenfrom openai import AzureOpenAI, OpenAI # pip install openaifrom PIL import Imagefrom tenacity import (retry,retry_if_exception,stop_after_attempt,stop_after_delay,wait_random_exponential,10 unmodified linesCONFIG_FILE = str(Path(__file__).with_name("gpt_config.yaml"))DEFAULT_GPT_TIMEOUT = float(os.environ.get("GPT_TIMEOUT", 90))DEFAULT_HF_ENDPOINT = "https://router.huggingface.co/v1"DEFAULT_HF_MODEL = "zai-org/GLM-5.3-Flash:baseten"HF_MAX_IMAGE_DIMENSION = int(os.environ.get("HF_MAX_IMAGE_DIMENSION", 1024))HF_IMAGE_JPEG_QUALITY = int(os.environ.get("HF_IMAGE_JPEG_QUALITY", 90))OPENAI_MAX_IMAGE_DIMENSION = int(os.environ.get("OPENAI_MAX_IMAGE_DIMENSION", 1024))# GPT-5.x counts reasoning tokens against this cap, so it must be high# enough to leave room for both reasoning and the visible reply.GPT5_DEFAULT_MAX_COMPLETION_TOKENS = 8192REASONING_VLM_DEFAULT_MAX_TOKENS = int(os.environ.get("REASONING_VLM_MAX_TOKENS", 2048))_CODEX_DEFAULT_REASONING_EFFORT = "medium"_HF_PROVIDERS = {"hf", "huggingface"}_OPENAI_COMPATIBLE_PROVIDERS = {"openai", *_HF_PROVIDERS}_NON_RETRYABLE_API_ERRORS = (openai.AuthenticationError,openai.BadRequestError,openai.NotFoundError,openai.PermissionDeniedError,openai.UnprocessableEntityError,)_CODEX_ENV_KEYS = {"ALL_PROXY","CODEX_HOME",17 unmodified linesif provider_override is not None:agent_config = {}endpoint = environ.get("ENDPOINT", agent_config.get("endpoint"))provider = provider_override or agent_config.get("provider")provider_name = (provider or "").lower()is_huggingface = provider_name in _HF_PROVIDERS or (endpoint is not None and "router.huggingface.co" in endpoint)if is_huggingface:provider = "huggingface"endpoint = endpoint or DEFAULT_HF_ENDPOINTapi_key = environ.get("API_KEY")if api_key is None and is_huggingface:api_key = environ.get("HF_TOKEN") or environ.get("HUGGING_FACE_HUB_TOKEN") or get_token()if api_key is None:api_key = agent_config.get("api_key")api_version = environ.get("API_VERSION", agent_config.get("api_version"))if is_huggingface:api_version = Nonereturn {"endpoint": endpoint,"api_key": api_key,"api_version": api_version,"model_name": environ.get("MODEL_NAME")or agent_config.get("model_name")or (DEFAULT_HF_MODEL if is_huggingface else None),"provider": provider,"bill_to": environ.get("HF_BILL_TO") if is_huggingface else None,}def _is_retryable_api_error(error: BaseException) -> bool:"""Return whether an API failure may succeed when retried."""if isinstance(error, _NON_RETRYABLE_API_ERRORS):return Falsestatus_code = getattr(error, "status_code", None)if status_code is not None and 400 <= status_code < 500:return status_code in {408, 409, 429}return Truedef _codex_subprocess_environment() -> dict[str, str]:"""Return the minimal host environment required by Codex CLI."""return {48 unmodified linescheck_connection (bool, optional): Whether to check API connection.verbose (bool, optional): Enable verbose logging.timeout (float, optional): Max seconds for a single GPT request.provider (str, optional): Backend provider. Use ``huggingface`` forHugging Face Inference Providers or ``codex`` to reuse a localCodex CLI login; otherwise the existing Azure/OpenAI-compatibleAPI selection is preserved.bill_to (str, optional): Hugging Face organization charged for routedrequests. Ignored by other providers.Example:```sh23 unmodified linesverbose: bool = False,timeout: float = DEFAULT_GPT_TIMEOUT,provider: Optional[str] = None,bill_to: Optional[str] = None,):self.provider = (provider or ("azure" if api_version else "openai")).lower()if self.provider == "hf":self.provider = "huggingface"self.codex_executable = Noneif self.provider == "codex":self.codex_executable = shutil.which("codex")3 unmodified lines"`codex login` before using the Codex provider.")self.client = Noneelif self.provider == "azure" or (self.provider not in _OPENAI_COMPATIBLE_PROVIDERSand api_version is not None):self.client = AzureOpenAI(azure_endpoint=endpoint,api_key=api_key,2 unmodified linesmax_retries=0,)else:client_kwargs = {"base_url": endpoint,"api_key": api_key,"timeout": timeout,"max_retries": 0,}if self.provider == "huggingface" and bill_to:client_kwargs["default_headers"] = {"X-HF-Bill-To": bill_to}self.client = OpenAI(**client_kwargs)self.endpoint = endpointself.model_name = model_nameself.bill_to = bill_to if self.provider == "huggingface" else Noneself.timeout = timeoutself.last_usage = Noneself.image_formats = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}self.verbose = verboseif check_connection:48 unmodified lines) from excreturn targetdef _prepare_huggingface_image(self, image: str | Image.Image) -> str:"""Encode one image as a compact data URL for Hugging Face."""if isinstance(image, str) and image.startswith("data:"):return imageif isinstance(image, Image.Image):prepared_image = image.copy()elif isinstance(image, str):source = Path(image).expanduser()try:source_is_file = source.is_file()except OSError:source_is_file = Falseif not source_is_file:if source.suffix.lower() in self.image_formats:raise FileNotFoundError(f"Image file not found: {image}")return f"data:image/png;base64,{image}"try:with Image.open(source) as source_image:prepared_image = source_image.copy()except OSError as exc:raise ValueError(f"Invalid image file: {image}") from excelse:raise TypeError("Image input must be a path, base64 string, or PIL Image")prepared_image.thumbnail((HF_MAX_IMAGE_DIMENSION, HF_MAX_IMAGE_DIMENSION),Image.Resampling.LANCZOS,)has_alpha = prepared_image.mode in {"LA", "RGBA"} or (prepared_image.mode == "P" and "transparency" in prepared_image.info)buffer = BytesIO()if has_alpha:prepared_image.convert("RGBA").save(buffer,format="PNG",optimize=True,)mime_type = "image/png"else:prepared_image.convert("RGB").save(buffer,format="JPEG",quality=HF_IMAGE_JPEG_QUALITY,optimize=True,)mime_type = "image/jpeg"encoded = base64.b64encode(buffer.getvalue()).decode("utf-8")return f"data:{mime_type};base64,{encoded}"def _prepare_openai_image(self, image: str | Image.Image) -> str:"""Encode visible pixels as PNG for OpenAI-compatible APIs."""if isinstance(image, Image.Image):prepared_image = image.copy()elif isinstance(image, str):source = Path(image).expanduser()try:source_is_file = source.is_file()except OSError:source_is_file = Falseif source_is_file:try:with Image.open(source) as source_image:prepared_image = source_image.copy()except OSError as exc:raise ValueError(f"Invalid image file: {image}") from excelse:if source.suffix.lower() in self.image_formats:raise FileNotFoundError(f"Image file not found: {image}")encoded = imageif image.startswith("data:"):header, separator, encoded = image.partition(",")if not separator or ";base64" not in header.lower():raise ValueError("Image data URI must contain base64 data")try:image_data = base64.b64decode(encoded, validate=True)with Image.open(BytesIO(image_data)) as decoded_image:prepared_image = decoded_image.copy()except (OSError, ValueError) as exc:raise ValueError("Image input is neither an existing image nor valid ""base64") from excelse:raise TypeError("Image input must be a path, base64 string, or PIL Image")prepared_image.thumbnail((OPENAI_MAX_IMAGE_DIMENSION, OPENAI_MAX_IMAGE_DIMENSION),Image.Resampling.LANCZOS,)has_alpha = prepared_image.mode in {"LA", "RGBA"} or (prepared_image.mode == "P" and "transparency" in prepared_image.info)if has_alpha:foreground = prepared_image.convert("RGBA")background = Image.new("RGBA", foreground.size, (0, 0, 0, 255))prepared_image = Image.alpha_composite(background, foreground)buffer = BytesIO()prepared_image.convert("RGB").save(buffer, format="PNG", optimize=True)encoded = base64.b64encode(buffer.getvalue()).decode("utf-8")return f"data:image/png;base64,{encoded}"def _query_codex(self,text_prompt: str,77 unmodified linesname = (model_name or "").lower()return "gpt-5" in name or "gpt5" in name@staticmethoddef _is_reasoning_vlm(model_name: str) -> bool:name = (model_name or "").lower()return any(model in namefor model in ("glm-4.5v", "glm-5.3-flash", "kimi-k3"))@staticmethoddef _default_top_p(model_name: str) -> float:name = (model_name or "").lower()return 0.95 if "kimi-k3" in name else 0.1@staticmethoddef _default_reasoning_effort(model_name: str) -> str | None:name = (model_name or "").lower()if "glm-5.3-flash" in name:return "max"return "low" if "kimi-k3" in name else None@retry(retry=retry_if_exception(_is_retryable_api_error),wait=wait_random_exponential(min=1, max=10),stop=stop_after_attempt(5) | stop_after_delay(DEFAULT_GPT_TIMEOUT),reraise=True,)def completion_with_backoff(self, **kwargs):"""Performs a chat completion request with retry/backoff."""54 unmodified linesif "openrouter" in self.endpoint:image_base64 = combine_images_to_grid(image_base64)for img in image_base64:if self.provider == "huggingface":content_user.append({"type": "image_url","image_url": {"url": self._prepare_huggingface_image(img)},})continuecontent_user.append({"type": "image_url","image_url": {"url": self._prepare_openai_image(img)},})10 unmodified lines"model": self.model_name,}else:max_tokens = (REASONING_VLM_DEFAULT_MAX_TOKENSif self._is_reasoning_vlm(self.model_name)else 500)payload = {"messages": [{"role": "system", "content": system_role},{"role": "user", "content": content_user},],"temperature": 0.1,"max_tokens": max_tokens,"top_p": self._default_top_p(self.model_name),"frequency_penalty": 0,"presence_penalty": 0,"stop": None,"model": self.model_name,}reasoning_effort = self._default_reasoning_effort(self.model_name)if reasoning_effort is not None:payload["reasoning_effort"] = reasoning_effortif params:params = dict(params)17 unmodified linespayload.update(params)response = Noneself.last_usage = Nonetry:completion = self.completion_with_backoff(**payload)usage = getattr(completion, "usage", None)if usage is not None:self.last_usage = (usage.model_dump()if hasattr(usage, "model_dump")else dict(usage))response = completion.choices[0].message.contentexcept Exception as e:logger.error(f"Error GPTclient {self.endpoint} API call: {e}")response = Noneif self.verbose:58 unmodified linescheck_connection=False,timeout=DEFAULT_GPT_TIMEOUT,provider=settings["provider"],bill_to=settings["bill_to"],)
123456789101112131415161718192021222324252627# config.yamlagent_type: "gpt-5.4" # gpt-4o, gpt-5.4 or gemma-4-31b or codexgpt-4o:endpoint: https://xxx.openai.azure.comapi_key: xxxapi_version: 2025-xx-xxmodel_name: yfb-gpt-4ogpt-5.4:endpoint: https://yfb-openai-sweden.openai.azure.com/api_key: xxxapi_version: 2024-12-01-previewmodel_name: gpt-5.4gemma-4-31b:endpoint: https://openrouter.ai/api/v1api_key: sk-or-v1-xxxapi_version: nullmodel_name: google/gemma-4-31b-it:freecodex:provider: codexendpoint: nullapi_key: nullapi_version: nullmodel_name: null123456789# config.yamlagent_type: "glm-5.3-flash"glm-5.3-flash:provider: huggingfaceendpoint: https://router.huggingface.co/v1api_key: nullapi_version: nullmodel_name: zai-org/GLM-5.3-Flash:baseten
embodied_gen/utils/gpt_clients.py+254-42
embodied_gen/utils/gpt_config.yaml+5-23