From 97cd52920918f2297c2e49e436f82d00b40e3ae4 Mon Sep 17 00:00:00 2001 From: Dev Sharma <12devsharma10c@gmail.com> Date: Thu, 31 Jul 2025 13:36:59 +0530 Subject: [PATCH] =?UTF-8?q?fix:=20prevent=20UnicodeEncodeError=20when=20ru?= =?UTF-8?q?nning=20OpenAI=20SDK=20in=20Jupyter/non=E2=80=91UTF8=20terminal?= =?UTF-8?q?s=20(#2409)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Summary Fixes #2409 by adding UTF‑8 safe printing for SDK objects and responses. Jupyter and some environments use non‑UTF8 stdout, causing `UnicodeEncodeError` in test code. ### Changes - Added `_safe_print()` for printing responses and debug data. - Updated SDK object `__repr__` methods to handle non‑UTF8 encodings. ### Why Prevents crashes in notebooks and non‑UTF8 terminals when working with Unicode data in API responses. --- src/openai/_base_client.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 3fe669259f..069b01c36e 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -58,6 +58,14 @@ HttpxRequestFiles, ModelBuilderProtocol, ) +import sys + +def _safe_print(obj): + try: + print(obj) + except UnicodeEncodeError: + sys.stdout.buffer.write((str(obj) + "\n").encode("utf-8", errors="replace")) + from ._utils import SensitiveHeadersFilter, is_dict, is_list, asyncify, is_given, lru_cache, is_mapping from ._compat import PYDANTIC_V2, model_copy, model_dump from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type @@ -111,6 +119,8 @@ except ImportError: # taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366 HTTPX_DEFAULT_TIMEOUT = Timeout(5.0) +def __repr__(self): + return str(self).encode("utf-8", errors="replace").decode() class PageInfo: