Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/openai/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,9 @@ def _idempotency_key(self) -> str:

class _DefaultHttpxClient(httpx.Client):
def __init__(self, **kwargs: Any) -> None:
from ._utils import sanitize_proxy_env_vars

sanitize_proxy_env_vars()
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
kwargs.setdefault("follow_redirects", True)
Expand Down Expand Up @@ -1420,6 +1423,9 @@ def get_api_list(

class _DefaultAsyncHttpxClient(httpx.AsyncClient):
def __init__(self, **kwargs: Any) -> None:
from ._utils import sanitize_proxy_env_vars

sanitize_proxy_env_vars()
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
kwargs.setdefault("follow_redirects", True)
Expand All @@ -1437,6 +1443,9 @@ def __init__(self, **_kwargs: Any) -> None:

class _DefaultAioHttpClient(httpx_aiohttp.HttpxAiohttpClient): # type: ignore
def __init__(self, **kwargs: Any) -> None:
from ._utils import sanitize_proxy_env_vars

sanitize_proxy_env_vars()
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
kwargs.setdefault("follow_redirects", True)
Expand Down
13 changes: 9 additions & 4 deletions src/openai/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,8 +657,11 @@ def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]
if not is_mapping(value):
return value

_, items_type = get_args(type_) # Dict[_, items_type]
return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}
dict_args = get_args(type_)
if len(dict_args) >= 2:
items_type = dict_args[1]
return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}
return dict(value)

if (
not is_literal_type(type_)
Expand All @@ -678,8 +681,10 @@ def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]
if not is_list(value):
return value

inner_type = args[0] # List[inner_type]
return [construct_type(value=entry, type_=inner_type) for entry in value]
if args:
inner_type = args[0] # List[inner_type]
return [construct_type(value=entry, type_=inner_type) for entry in value]
return list(value)

if origin == float:
if isinstance(value, int):
Expand Down
32 changes: 24 additions & 8 deletions src/openai/_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,10 @@ def __stream__(self) -> Iterator[_T]:
if sse.data.startswith("[DONE]"):
break

# we have to special case the Assistants `thread.` events since we won't have an "event" key in the data
if sse.event and sse.event.startswith("thread."):
# Handle error events first - these can occur outside of thread.* events
if sse.event == "error":

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve Assistants error payloads

When a beta Assistants stream emits its generated ErrorEvent, the SSE frame uses event: error with the ErrorObject fields (message, type, etc.) at the top level of the data, not nested under error. This new catch-all path therefore raises a generic APIError before the synthesized-event path can cast and deliver that ErrorEvent to AssistantEventHandler.on_event, so users of threads/runs streaming lose the actual server message and any custom error-event handling. Please either handle the top-level error-object shape here or let synthesized streams process those events as before.

Useful? React with 👍 / 👎.

data = sse.json()

if sse.event == "error" and is_mapping(data) and data.get("error"):
if is_mapping(data) and data.get("error"):
message = None
error = data.get("error")
if is_mapping(error):
Expand All @@ -80,7 +79,16 @@ def __stream__(self) -> Iterator[_T]:
request=self.response.request,
body=data["error"],
)
# If error event doesn't have expected structure, still raise
raise APIError(
message="An error occurred during streaming",
request=self.response.request,
body=data,
)

# we have to special case the Assistants `thread.` events since we won't have an "event" key in the data
if sse.event and sse.event.startswith("thread."):
data = sse.json()
yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response)
else:
data = sse.json()
Expand Down Expand Up @@ -173,11 +181,10 @@ async def __stream__(self) -> AsyncIterator[_T]:
if sse.data.startswith("[DONE]"):
break

# we have to special case the Assistants `thread.` events since we won't have an "event" key in the data
if sse.event and sse.event.startswith("thread."):
# Handle error events first - these can occur outside of thread.* events
if sse.event == "error":
data = sse.json()

if sse.event == "error" and is_mapping(data) and data.get("error"):
if is_mapping(data) and data.get("error"):
message = None
error = data.get("error")
if is_mapping(error):
Expand All @@ -190,7 +197,16 @@ async def __stream__(self) -> AsyncIterator[_T]:
request=self.response.request,
body=data["error"],
)
# If error event doesn't have expected structure, still raise
raise APIError(
message="An error occurred during streaming",
request=self.response.request,
body=data,
)

# we have to special case the Assistants `thread.` events since we won't have an "event" key in the data
if sse.event and sse.event.startswith("thread."):
data = sse.json()
yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response)
else:
data = sse.json()
Expand Down
1 change: 1 addition & 0 deletions src/openai/_utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
get_async_library as get_async_library,
maybe_coerce_float as maybe_coerce_float,
get_required_header as get_required_header,
sanitize_proxy_env_vars as sanitize_proxy_env_vars,
maybe_coerce_boolean as maybe_coerce_boolean,
maybe_coerce_integer as maybe_coerce_integer,
is_async_azure_client as is_async_azure_client,
Expand Down
26 changes: 22 additions & 4 deletions src/openai/_utils/_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,11 @@ def _transform_recursive(
return _transform_typeddict(data, stripped_type)

if origin == dict and is_mapping(data):
items_type = get_args(stripped_type)[1]
return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
args = get_args(stripped_type)
if len(args) >= 2:
items_type = args[1]
return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
return dict(data)

if (
# List[T]
Expand All @@ -196,6 +199,12 @@ def _transform_recursive(
if isinstance(data, dict):
return cast(object, data)

# bare list/iterable/sequence with no type args - return as-is
if not get_args(stripped_type):
if is_list(data):
return data
return list(data)

inner_type = extract_type_arg(stripped_type, 0)
if _no_transform_needed(inner_type):
# for some types there is no need to transform anything, so we can get a small
Expand Down Expand Up @@ -346,8 +355,11 @@ async def _async_transform_recursive(
return await _async_transform_typeddict(data, stripped_type)

if origin == dict and is_mapping(data):
items_type = get_args(stripped_type)[1]
return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
args = get_args(stripped_type)
if len(args) >= 2:
items_type = args[1]
return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
return dict(data)

if (
# List[T]
Expand All @@ -362,6 +374,12 @@ async def _async_transform_recursive(
if isinstance(data, dict):
return cast(object, data)

# bare list/iterable/sequence with no type args - return as-is
if not get_args(stripped_type):
if is_list(data):
return data
return list(data)

inner_type = extract_type_arg(stripped_type, 0)
if _no_transform_needed(inner_type):
# for some types there is no need to transform anything, so we can get a small
Expand Down
29 changes: 29 additions & 0 deletions src/openai/_utils/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,3 +447,32 @@ def is_async_azure_client(client: object) -> TypeGuard[AsyncAzureOpenAI]:
from ..lib.azure import AsyncAzureOpenAI

return isinstance(client, AsyncAzureOpenAI)


_PROXY_ENV_VARS = (
"HTTP_PROXY",
"http_proxy",
"HTTPS_PROXY",
"https_proxy",
"ALL_PROXY",
"all_proxy",
"NO_PROXY",
"no_proxy",
)


def sanitize_proxy_env_vars() -> None:
"""Sanitize proxy-related environment variables by removing newline characters.

This works around an issue where httpx's proxy parsing only splits by comma
and fails with InvalidURL when newlines are present in the value.
"""
for var in _PROXY_ENV_VARS:
value = os.environ.get(var)
if value and ("\n" in value or "\r" in value):
sanitized = ",".join(
part.strip()
for part in value.replace("\n", ",").replace("\r", ",").split(",")
if part.strip()
)
os.environ[var] = sanitized
6 changes: 3 additions & 3 deletions src/openai/lib/_parsing/_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def parse_response(
) -> ParsedResponse[TextFormatT]:
output_list: List[ParsedResponseOutputItem[TextFormatT]] = []

for output in response.output:
for output in (response.output or []):
if output.type == "message":
content_list: List[ParsedContent[TextFormatT]] = []
for item in output.content:
Expand All @@ -71,7 +71,7 @@ def parse_response(
type_=ParsedResponseOutputText[TextFormatT],
value={
**item.to_dict(),
"parsed": parse_text(item.text, text_format=text_format),
"parsed": parse_text(item.text, text_format=text_format) if item.text is not None else None,
},
)
)
Expand Down Expand Up @@ -140,7 +140,7 @@ def parse_response(


def parse_text(text: str, text_format: type[TextFormatT] | Omit) -> TextFormatT | None:
if not is_given(text_format):
if not is_given(text_format) or text_format is None:
return None

if is_basemodel_type(text_format):
Expand Down
2 changes: 1 addition & 1 deletion src/openai/types/responses/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ def output_text(self) -> str:
for output in self.output:
if output.type == "message":
for content in output.content:
if content.type == "output_text":
if content.type == "output_text" and content.text is not None:
texts.append(content.text)

return "".join(texts)
14 changes: 9 additions & 5 deletions src/openai/types/responses/response_function_web_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@
class ActionSearchSource(BaseModel):
"""A source used in the search."""

type: Literal["url"]
"""The type of source. Always `url`."""
type: Literal["url", "api"]
"""The type of source. `url` for a web page, `api` for a built-in OpenAI data source."""

url: str
"""The URL of the source."""
url: Optional[str] = None
"""The URL of the source. Present when type is `url`."""

name: Optional[str] = None
"""The name of the built-in data source (e.g. `oai-weather`, `oai-sports`, `oai-finance`).
Present when type is `api`."""


class ActionSearch(BaseModel):
Expand Down Expand Up @@ -78,7 +82,7 @@ class ResponseFunctionWebSearch(BaseModel):
id: str
"""The unique ID of the web search tool call."""

action: Action
action: Optional[Action] = None
"""
An object describing the specific action taken in this web search call. Includes
details on how the model used the web (search, open_page, find_in_page).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,15 @@
class ActionSearchSource(TypedDict, total=False):
"""A source used in the search."""

type: Required[Literal["url"]]
"""The type of source. Always `url`."""
type: Required[Literal["url", "api"]]
"""The type of source. `url` for a web page, `api` for a built-in OpenAI data source."""

url: Required[str]
"""The URL of the source."""
url: str
"""The URL of the source. Required when type is `url`."""

name: str
"""The name of the built-in data source (e.g. `oai-weather`, `oai-sports`, `oai-finance`).
Required when type is `api`."""


class ActionSearch(TypedDict, total=False):
Expand Down
Loading