@@ -46,35 +46,36 @@ class FileArtifact(BaseModel):
4646 filename : str
4747 contents : str | bytes = Field (exclude = True )
4848
49- @staticmethod
50- def coerce_contents (value : io .BytesIO | str | bytes ) -> bytes :
49+ @field_validator ("contents" , mode = "before" )
50+ @classmethod
51+ def validate_contents (cls , value : io .BytesIO | str | bytes ):
5152 if isinstance (value , io .BytesIO ):
5253 return value .getvalue ()
5354 if isinstance (value , str ):
5455 return value .encode ("utf-8" )
5556 return value
5657
57- @field_validator ("contents" , mode = "before" )
58- @classmethod
59- def contents_conformer (cls , value ):
60- return cls .coerce_contents (value )
61-
6258 def log_model (self , log_path : str , encoding : Optional [str ] = None ) -> None :
6359 """Log the file contents to disk.
6460
6561 Args:
6662 log_path (str): path to write the file
67- encoding (str | None): if None, writes as binary
63+ encoding (str | None): if None, auto-detect binary or not
6864 """
6965 log_name = os .path .join (log_path , self .filename )
70- contents = self .coerce_contents ( self . contents )
66+ contents = self .contents
7167
72- if encoding is None :
73- with open (log_name , "wb" ) as f :
74- f .write (contents )
75- else :
68+ if encoding :
7669 with open (log_name , "w" , encoding = encoding ) as f :
7770 f .write (contents .decode (encoding ))
71+ else :
72+ try :
73+ decoded = contents .decode ("utf-8" )
74+ with open (log_name , "w" , encoding = "utf-8" ) as f :
75+ f .write (decoded )
76+ except UnicodeDecodeError :
77+ with open (log_name , "wb" ) as f :
78+ f .write (contents )
7879
7980 def contents_str (self ) -> str :
8081 """Safe string representation of contents (for logs)."""
0 commit comments