// #nullable disable using System; using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Text.Json; using OpenAI; namespace OpenAI.Chat { public partial class ChatCompletion : IJsonModel { internal ChatCompletion() : this(null, null, default, null, default, null, null, null, default) { } [Experimental("OPENAI001")] protected virtual ChatCompletion PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) { string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions)) { return DeserializeChatCompletion(document.RootElement, data, options); } default: throw new FormatException($"The model {nameof(ChatCompletion)} does not support reading '{options.Format}' format."); } } [Experimental("OPENAI001")] protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) { string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options, OpenAIContext.Default); default: throw new FormatException($"The model {nameof(ChatCompletion)} does not support writing '{options.Format}' format."); } } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); ChatCompletion IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; [Experimental("OPENAI001")] public static explicit operator ChatCompletion(ClientResult result) { PipelineResponse response = result.GetRawResponse(); BinaryData data = response.Content; using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); return DeserializeChatCompletion(document.RootElement, data, ModelSerializationExtensions.WireOptions); } void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { #pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. if (Patch.Contains("$"u8)) { writer.WriteRawValue(Patch.GetJson("$"u8)); return; } #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. writer.WriteStartObject(); JsonModelWriteCore(writer, options); writer.WriteEndObject(); } [Experimental("OPENAI001")] protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatCompletion)} does not support writing '{format}' format."); } #pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. if (!Patch.Contains("$.id"u8)) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } if (Patch.Contains("$.choices"u8)) { if (!Patch.IsRemoved("$.choices"u8)) { writer.WritePropertyName("choices"u8); writer.WriteRawValue(Patch.GetJson("$.choices"u8)); } } else { writer.WritePropertyName("choices"u8); writer.WriteStartArray(); for (int i = 0; i < Choices.Count; i++) { if (Choices[i].Patch.IsRemoved("$"u8)) { continue; } writer.WriteObjectValue(Choices[i], options); } Patch.WriteTo(writer, "$.choices"u8); writer.WriteEndArray(); } if (!Patch.Contains("$.created"u8)) { writer.WritePropertyName("created"u8); writer.WriteNumberValue(CreatedAt, "U"); } if (!Patch.Contains("$.model"u8)) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } if (Optional.IsDefined(ServiceTier) && !Patch.Contains("$.service_tier"u8)) { writer.WritePropertyName("service_tier"u8); writer.WriteStringValue(ServiceTier.Value.ToString()); } if (Optional.IsDefined(SystemFingerprint) && !Patch.Contains("$.system_fingerprint"u8)) { writer.WritePropertyName("system_fingerprint"u8); writer.WriteStringValue(SystemFingerprint); } if (!Patch.Contains("$.object"u8)) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object); } if (Optional.IsDefined(Usage) && !Patch.Contains("$.usage"u8)) { writer.WritePropertyName("usage"u8); writer.WriteObjectValue(Usage, options); } Patch.WriteTo(writer); #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. } ChatCompletion IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); [Experimental("OPENAI001")] protected virtual ChatCompletion JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatCompletion)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatCompletion(document.RootElement, null, options); } internal static ChatCompletion DeserializeChatCompletion(JsonElement element, BinaryData data, ModelReaderWriterOptions options) { if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; IReadOnlyList choices = default; DateTimeOffset createdAt = default; string model = default; ChatServiceTier? serviceTier = default; string systemFingerprint = default; string @object = default; ChatTokenUsage usage = default; #pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. JsonPatch patch = new JsonPatch(data is null ? ReadOnlyMemory.Empty : data.ToMemory()); #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. foreach (var prop in element.EnumerateObject()) { if (prop.NameEquals("id"u8)) { id = prop.Value.GetString(); continue; } if (prop.NameEquals("choices"u8)) { List array = new List(); foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalCreateChatCompletionResponseChoice.DeserializeInternalCreateChatCompletionResponseChoice(item, item.GetUtf8Bytes(), options)); } choices = array; continue; } if (prop.NameEquals("created"u8)) { createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } if (prop.NameEquals("model"u8)) { model = prop.Value.GetString(); continue; } if (prop.NameEquals("service_tier"u8)) { if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } serviceTier = new ChatServiceTier(prop.Value.GetString()); continue; } if (prop.NameEquals("system_fingerprint"u8)) { systemFingerprint = prop.Value.GetString(); continue; } if (prop.NameEquals("object"u8)) { @object = prop.Value.GetString(); continue; } if (prop.NameEquals("usage"u8)) { if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } usage = ChatTokenUsage.DeserializeChatTokenUsage(prop.Value, prop.Value.GetUtf8Bytes(), options); continue; } patch.Set([.. "$."u8, .. Encoding.UTF8.GetBytes(prop.Name)], prop.Value.GetUtf8Bytes()); } return new ChatCompletion( id, choices, createdAt, model, serviceTier, systemFingerprint, @object, usage, patch); } #pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. private bool PropagateGet(ReadOnlySpan jsonPath, out JsonPatch.EncodedValue value) { ReadOnlySpan local = jsonPath.SliceToStartOfPropertyName(); value = default; if (local.StartsWith("usage"u8)) { return Usage.Patch.TryGetEncodedValue([.. "$"u8, .. local.Slice("usage"u8.Length)], out value); } if (local.StartsWith("choices"u8)) { int propertyLength = "choices"u8.Length; ReadOnlySpan currentSlice = local.Slice(propertyLength); if (currentSlice.IsEmpty) { return TryResolveChoicesArray(out value); } if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed)) { return false; } return Choices[index].Patch.TryGetEncodedValue([.. "$"u8, .. currentSlice.Slice(bytesConsumed)], out value); } return false; } #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. #pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. private bool PropagateSet(ReadOnlySpan jsonPath, JsonPatch.EncodedValue value) { ReadOnlySpan local = jsonPath.SliceToStartOfPropertyName(); if (local.StartsWith("usage"u8)) { Usage.Patch.Set([.. "$"u8, .. local.Slice("usage"u8.Length)], value); return true; } if (local.StartsWith("choices"u8)) { int propertyLength = "choices"u8.Length; ReadOnlySpan currentSlice = local.Slice(propertyLength); if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed)) { return false; } Choices[index].Patch.Set([.. "$"u8, .. currentSlice.Slice(bytesConsumed)], value); return true; } return false; } #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. #pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. private bool TryResolveChoicesArray(out JsonPatch.EncodedValue value) { value = default; BinaryData data = ModelReaderWriter.Write(ActiveChoices(), ModelReaderWriterOptions.Json, OpenAIContext.Default); JsonPatch tempPatch = new JsonPatch(); tempPatch.Set("$"u8, data.ToMemory().Span); return tempPatch.TryGetEncodedValue("$"u8, out value); } #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. #pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. private IEnumerable ActiveChoices() { if (!Optional.IsCollectionDefined(Choices)) { yield break; } for (int i = 0; i < Choices.Count; i++) { if (!Choices[i].Patch.IsRemoved("$"u8)) { yield return Choices[i]; } } } #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. } }