-
Notifications
You must be signed in to change notification settings - Fork 863
Expand file tree
/
Copy pathOpenTelemetryChatClient.cs
More file actions
723 lines (621 loc) · 28.9 KB
/
OpenTelemetryChatClient.cs
File metadata and controls
723 lines (621 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Shared.Diagnostics;
#pragma warning disable CA1307 // Specify StringComparison for clarity
#pragma warning disable CA1308 // Normalize strings to uppercase
#pragma warning disable SA1111 // Closing parenthesis should be on line of last parameter
#pragma warning disable SA1113 // Comma should be on the same line as previous parameter
namespace Microsoft.Extensions.AI;
/// <summary>Represents a delegating chat client that implements the OpenTelemetry Semantic Conventions for Generative AI systems.</summary>
/// <remarks>
/// This class provides an implementation of the Semantic Conventions for Generative AI systems v1.38, defined at <see href="https://opentelemetry.io/docs/specs/semconv/gen-ai/" />.
/// The specification is still experimental and subject to change; as such, the telemetry output by this client is also subject to change.
/// </remarks>
public sealed partial class OpenTelemetryChatClient : DelegatingChatClient
{
private readonly ActivitySource _activitySource;
private readonly Meter _meter;
private readonly Histogram<int> _tokenUsageHistogram;
private readonly Histogram<double> _operationDurationHistogram;
private readonly string? _defaultModelId;
private readonly string? _providerName;
private readonly string? _serverAddress;
private readonly int _serverPort;
private JsonSerializerOptions _jsonSerializerOptions;
/// <summary>Initializes a new instance of the <see cref="OpenTelemetryChatClient"/> class.</summary>
/// <param name="innerClient">The underlying <see cref="IChatClient"/>.</param>
/// <param name="logger">The <see cref="ILogger"/> to use for emitting any logging data from the client.</param>
/// <param name="sourceName">An optional source name that will be used on the telemetry data.</param>
#pragma warning disable IDE0060 // Remove unused parameter; it exists for backwards compatibility and future use
public OpenTelemetryChatClient(IChatClient innerClient, ILogger? logger = null, string? sourceName = null)
#pragma warning restore IDE0060
: base(innerClient)
{
Debug.Assert(innerClient is not null, "Should have been validated by the base ctor");
if (innerClient!.GetService<ChatClientMetadata>() is ChatClientMetadata metadata)
{
_defaultModelId = metadata.DefaultModelId;
_providerName = metadata.ProviderName;
_serverAddress = metadata.ProviderUri?.Host;
_serverPort = metadata.ProviderUri?.Port ?? 0;
}
string name = string.IsNullOrEmpty(sourceName) ? OpenTelemetryConsts.DefaultSourceName : sourceName!;
_activitySource = new(name);
_meter = new(name);
_tokenUsageHistogram = _meter.CreateHistogram<int>(
OpenTelemetryConsts.GenAI.Client.TokenUsage.Name,
OpenTelemetryConsts.TokensUnit,
OpenTelemetryConsts.GenAI.Client.TokenUsage.Description
#if NET9_0_OR_GREATER
, advice: new() { HistogramBucketBoundaries = OpenTelemetryConsts.GenAI.Client.TokenUsage.ExplicitBucketBoundaries }
#endif
);
_operationDurationHistogram = _meter.CreateHistogram<double>(
OpenTelemetryConsts.GenAI.Client.OperationDuration.Name,
OpenTelemetryConsts.SecondsUnit,
OpenTelemetryConsts.GenAI.Client.OperationDuration.Description
#if NET9_0_OR_GREATER
, advice: new() { HistogramBucketBoundaries = OpenTelemetryConsts.GenAI.Client.OperationDuration.ExplicitBucketBoundaries }
#endif
);
_jsonSerializerOptions = AIJsonUtilities.DefaultOptions;
}
/// <summary>Gets or sets JSON serialization options to use when formatting chat data into telemetry strings.</summary>
public JsonSerializerOptions JsonSerializerOptions
{
get => _jsonSerializerOptions;
set => _jsonSerializerOptions = Throw.IfNull(value);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_activitySource.Dispose();
_meter.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Gets or sets a value indicating whether potentially sensitive information should be included in telemetry.
/// </summary>
/// <value>
/// <see langword="true"/> if potentially sensitive information should be included in telemetry;
/// <see langword="false"/> if telemetry shouldn't include raw inputs and outputs.
/// The default value is <see langword="false"/>, unless the <c>OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT</c>
/// environment variable is set to "true" (case-insensitive).
/// </value>
/// <remarks>
/// By default, telemetry includes metadata, such as token counts, but not raw inputs
/// and outputs, such as message content, function call arguments, and function call results.
/// The default value can be overridden by setting the <c>OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT</c>
/// environment variable to "true". Explicitly setting this property will override the environment variable.
/// </remarks>
public bool EnableSensitiveData { get; set; } = TelemetryHelpers.EnableSensitiveDataDefault;
/// <inheritdoc/>
public override object? GetService(Type serviceType, object? serviceKey = null) =>
serviceType == typeof(ActivitySource) ? _activitySource :
base.GetService(serviceType, serviceKey);
/// <inheritdoc/>
public override async Task<ChatResponse> GetResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
{
_ = Throw.IfNull(messages);
_jsonSerializerOptions.MakeReadOnly();
using Activity? activity = CreateAndConfigureActivity(options);
Stopwatch? stopwatch = _operationDurationHistogram.Enabled ? Stopwatch.StartNew() : null;
string? requestModelId = options?.ModelId ?? _defaultModelId;
AddInputMessagesTags(messages, options, activity);
ChatResponse? response = null;
Exception? error = null;
try
{
response = await base.GetResponseAsync(messages, options, cancellationToken);
return response;
}
catch (Exception ex)
{
error = ex;
throw;
}
finally
{
TraceResponse(activity, requestModelId, response, error, stopwatch);
}
}
/// <inheritdoc/>
public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
_ = Throw.IfNull(messages);
_jsonSerializerOptions.MakeReadOnly();
using Activity? activity = CreateAndConfigureActivity(options);
Stopwatch? stopwatch = _operationDurationHistogram.Enabled ? Stopwatch.StartNew() : null;
string? requestModelId = options?.ModelId ?? _defaultModelId;
AddInputMessagesTags(messages, options, activity);
IAsyncEnumerable<ChatResponseUpdate> updates;
try
{
updates = base.GetStreamingResponseAsync(messages, options, cancellationToken);
}
catch (Exception ex)
{
TraceResponse(activity, requestModelId, response: null, ex, stopwatch);
throw;
}
var responseEnumerator = updates.GetAsyncEnumerator(cancellationToken);
List<ChatResponseUpdate> trackedUpdates = [];
Exception? error = null;
try
{
while (true)
{
ChatResponseUpdate update;
try
{
if (!await responseEnumerator.MoveNextAsync())
{
break;
}
update = responseEnumerator.Current;
}
catch (Exception ex)
{
error = ex;
throw;
}
trackedUpdates.Add(update);
yield return update;
Activity.Current = activity; // workaround for https://github.com/dotnet/runtime/issues/47802
}
}
finally
{
TraceResponse(activity, requestModelId, trackedUpdates.ToChatResponse(), error, stopwatch);
await responseEnumerator.DisposeAsync();
}
}
internal static string SerializeChatMessages(
IEnumerable<ChatMessage> messages, ChatFinishReason? chatFinishReason = null, JsonSerializerOptions? customContentSerializerOptions = null)
{
List<object> output = [];
string? finishReason =
chatFinishReason?.Value is null ? null :
chatFinishReason == ChatFinishReason.Length ? "length" :
chatFinishReason == ChatFinishReason.ContentFilter ? "content_filter" :
chatFinishReason == ChatFinishReason.ToolCalls ? "tool_call" :
"stop";
foreach (ChatMessage message in messages)
{
OtelMessage m = new()
{
FinishReason = finishReason,
Role =
message.Role == ChatRole.Assistant ? "assistant" :
message.Role == ChatRole.Tool ? "tool" :
message.Role == ChatRole.System || message.Role == new ChatRole("developer") ? "system" :
"user",
Name = message.AuthorName,
};
foreach (AIContent content in message.Contents)
{
switch (content)
{
// These are all specified in the convention:
case TextContent tc when !string.IsNullOrWhiteSpace(tc.Text):
m.Parts.Add(new OtelGenericPart { Content = tc.Text });
break;
case TextReasoningContent trc when !string.IsNullOrWhiteSpace(trc.Text):
m.Parts.Add(new OtelGenericPart { Type = "reasoning", Content = trc.Text });
break;
case FunctionCallContent fcc:
m.Parts.Add(new OtelToolCallRequestPart
{
Id = fcc.CallId,
Name = fcc.Name,
Arguments = fcc.Arguments,
});
break;
case FunctionResultContent frc:
m.Parts.Add(new OtelToolCallResponsePart
{
Id = frc.CallId,
Response = frc.Result,
});
break;
case DataContent dc:
m.Parts.Add(new OtelBlobPart
{
Content = dc.Base64Data.ToString(),
MimeType = dc.MediaType,
Modality = DeriveModalityFromMediaType(dc.MediaType),
});
break;
case UriContent uc:
m.Parts.Add(new OtelUriPart
{
Uri = uc.Uri.AbsoluteUri,
MimeType = uc.MediaType,
Modality = DeriveModalityFromMediaType(uc.MediaType),
});
break;
case HostedFileContent fc:
m.Parts.Add(new OtelFilePart
{
FileId = fc.FileId,
MimeType = fc.MediaType,
Modality = DeriveModalityFromMediaType(fc.MediaType),
});
break;
// These are non-standard and are using the "generic" non-text part that provides an extensibility mechanism:
case HostedVectorStoreContent vsc:
m.Parts.Add(new OtelGenericPart { Type = "vector_store", Content = vsc.VectorStoreId });
break;
case ErrorContent ec:
m.Parts.Add(new OtelGenericPart { Type = "error", Content = ec.Message });
break;
default:
JsonElement element = _emptyObject;
try
{
JsonTypeInfo? unknownContentTypeInfo =
customContentSerializerOptions?.TryGetTypeInfo(content.GetType(), out JsonTypeInfo? ctsi) is true ? ctsi :
_defaultOptions.TryGetTypeInfo(content.GetType(), out JsonTypeInfo? dtsi) ? dtsi :
null;
if (unknownContentTypeInfo is not null)
{
element = JsonSerializer.SerializeToElement(content, unknownContentTypeInfo);
}
}
catch
{
// Ignore the contents of any parts that can't be serialized.
}
m.Parts.Add(new OtelGenericPart
{
Type = content.GetType().FullName!,
Content = element,
});
break;
}
}
output.Add(m);
}
return JsonSerializer.Serialize(output, _defaultOptions.GetTypeInfo(typeof(IList<object>)));
}
private static string? DeriveModalityFromMediaType(string? mediaType)
{
if (mediaType is not null)
{
int pos = mediaType.IndexOf('/');
if (pos >= 0)
{
ReadOnlySpan<char> topLevel = mediaType.AsSpan(0, pos);
return
topLevel.Equals("image", StringComparison.OrdinalIgnoreCase) ? "image" :
topLevel.Equals("audio", StringComparison.OrdinalIgnoreCase) ? "audio" :
topLevel.Equals("video", StringComparison.OrdinalIgnoreCase) ? "video" :
null;
}
}
return null;
}
/// <summary>Creates an activity for a chat request, or returns <see langword="null"/> if not enabled.</summary>
private Activity? CreateAndConfigureActivity(ChatOptions? options)
{
Activity? activity = null;
if (_activitySource.HasListeners())
{
string? modelId = options?.ModelId ?? _defaultModelId;
activity = _activitySource.StartActivity(
string.IsNullOrWhiteSpace(modelId) ? OpenTelemetryConsts.GenAI.ChatName : $"{OpenTelemetryConsts.GenAI.ChatName} {modelId}",
ActivityKind.Client);
if (activity is { IsAllDataRequested: true })
{
_ = activity
.AddTag(OpenTelemetryConsts.GenAI.Operation.Name, OpenTelemetryConsts.GenAI.ChatName)
.AddTag(OpenTelemetryConsts.GenAI.Request.Model, modelId)
.AddTag(OpenTelemetryConsts.GenAI.Provider.Name, _providerName);
if (_serverAddress is not null)
{
_ = activity
.AddTag(OpenTelemetryConsts.Server.Address, _serverAddress)
.AddTag(OpenTelemetryConsts.Server.Port, _serverPort);
}
if (options is not null)
{
if (options.ConversationId is string conversationId)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Conversation.Id, conversationId);
}
if (options.FrequencyPenalty is float frequencyPenalty)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Request.FrequencyPenalty, frequencyPenalty);
}
if (options.MaxOutputTokens is int maxTokens)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Request.MaxTokens, maxTokens);
}
if (options.PresencePenalty is float presencePenalty)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Request.PresencePenalty, presencePenalty);
}
if (options.Seed is long seed)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Request.Seed, seed);
}
if (options.StopSequences is IList<string> { Count: > 0 } stopSequences)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Request.StopSequences, $"[{string.Join(", ", stopSequences.Select(s => $"\"{s}\""))}]");
}
if (options.Temperature is float temperature)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Request.Temperature, temperature);
}
if (options.TopK is int topK)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Request.TopK, topK);
}
if (options.TopP is float top_p)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Request.TopP, top_p);
}
if (options.ResponseFormat is not null)
{
switch (options.ResponseFormat)
{
case ChatResponseFormatText:
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Output.Type, OpenTelemetryConsts.TypeText);
break;
case ChatResponseFormatJson:
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Output.Type, OpenTelemetryConsts.TypeJson);
break;
}
}
if (EnableSensitiveData)
{
if (options.Tools is { Count: > 0 })
{
_ = activity.AddTag(
OpenTelemetryConsts.GenAI.Tool.Definitions,
JsonSerializer.Serialize(options.Tools.Select(t => t switch
{
_ when t.GetService<AIFunctionDeclaration>() is { } af => new OtelFunction
{
Name = af.Name,
Description = af.Description,
Parameters = af.JsonSchema,
},
_ => new OtelFunction { Type = t.Name },
}), OtelContext.Default.IEnumerableOtelFunction));
}
// Log all additional request options as raw values on the span.
// Since AdditionalProperties has undefined meaning, we treat it as potentially sensitive data.
if (options.AdditionalProperties is { } props)
{
foreach (KeyValuePair<string, object?> prop in props)
{
_ = activity.AddTag(prop.Key, prop.Value);
}
}
}
}
}
}
return activity;
}
/// <summary>Adds chat response information to the activity.</summary>
private void TraceResponse(
Activity? activity,
string? requestModelId,
ChatResponse? response,
Exception? error,
Stopwatch? stopwatch)
{
if (_operationDurationHistogram.Enabled && stopwatch is not null)
{
TagList tags = default;
AddMetricTags(ref tags, requestModelId, response);
if (error is not null)
{
tags.Add(OpenTelemetryConsts.Error.Type, error.GetType().FullName);
}
_operationDurationHistogram.Record(stopwatch.Elapsed.TotalSeconds, tags);
}
if (_tokenUsageHistogram.Enabled && response?.Usage is { } usage)
{
if (usage.InputTokenCount is long inputTokens)
{
TagList tags = default;
tags.Add(OpenTelemetryConsts.GenAI.Token.Type, OpenTelemetryConsts.TokenTypeInput);
AddMetricTags(ref tags, requestModelId, response);
_tokenUsageHistogram.Record((int)inputTokens, tags);
}
if (usage.OutputTokenCount is long outputTokens)
{
TagList tags = default;
tags.Add(OpenTelemetryConsts.GenAI.Token.Type, OpenTelemetryConsts.TokenTypeOutput);
AddMetricTags(ref tags, requestModelId, response);
_tokenUsageHistogram.Record((int)outputTokens, tags);
}
}
if (error is not null)
{
_ = activity?
.AddTag(OpenTelemetryConsts.Error.Type, error.GetType().FullName)
.SetStatus(ActivityStatusCode.Error, error.Message);
}
if (response is not null)
{
AddOutputMessagesTags(response, activity);
if (activity is not null)
{
if (response.FinishReason is ChatFinishReason finishReason)
{
#pragma warning disable CA1308 // Normalize strings to uppercase
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Response.FinishReasons, $"[\"{finishReason.Value.ToLowerInvariant()}\"]");
#pragma warning restore CA1308
}
if (!string.IsNullOrWhiteSpace(response.ResponseId))
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Response.Id, response.ResponseId);
}
if (response.ModelId is not null)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Response.Model, response.ModelId);
}
if (response.Usage?.InputTokenCount is long inputTokens)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Usage.InputTokens, (int)inputTokens);
}
if (response.Usage?.OutputTokenCount is long outputTokens)
{
_ = activity.AddTag(OpenTelemetryConsts.GenAI.Usage.OutputTokens, (int)outputTokens);
}
// Log all additional response properties as raw values on the span.
// Since AdditionalProperties has undefined meaning, we treat it as potentially sensitive data.
if (EnableSensitiveData && response.AdditionalProperties is { } props)
{
foreach (KeyValuePair<string, object?> prop in props)
{
_ = activity.AddTag(prop.Key, prop.Value);
}
}
}
}
void AddMetricTags(ref TagList tags, string? requestModelId, ChatResponse? response)
{
tags.Add(OpenTelemetryConsts.GenAI.Operation.Name, OpenTelemetryConsts.GenAI.ChatName);
if (requestModelId is not null)
{
tags.Add(OpenTelemetryConsts.GenAI.Request.Model, requestModelId);
}
tags.Add(OpenTelemetryConsts.GenAI.Provider.Name, _providerName);
if (_serverAddress is string endpointAddress)
{
tags.Add(OpenTelemetryConsts.Server.Address, endpointAddress);
tags.Add(OpenTelemetryConsts.Server.Port, _serverPort);
}
if (response?.ModelId is string responseModel)
{
tags.Add(OpenTelemetryConsts.GenAI.Response.Model, responseModel);
}
}
}
private void AddInputMessagesTags(IEnumerable<ChatMessage> messages, ChatOptions? options, Activity? activity)
{
if (EnableSensitiveData && activity is { IsAllDataRequested: true })
{
if (!string.IsNullOrWhiteSpace(options?.Instructions))
{
_ = activity.AddTag(
OpenTelemetryConsts.GenAI.SystemInstructions,
JsonSerializer.Serialize(new object[1] { new OtelGenericPart { Content = options!.Instructions } }, _defaultOptions.GetTypeInfo(typeof(IList<object>))));
}
_ = activity.AddTag(
OpenTelemetryConsts.GenAI.Input.Messages,
SerializeChatMessages(messages, customContentSerializerOptions: _jsonSerializerOptions));
}
}
private void AddOutputMessagesTags(ChatResponse response, Activity? activity)
{
if (EnableSensitiveData && activity is { IsAllDataRequested: true })
{
_ = activity.AddTag(
OpenTelemetryConsts.GenAI.Output.Messages,
SerializeChatMessages(response.Messages, response.FinishReason, customContentSerializerOptions: _jsonSerializerOptions));
}
}
private sealed class OtelMessage
{
public string? Role { get; set; }
public string? Name { get; set; }
public List<object> Parts { get; set; } = [];
public string? FinishReason { get; set; }
}
private sealed class OtelGenericPart
{
public string Type { get; set; } = "text";
public object? Content { get; set; } // should be a string when Type == "text"
}
private sealed class OtelBlobPart
{
public string Type { get; set; } = "blob";
public string? Content { get; set; } // base64-encoded binary data
public string? MimeType { get; set; }
public string? Modality { get; set; }
}
private sealed class OtelUriPart
{
public string Type { get; set; } = "uri";
public string? Uri { get; set; }
public string? MimeType { get; set; }
public string? Modality { get; set; }
}
private sealed class OtelFilePart
{
public string Type { get; set; } = "file";
public string? FileId { get; set; }
public string? MimeType { get; set; }
public string? Modality { get; set; }
}
private sealed class OtelToolCallRequestPart
{
public string Type { get; set; } = "tool_call";
public string? Id { get; set; }
public string? Name { get; set; }
public IDictionary<string, object?>? Arguments { get; set; }
}
private sealed class OtelToolCallResponsePart
{
public string Type { get; set; } = "tool_call_response";
public string? Id { get; set; }
public object? Response { get; set; }
}
private sealed class OtelFunction
{
public string Type { get; set; } = "function";
public string? Name { get; set; }
public string? Description { get; set; }
public JsonElement? Parameters { get; set; }
}
private static readonly JsonSerializerOptions _defaultOptions = CreateDefaultOptions();
private static readonly JsonElement _emptyObject = JsonSerializer.SerializeToElement(new object(), _defaultOptions.GetTypeInfo(typeof(object)));
private static JsonSerializerOptions CreateDefaultOptions()
{
JsonSerializerOptions options = new(OtelContext.Default.Options)
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);
options.MakeReadOnly();
return options;
}
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower,
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(IList<object>))]
[JsonSerializable(typeof(OtelMessage))]
[JsonSerializable(typeof(OtelGenericPart))]
[JsonSerializable(typeof(OtelBlobPart))]
[JsonSerializable(typeof(OtelUriPart))]
[JsonSerializable(typeof(OtelFilePart))]
[JsonSerializable(typeof(OtelToolCallRequestPart))]
[JsonSerializable(typeof(OtelToolCallResponsePart))]
[JsonSerializable(typeof(IEnumerable<OtelFunction>))]
private sealed partial class OtelContext : JsonSerializerContext;
}