// #nullable disable using System; 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 AssistantChatMessage : ChatMessage, IJsonModel { [Experimental("OPENAI001")] protected override ChatMessage 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 DeserializeAssistantChatMessage(document.RootElement, data, options); } default: throw new FormatException($"The model {nameof(AssistantChatMessage)} does not support reading '{options.Format}' format."); } } [Experimental("OPENAI001")] protected override 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(AssistantChatMessage)} does not support writing '{options.Format}' format."); } } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); AssistantChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (AssistantChatMessage)PersistableModelCreateCore(data, options); string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; [Experimental("OPENAI001")] protected override 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(AssistantChatMessage)} does not support writing '{format}' format."); } base.JsonModelWriteCore(writer, options); #pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. if (Optional.IsDefined(Refusal) && !Patch.Contains("$.refusal"u8)) { writer.WritePropertyName("refusal"u8); writer.WriteStringValue(Refusal); } if (Optional.IsDefined(ParticipantName) && !Patch.Contains("$.name"u8)) { writer.WritePropertyName("name"u8); writer.WriteStringValue(ParticipantName); } if (Optional.IsDefined(OutputAudioReference) && !Patch.Contains("$.audio"u8)) { writer.WritePropertyName("audio"u8); writer.WriteObjectValue(OutputAudioReference, options); } if (Patch.Contains("$.tool_calls"u8)) { if (!Patch.IsRemoved("$.tool_calls"u8)) { writer.WritePropertyName("tool_calls"u8); writer.WriteRawValue(Patch.GetJson("$.tool_calls"u8)); } } else if (Optional.IsCollectionDefined(ToolCalls)) { writer.WritePropertyName("tool_calls"u8); writer.WriteStartArray(); for (int i = 0; i < ToolCalls.Count; i++) { if (ToolCalls[i].Patch.IsRemoved("$"u8)) { continue; } writer.WriteObjectValue(ToolCalls[i], options); } Patch.WriteTo(writer, "$.tool_calls"u8); writer.WriteEndArray(); } if (Optional.IsDefined(FunctionCall) && !Patch.Contains("$.function_call"u8)) { writer.WritePropertyName("function_call"u8); writer.WriteObjectValue(FunctionCall, options); } Patch.WriteTo(writer); #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. } AssistantChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (AssistantChatMessage)JsonModelCreateCore(ref reader, options); [Experimental("OPENAI001")] protected override ChatMessage 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(AssistantChatMessage)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAssistantChatMessage(document.RootElement, null, options); } internal static AssistantChatMessage DeserializeAssistantChatMessage(JsonElement element, BinaryData data, ModelReaderWriterOptions options) { if (element.ValueKind == JsonValueKind.Null) { return null; } ChatMessageRole role = default; ChatMessageContent content = 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. string refusal = default; string participantName = default; ChatOutputAudioReference outputAudioReference = default; IList toolCalls = default; ChatFunctionCall functionCall = default; foreach (var prop in element.EnumerateObject()) { if (prop.NameEquals("role"u8)) { role = prop.Value.GetString().ToChatMessageRole(); continue; } if (prop.NameEquals("content"u8)) { DeserializeContentValue(prop, ref content, options); continue; } if (prop.NameEquals("refusal"u8)) { if (prop.Value.ValueKind == JsonValueKind.Null) { refusal = null; continue; } refusal = prop.Value.GetString(); continue; } if (prop.NameEquals("name"u8)) { participantName = prop.Value.GetString(); continue; } if (prop.NameEquals("audio"u8)) { if (prop.Value.ValueKind == JsonValueKind.Null) { outputAudioReference = null; continue; } outputAudioReference = ChatOutputAudioReference.DeserializeChatOutputAudioReference(prop.Value, prop.Value.GetUtf8Bytes(), options); continue; } if (prop.NameEquals("tool_calls"u8)) { if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatToolCall.DeserializeChatToolCall(item, item.GetUtf8Bytes(), options)); } toolCalls = array; continue; } if (prop.NameEquals("function_call"u8)) { if (prop.Value.ValueKind == JsonValueKind.Null) { functionCall = null; continue; } functionCall = ChatFunctionCall.DeserializeChatFunctionCall(prop.Value, prop.Value.GetUtf8Bytes(), options); continue; } patch.Set([.. "$."u8, .. Encoding.UTF8.GetBytes(prop.Name)], prop.Value.GetUtf8Bytes()); } return new AssistantChatMessage( role, content, patch, refusal, participantName, outputAudioReference, toolCalls ?? new ChangeTrackingList(), functionCall); } #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("audio"u8)) { return OutputAudioReference.Patch.TryGetEncodedValue([.. "$"u8, .. local.Slice("audio"u8.Length)], out value); } if (local.StartsWith("function_call"u8)) { return FunctionCall.Patch.TryGetEncodedValue([.. "$"u8, .. local.Slice("function_call"u8.Length)], out value); } if (local.StartsWith("tool_calls"u8)) { int propertyLength = "tool_calls"u8.Length; ReadOnlySpan currentSlice = local.Slice(propertyLength); if (currentSlice.IsEmpty) { return TryResolveToolCallsArray(out value); } if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed)) { return false; } return ToolCalls[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("audio"u8)) { OutputAudioReference.Patch.Set([.. "$"u8, .. local.Slice("audio"u8.Length)], value); return true; } if (local.StartsWith("function_call"u8)) { FunctionCall.Patch.Set([.. "$"u8, .. local.Slice("function_call"u8.Length)], value); return true; } if (local.StartsWith("tool_calls"u8)) { int propertyLength = "tool_calls"u8.Length; ReadOnlySpan currentSlice = local.Slice(propertyLength); if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed)) { return false; } ToolCalls[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 TryResolveToolCallsArray(out JsonPatch.EncodedValue value) { value = default; BinaryData data = ModelReaderWriter.Write(ActiveToolCalls(), 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 ActiveToolCalls() { if (!Optional.IsCollectionDefined(ToolCalls)) { yield break; } for (int i = 0; i < ToolCalls.Count; i++) { if (!ToolCalls[i].Patch.IsRemoved("$"u8)) { yield return ToolCalls[i]; } } } #pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. } }