1010using System . Text . Encodings . Web ;
1111using System . Text . Json ;
1212using System . Text . Json . Serialization ;
13+ using System . Text . Json . Serialization . Metadata ;
1314using System . Threading ;
1415using System . Threading . Tasks ;
1516using Microsoft . Extensions . Logging ;
@@ -216,7 +217,8 @@ public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseA
216217 }
217218 }
218219
219- internal static string SerializeChatMessages ( IEnumerable < ChatMessage > messages , ChatFinishReason ? chatFinishReason = null )
220+ internal static string SerializeChatMessages (
221+ IEnumerable < ChatMessage > messages , ChatFinishReason ? chatFinishReason = null , JsonSerializerOptions ? customContentSerializerOptions = null )
220222 {
221223 List < object > output = [ ] ;
222224
@@ -293,10 +295,28 @@ internal static string SerializeChatMessages(IEnumerable<ChatMessage> messages,
293295 break ;
294296
295297 default :
298+ JsonElement element = _emptyObject ;
299+ try
300+ {
301+ JsonTypeInfo ? unknownContentTypeInfo =
302+ customContentSerializerOptions ? . TryGetTypeInfo ( content . GetType ( ) , out JsonTypeInfo ? ctsi ) is true ? ctsi :
303+ _defaultOptions . TryGetTypeInfo ( content . GetType ( ) , out JsonTypeInfo ? dtsi ) ? dtsi :
304+ null ;
305+
306+ if ( unknownContentTypeInfo is not null )
307+ {
308+ element = JsonSerializer . SerializeToElement ( content , unknownContentTypeInfo ) ;
309+ }
310+ }
311+ catch
312+ {
313+ // Ignore the contents of any parts that can't be serialized.
314+ }
315+
296316 m . Parts . Add ( new OtelGenericPart
297317 {
298318 Type = content . GetType ( ) . FullName ! ,
299- Content = content ,
319+ Content = element ,
300320 } ) ;
301321 break ;
302322 }
@@ -558,7 +578,7 @@ private void AddInputMessagesTags(IEnumerable<ChatMessage> messages, ChatOptions
558578
559579 _ = activity . AddTag (
560580 OpenTelemetryConsts . GenAI . Input . Messages ,
561- SerializeChatMessages ( messages ) ) ;
581+ SerializeChatMessages ( messages , customContentSerializerOptions : _jsonSerializerOptions ) ) ;
562582 }
563583 }
564584
@@ -568,7 +588,7 @@ private void AddOutputMessagesTags(ChatResponse response, Activity? activity)
568588 {
569589 _ = activity . AddTag (
570590 OpenTelemetryConsts . GenAI . Output . Messages ,
571- SerializeChatMessages ( response . Messages , response . FinishReason ) ) ;
591+ SerializeChatMessages ( response . Messages , response . FinishReason , customContentSerializerOptions : _jsonSerializerOptions ) ) ;
572592 }
573593 }
574594
@@ -609,6 +629,7 @@ private sealed class OtelFunction
609629 }
610630
611631 private static readonly JsonSerializerOptions _defaultOptions = CreateDefaultOptions ( ) ;
632+ private static readonly JsonElement _emptyObject = JsonSerializer . SerializeToElement ( new object ( ) , _defaultOptions . GetTypeInfo ( typeof ( object ) ) ) ;
612633
613634 private static JsonSerializerOptions CreateDefaultOptions ( )
614635 {
0 commit comments