22
33import json
44from dataclasses import dataclass
5+ from pprint import pformat
56from typing import Any , Literal , Optional
67
78ImageContentTypes = Literal [
@@ -154,7 +155,7 @@ def __str__(self):
154155 args_str = self ._arguments_str ()
155156 func_call = f"{ self .name } ({ args_str } )"
156157 comment = f"# tool request ({ self .id } )"
157- return f"\n ```python\n { comment } \n { func_call } \n ```\n "
158+ return f"```python\n { comment } \n { func_call } \n ```\n "
158159
159160 def _repr_markdown_ (self ):
160161 return self .__str__ ()
@@ -195,10 +196,20 @@ class ContentToolResult(Content):
195196 value : Any = None
196197 error : Optional [str ] = None
197198
199+ def _get_value_and_language (self ) -> tuple [str , str ]:
200+ if self .error :
201+ return f"Tool calling failed with error: '{ self .error } '" , ""
202+ try :
203+ json_val = json .loads (self .value )
204+ return pformat (json_val , indent = 2 , sort_dicts = False ), "python"
205+ except : # noqa: E722
206+ return str (self .value ), ""
207+
198208 def __str__ (self ):
199209 comment = f"# tool result ({ self .id } )"
200- val = self .get_final_value ()
201- return f"""\n ```python\n { comment } \n "{ val } "\n ```\n """
210+ value , language = self ._get_value_and_language ()
211+
212+ return f"""```{ language } \n { comment } \n { value } \n ```"""
202213
203214 def _repr_markdown_ (self ):
204215 return self .__str__ ()
@@ -211,9 +222,8 @@ def __repr__(self, indent: int = 0):
211222 return res + ">"
212223
213224 def get_final_value (self ) -> str :
214- if self .error :
215- return f"Tool calling failed with error: '{ self .error } '"
216- return str (self .value )
225+ value , _language = self ._get_value_and_language ()
226+ return value
217227
218228
219229@dataclass
@@ -236,7 +246,7 @@ def __str__(self):
236246 return json .dumps (self .value , indent = 2 )
237247
238248 def _repr_markdown_ (self ):
239- return f"""\n ```json\n { self .__str__ ()} \n ```\n """
249+ return f"""```json\n { self .__str__ ()} \n ```"""
240250
241251 def __repr__ (self , indent : int = 0 ):
242252 return " " * indent + f"<ContentJson value={ self .value } >"
0 commit comments