From 29337aebd0709cf8466eb1426583f34e2a3ba857 Mon Sep 17 00:00:00 2001 From: PiedPiper911 <32931126+PiedPiper911@users.noreply.github.com> Date: Mon, 10 Aug 2026 19:36:02 +0800 Subject: [PATCH 1/2] Fix APIStatusError.code type to accept int values The API can return integer error codes, but the type was Optional[str]. Changed to Optional[Union[str, int]] to match runtime behavior. Fixes #3531 --- src/openai/_exceptions.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index 86f44b0e15..d61bc1684c 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Optional, cast +from typing import TYPE_CHECKING, Any, Optional, Union, cast from typing_extensions import Literal import httpx @@ -60,7 +60,7 @@ class APIError(OpenAIError): If there was no response associated with this error then it will be `None`. """ - code: Optional[str] = None + code: Optional[Union[str, int]] = None param: Optional[str] = None type: Optional[str] @@ -71,7 +71,7 @@ def __init__(self, message: str, request: httpx.Request, *, body: object | None) self.body = body if is_dict(body): - self.code = cast(Any, construct_type(type_=Optional[str], value=body.get("code"))) + self.code = cast(Any, construct_type(type_=Optional[Union[str, int]], value=body.get("code"))) self.param = cast(Any, construct_type(type_=Optional[str], value=body.get("param"))) self.type = cast(Any, construct_type(type_=str, value=body.get("type"))) else: From 836264224a26b93cb1fa14c1358aa4cd5dbc3d21 Mon Sep 17 00:00:00 2001 From: PiedPiper911 <32931126+PiedPiper911@users.noreply.github.com> Date: Wed, 12 Aug 2026 13:46:06 +0800 Subject: [PATCH 2/2] fix: bypass construct_type for code field to preserve int values under Pydantic v1 --- src/openai/_exceptions.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index d61bc1684c..40adff6de2 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -71,7 +71,8 @@ def __init__(self, message: str, request: httpx.Request, *, body: object | None) self.body = body if is_dict(body): - self.code = cast(Any, construct_type(type_=Optional[Union[str, int]], value=body.get("code"))) + code_value = body.get("code") + self.code = code_value if isinstance(code_value, (str, int)) else None self.param = cast(Any, construct_type(type_=Optional[str], value=body.get("param"))) self.type = cast(Any, construct_type(type_=str, value=body.get("type"))) else: