openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
6b3c8b0a3d3208218dc3cbcd295502024988a956

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/Generated/Models/Chat/AssistantChatMessage.Serialization.cs

272lines · modepreview

// <auto-generated/>

#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<AssistantChatMessage>
    {
        [Experimental("OPENAI001")]
        protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<AssistantChatMessage>)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<AssistantChatMessage>.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<AssistantChatMessage>)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<byte>.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<ChatToolCall> 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);
                    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<ChatToolCall> array = new List<ChatToolCall>();
                    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<ChatToolCall>(),
                functionCall);
        }

        BinaryData IPersistableModel<AssistantChatMessage>.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options);

        [Experimental("OPENAI001")]
        protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<AssistantChatMessage>)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.");
            }
        }

        AssistantChatMessage IPersistableModel<AssistantChatMessage>.Create(BinaryData data, ModelReaderWriterOptions options) => (AssistantChatMessage)PersistableModelCreateCore(data, options);

        [Experimental("OPENAI001")]
        protected override ChatMessage PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<AssistantChatMessage>)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.");
            }
        }

        string IPersistableModel<AssistantChatMessage>.GetFormatFromOptions(ModelReaderWriterOptions options) => "J";

#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
        private bool PropagateGet(ReadOnlySpan<byte> jsonPath, out JsonPatch.EncodedValue value)
        {
            ReadOnlySpan<byte> 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<byte> currentSlice = local.Slice(propertyLength);
                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<byte> jsonPath, JsonPatch.EncodedValue value)
        {
            ReadOnlySpan<byte> 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<byte> 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.
    }
}