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
5 changes: 4 additions & 1 deletion src/openai/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,10 @@ 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]
if len(args) < 2:
return value

_, items_type = args # Dict[_, items_type]
return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}

if (
Expand Down
12 changes: 10 additions & 2 deletions src/openai/_utils/_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +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]
args = get_args(stripped_type)
if len(args) < 2:
return data

items_type = args[1]
return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}

if (
Expand Down Expand Up @@ -346,7 +350,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]
args = get_args(stripped_type)
if len(args) < 2:
return data

items_type = args[1]
return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}

if (
Expand Down
4 changes: 4 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,10 @@ class Model(BaseModel):
assert m.value == "foo"


def test_construct_bare_dict_type() -> None:
assert construct_type(value={"key": "value"}, type_=dict) == {"key": "value"}


def test_discriminated_unions_invalid_data() -> None:
class A(BaseModel):
type: Literal["a"]
Expand Down
12 changes: 12 additions & 0 deletions tests/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,18 @@ class DictItems(TypedDict):
assert await transform({"foo": {"foo_baz": "bar"}}, Dict[str, DictItems], use_async) == {"foo": {"fooBaz": "bar"}}


class BareDictParam(TypedDict):
metadata: dict


@parametrize
@pytest.mark.asyncio
async def test_bare_dictionary_annotation(use_async: bool) -> None:
data = {"metadata": {"foo_bar": "bar"}}

assert await transform(data, BareDictParam, use_async) == data


class TypedDictIterableUnionStr(TypedDict):
foo: Annotated[Union[str, Iterable[Baz8]], PropertyInfo(alias="FOO")]

Expand Down