99import os
1010import tempfile
1111import threading
12- from collections .abc import AsyncIterable , AsyncIterator , Generator , Mapping , Sequence
12+ from collections .abc import AsyncIterable , AsyncIterator , Generator , Sequence
1313from contextlib import suppress
14+ from dataclasses import asdict , is_dataclass
1415from pathlib import Path
1516from typing import Protocol , cast
1617
@@ -1394,11 +1395,20 @@ def _convert_message_content(content: MessageContent) -> Content:
13941395# region Output Item Conversion
13951396
13961397
1397- def _arguments_to_str (arguments : str | Mapping [str , Any ] | None ) -> str :
1398+ def _argument_json_default (value : Any ) -> Any :
1399+ if is_dataclass (value ) and not isinstance (value , type ):
1400+ return asdict (value )
1401+ to_dict = getattr (value , "to_dict" , None )
1402+ if callable (to_dict ):
1403+ return to_dict ()
1404+ raise TypeError (f"Object of type { type (value ).__name__ } is not JSON serializable" )
1405+
1406+
1407+ def _arguments_to_str (arguments : Any | None ) -> str :
13981408 """Convert arguments to a JSON string.
13991409
14001410 Args:
1401- arguments: The arguments to convert, can be a string, mapping , or None.
1411+ arguments: The arguments to convert, can be a string, JSON-like object , or None.
14021412
14031413 Returns:
14041414 The arguments as a JSON string.
@@ -1407,7 +1417,7 @@ def _arguments_to_str(arguments: str | Mapping[str, Any] | None) -> str:
14071417 return ""
14081418 if isinstance (arguments , str ):
14091419 return arguments
1410- return json .dumps (arguments )
1420+ return json .dumps (arguments , default = _argument_json_default )
14111421
14121422
14131423async def _to_outputs (
0 commit comments